@opentiny/next-sdk 0.2.4 → 0.2.6

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,41 +1,41 @@
1
- (function(br,Mn){typeof exports=="object"&&typeof module<"u"?Mn(exports):typeof define=="function"&&define.amd?define(["exports"],Mn):(br=typeof globalThis<"u"?globalThis:br||self,Mn(br.WebAgent={}))})(this,(function(br){"use strict";var Mn="vercel.ai.error",A_=Symbol.for(Mn),qu,Lu,he=class R_ extends(Lu=Error,qu=A_,Lu){constructor({name:t,message:r,cause:n}){super(r),this[qu]=!0,this.name=t,this.cause=n}static isInstance(t){return R_.hasMarker(t,Mn)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},ju="AI_APICallError",Uu=`vercel.ai.error.${ju}`,q_=Symbol.for(Uu),Du,zu,ut=class extends(zu=he,Du=q_,zu){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:ju,message:t,cause:i}),this[Du]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return he.hasMarker(t,Uu)}},Fu="AI_EmptyResponseBodyError",Vu=`vercel.ai.error.${Fu}`,L_=Symbol.for(Vu),Zu,Bu,j_=class extends(Bu=he,Zu=L_,Bu){constructor({message:t="Empty response body"}={}){super({name:Fu,message:t}),this[Zu]=!0}static isInstance(t){return he.hasMarker(t,Vu)}};function on(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Hu="AI_InvalidArgumentError",Ju=`vercel.ai.error.${Hu}`,U_=Symbol.for(Ju),Gu,Wu,Ku=class extends(Wu=he,Gu=U_,Wu){constructor({message:t,cause:r,argument:n}){super({name:Hu,message:t,cause:r}),this[Gu]=!0,this.argument=n}static isInstance(t){return he.hasMarker(t,Ju)}},Yu="AI_InvalidPromptError",Qu=`vercel.ai.error.${Yu}`,D_=Symbol.for(Qu),Xu,ed,sn=class extends(ed=he,Xu=D_,ed){constructor({prompt:e,message:t,cause:r}){super({name:Yu,message:`Invalid prompt: ${t}`,cause:r}),this[Xu]=!0,this.prompt=e}static isInstance(e){return he.hasMarker(e,Qu)}},td="AI_InvalidResponseDataError",rd=`vercel.ai.error.${td}`,z_=Symbol.for(rd),nd,od,bi=class extends(od=he,nd=z_,od){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:td,message:r}),this[nd]=!0,this.data=t}static isInstance(t){return he.hasMarker(t,rd)}},sd="AI_JSONParseError",ad=`vercel.ai.error.${sd}`,F_=Symbol.for(ad),id,ld,fs=class extends(ld=he,id=F_,ld){constructor({text:t,cause:r}){super({name:sd,message:`JSON parsing failed: Text: ${t}.
2
- Error message: ${on(r)}`,cause:r}),this[id]=!0,this.text=t}static isInstance(t){return he.hasMarker(t,ad)}},cd="AI_LoadAPIKeyError",ud=`vercel.ai.error.${cd}`,V_=Symbol.for(ud),dd,pd,hs=class extends(pd=he,dd=V_,pd){constructor({message:t}){super({name:cd,message:t}),this[dd]=!0}static isInstance(t){return he.hasMarker(t,ud)}},fd="AI_TooManyEmbeddingValuesForCallError",hd=`vercel.ai.error.${fd}`,Z_=Symbol.for(hd),md,gd,B_=class extends(gd=he,md=Z_,gd){constructor(e){super({name:fd,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[md]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return he.hasMarker(e,hd)}},yd="AI_TypeValidationError",_d=`vercel.ai.error.${yd}`,H_=Symbol.for(_d),vd,wd,an=class Ou extends(wd=he,vd=H_,wd){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:yd,message:`${o}: Value: ${JSON.stringify(t)}.
3
- Error message: ${on(r)}`,cause:r}),this[vd]=!0,this.value=t,this.context=n}static isInstance(t){return he.hasMarker(t,_d)}static wrap({value:t,cause:r,context:n}){var o,s,a;return Ou.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((s=r.context)==null?void 0:s.entityName)===n?.entityName&&((a=r.context)==null?void 0:a.entityId)===n?.entityId?r:new Ou({value:t,cause:r,context:n})}},bd="AI_UnsupportedFunctionalityError",kd=`vercel.ai.error.${bd}`,J_=Symbol.for(kd),Cd,Td,dr=class extends(Td=he,Cd=J_,Td){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:bd,message:r}),this[Cd]=!0,this.functionality=t}static isInstance(t){return he.hasMarker(t,kd)}};const Sd=Object.freeze({status:"aborted"});function J(e,t,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const c=r?.Parent?new s:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class uo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Id={};function qr(e){return Id}function xd(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function G_(e,t){return typeof t=="bigint"?t.toString():t}function ki(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ci(e){return e==null}function Ti(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function W_(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function Ze(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function ms(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function po(e){return JSON.stringify(e)}const Ed=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const K_=ki(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ys(e){if(gs(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(gs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Y_=new Set(["string","number","symbol"]);function fo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ln(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function de(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Q_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const X_={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 ev(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return ln(e,{...e._zod.def,shape:r,checks:[]})}function tv(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return ln(e,{...e._zod.def,shape:r,checks:[]})}function rv(e,t){if(!ys(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return ms(this,"shape",n),n},checks:[]};return ln(e,r)}function nv(e,t){return ln(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return ms(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function ov(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(const s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return ln(t,{...t._zod.def,shape:o,checks:[]})}function sv(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return ln(t,{...t._zod.def,shape:o,checks:[]})}function ho(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function cn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function _s(e){return typeof e=="string"?e:e?.message}function Lr(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=_s(e.inst?._zod.def?.error?.(e))??_s(t?.error?.(e))??_s(r.customError?.(e))??_s(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Si(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function mo(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const $d=(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,G_,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Rd=J("$ZodError",$d),Pd=J("$ZodError",$d,{Parent:Error});function av(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function iv(e,t){const r=t||function(s){return s.message},n={_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)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),n}const lv=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new uo;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>Lr(l,s,qr())));throw Ed(i,o?.callee),i}return a.value},cv=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>Lr(l,s,qr())));throw Ed(i,o?.callee),i}return a.value},Md=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new uo;return s.issues.length?{success:!1,error:new(e??Rd)(s.issues.map(a=>Lr(a,o,qr())))}:{success:!0,data:s.value}},Nd=Md(Pd),Od=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Lr(a,o,qr())))}:{success:!0,data:s.value}},uv=Od(Pd),dv=/^[cC][^\s-]{8,}$/,pv=/^[0-9a-z]+$/,fv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,hv=/^[0-9a-vA-V]{20}$/,mv=/^[A-Za-z0-9]{27}$/,gv=/^[a-zA-Z0-9_-]{21}$/,yv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,_v=/^([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})$/,Ad=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)$/,vv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,wv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function bv(){return new RegExp(wv,"u")}const kv=/^(?:(?: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])$/,Cv=/^(([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})$/,Tv=/^((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])$/,Sv=/^(([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])$/,Iv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qd=/^[A-Za-z0-9_-]*$/,xv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Ev=/^\+(?:[0-9]){6,14}[0-9]$/,Ld="(?:(?:\\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])))",$v=new RegExp(`^${Ld}$`);function jd(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 Rv(e){return new RegExp(`^${jd(e)}$`)}function Pv(e){const t=jd({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Ld}T(?:${n})$`)}const Mv=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Nv=/^\d+$/,Ov=/^-?\d+(?:\.\d+)?/i,Av=/true|false/i,qv=/null/i,Lv=/^[^A-Z]*$/,jv=/^[^a-z]*$/,Nt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ud={number:"number",bigint:"bigint",object:"date"},Dd=J("$ZodCheckLessThan",(e,t)=>{Nt.init(e,t);const r=Ud[typeof t.value];e._zod.onattach.push(n=>{const o=n._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=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),zd=J("$ZodCheckGreaterThan",(e,t)=>{Nt.init(e,t);const r=Ud[typeof t.value];e._zod.onattach.push(n=>{const o=n._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=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Uv=J("$ZodCheckMultipleOf",(e,t)=>{Nt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):W_(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Dv=J("$ZodCheckNumberFormat",(e,t)=>{Nt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=X_[t.format];e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,i.minimum=o,i.maximum=s,r&&(i.pattern=Nv)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}i<o&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),zv=J("$ZodCheckMaxLength",(e,t)=>{var r;Nt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ci(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const a=Si(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Fv=J("$ZodCheckMinLength",(e,t)=>{var r;Nt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ci(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const a=Si(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Vv=J("$ZodCheckLengthEquals",(e,t)=>{var r;Nt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ci(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const a=Si(o),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),vs=J("$ZodCheckStringFormat",(e,t)=>{var r,n;Nt.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?(r=e._zod).check??(r.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})}):(n=e._zod).check??(n.check=()=>{})}),Zv=J("$ZodCheckRegex",(e,t)=>{vs.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Bv=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Lv),vs.init(e,t)}),Hv=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=jv),vs.init(e,t)}),Jv=J("$ZodCheckIncludes",(e,t)=>{Nt.init(e,t);const r=fo(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),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})}}),Gv=J("$ZodCheckStartsWith",(e,t)=>{Nt.init(e,t);const r=new RegExp(`^${fo(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Wv=J("$ZodCheckEndsWith",(e,t)=>{Nt.init(e,t);const r=new RegExp(`.*${fo(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Kv=J("$ZodCheckOverwrite",(e,t)=>{Nt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Yv{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 n=t.split(`
1
+ (function(Pr,Un){typeof exports=="object"&&typeof module<"u"?Un(exports):typeof define=="function"&&define.amd?define(["exports"],Un):(Pr=typeof globalThis<"u"?globalThis:Pr||self,Un(Pr.WebAgent={}))})(this,(function(Pr){"use strict";var Un="vercel.ai.error",ev=Symbol.for(Un),Xu,ed,me=class W_ extends(ed=Error,Xu=ev,ed){constructor({name:t,message:r,cause:n}){super(r),this[Xu]=!0,this.name=t,this.cause=n}static isInstance(t){return W_.hasMarker(t,Un)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},td="AI_APICallError",rd=`vercel.ai.error.${td}`,tv=Symbol.for(rd),nd,od,st=class extends(od=me,nd=tv,od){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:td,message:t,cause:i}),this[nd]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return me.hasMarker(t,rd)}},sd="AI_EmptyResponseBodyError",ad=`vercel.ai.error.${sd}`,rv=Symbol.for(ad),id,ld,nv=class extends(ld=me,id=rv,ld){constructor({message:t="Empty response body"}={}){super({name:sd,message:t}),this[id]=!0}static isInstance(t){return me.hasMarker(t,ad)}};function mn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var cd="AI_InvalidArgumentError",ud=`vercel.ai.error.${cd}`,ov=Symbol.for(ud),dd,pd,fd=class extends(pd=me,dd=ov,pd){constructor({message:t,cause:r,argument:n}){super({name:cd,message:t,cause:r}),this[dd]=!0,this.argument=n}static isInstance(t){return me.hasMarker(t,ud)}},hd="AI_InvalidPromptError",md=`vercel.ai.error.${hd}`,sv=Symbol.for(md),gd,yd,gn=class extends(yd=me,gd=sv,yd){constructor({prompt:e,message:t,cause:r}){super({name:hd,message:`Invalid prompt: ${t}`,cause:r}),this[gd]=!0,this.prompt=e}static isInstance(e){return me.hasMarker(e,md)}},_d="AI_InvalidResponseDataError",vd=`vercel.ai.error.${_d}`,av=Symbol.for(vd),wd,bd,Di=class extends(bd=me,wd=av,bd){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:_d,message:r}),this[wd]=!0,this.data=t}static isInstance(t){return me.hasMarker(t,vd)}},kd="AI_JSONParseError",Cd=`vercel.ai.error.${kd}`,iv=Symbol.for(Cd),Td,Sd,Is=class extends(Sd=me,Td=iv,Sd){constructor({text:t,cause:r}){super({name:kd,message:`JSON parsing failed: Text: ${t}.
2
+ Error message: ${mn(r)}`,cause:r}),this[Td]=!0,this.text=t}static isInstance(t){return me.hasMarker(t,Cd)}},Id="AI_LoadAPIKeyError",xd=`vercel.ai.error.${Id}`,lv=Symbol.for(xd),Ed,$d,xs=class extends($d=me,Ed=lv,$d){constructor({message:t}){super({name:Id,message:t}),this[Ed]=!0}static isInstance(t){return me.hasMarker(t,xd)}},Rd="AI_TooManyEmbeddingValuesForCallError",Pd=`vercel.ai.error.${Rd}`,cv=Symbol.for(Pd),Nd,Md,uv=class extends(Md=me,Nd=cv,Md){constructor(e){super({name:Rd,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[Nd]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return me.hasMarker(e,Pd)}},Od="AI_TypeValidationError",Ad=`vercel.ai.error.${Od}`,dv=Symbol.for(Ad),qd,Ld,yn=class Yu extends(Ld=me,qd=dv,Ld){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:Od,message:`${o}: Value: ${JSON.stringify(t)}.
3
+ Error message: ${mn(r)}`,cause:r}),this[qd]=!0,this.value=t,this.context=n}static isInstance(t){return me.hasMarker(t,Ad)}static wrap({value:t,cause:r,context:n}){var o,s,a;return Yu.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((s=r.context)==null?void 0:s.entityName)===n?.entityName&&((a=r.context)==null?void 0:a.entityId)===n?.entityId?r:new Yu({value:t,cause:r,context:n})}},jd="AI_UnsupportedFunctionalityError",Dd=`vercel.ai.error.${jd}`,pv=Symbol.for(Dd),Ud,zd,br=class extends(zd=me,Ud=pv,zd){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:jd,message:r}),this[Ud]=!0,this.functionality=t}static isInstance(t){return me.hasMarker(t,Dd)}};const Fd=Object.freeze({status:"aborted"});function J(e,t,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const c=r?.Parent?new s:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class bo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Vd={};function Jr(e){return Vd}function Zd(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function fv(e,t){return typeof t=="bigint"?t.toString():t}function Ui(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function zi(e){return e==null}function Fi(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function hv(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function Fe(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Es(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ko(e){return JSON.stringify(e)}const Bd=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function $s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const mv=Ui(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Rs(e){if($s(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!($s(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const gv=new Set(["string","number","symbol"]);function Co(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _n(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ue(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function yv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const _v={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 vv(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return _n(e,{...e._zod.def,shape:r,checks:[]})}function wv(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return _n(e,{...e._zod.def,shape:r,checks:[]})}function bv(e,t){if(!Rs(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return Es(this,"shape",n),n},checks:[]};return _n(e,r)}function kv(e,t){return _n(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Es(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Cv(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(const s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return _n(t,{...t._zod.def,shape:o,checks:[]})}function Tv(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return _n(t,{...t._zod.def,shape:o,checks:[]})}function To(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function vn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ps(e){return typeof e=="string"?e:e?.message}function Gr(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Ps(e.inst?._zod.def?.error?.(e))??Ps(t?.error?.(e))??Ps(r.customError?.(e))??Ps(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Vi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function So(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Hd=(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,fv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Jd=J("$ZodError",Hd),Gd=J("$ZodError",Hd,{Parent:Error});function Sv(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Iv(e,t){const r=t||function(s){return s.message},n={_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)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),n}const xv=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new bo;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>Gr(l,s,Jr())));throw Bd(i,o?.callee),i}return a.value},Ev=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>Gr(l,s,Jr())));throw Bd(i,o?.callee),i}return a.value},Wd=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new bo;return s.issues.length?{success:!1,error:new(e??Jd)(s.issues.map(a=>Gr(a,o,Jr())))}:{success:!0,data:s.value}},Kd=Wd(Gd),Yd=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Gr(a,o,Jr())))}:{success:!0,data:s.value}},$v=Yd(Gd),Rv=/^[cC][^\s-]{8,}$/,Pv=/^[0-9a-z]+$/,Nv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Mv=/^[0-9a-vA-V]{20}$/,Ov=/^[A-Za-z0-9]{27}$/,Av=/^[a-zA-Z0-9_-]{21}$/,qv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Lv=/^([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})$/,Qd=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)$/,jv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Uv(){return new RegExp(Dv,"u")}const zv=/^(?:(?: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])$/,Fv=/^(([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})$/,Vv=/^((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])$/,Zv=/^(([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])$/,Bv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xd=/^[A-Za-z0-9_-]*$/,Hv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Jv=/^\+(?:[0-9]){6,14}[0-9]$/,ep="(?:(?:\\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])))",Gv=new RegExp(`^${ep}$`);function tp(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 Wv(e){return new RegExp(`^${tp(e)}$`)}function Kv(e){const t=tp({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${ep}T(?:${n})$`)}const Yv=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Qv=/^\d+$/,Xv=/^-?\d+(?:\.\d+)?/i,e1=/true|false/i,t1=/null/i,r1=/^[^A-Z]*$/,n1=/^[^a-z]*$/,Dt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),rp={number:"number",bigint:"bigint",object:"date"},np=J("$ZodCheckLessThan",(e,t)=>{Dt.init(e,t);const r=rp[typeof t.value];e._zod.onattach.push(n=>{const o=n._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=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),op=J("$ZodCheckGreaterThan",(e,t)=>{Dt.init(e,t);const r=rp[typeof t.value];e._zod.onattach.push(n=>{const o=n._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=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),o1=J("$ZodCheckMultipleOf",(e,t)=>{Dt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):hv(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),s1=J("$ZodCheckNumberFormat",(e,t)=>{Dt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=_v[t.format];e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,i.minimum=o,i.maximum=s,r&&(i.pattern=Qv)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}i<o&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),a1=J("$ZodCheckMaxLength",(e,t)=>{var r;Dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!zi(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const a=Vi(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),i1=J("$ZodCheckMinLength",(e,t)=>{var r;Dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!zi(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const a=Vi(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),l1=J("$ZodCheckLengthEquals",(e,t)=>{var r;Dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!zi(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const a=Vi(o),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ns=J("$ZodCheckStringFormat",(e,t)=>{var r,n;Dt.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?(r=e._zod).check??(r.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})}):(n=e._zod).check??(n.check=()=>{})}),c1=J("$ZodCheckRegex",(e,t)=>{Ns.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),u1=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=r1),Ns.init(e,t)}),d1=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=n1),Ns.init(e,t)}),p1=J("$ZodCheckIncludes",(e,t)=>{Dt.init(e,t);const r=Co(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),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})}}),f1=J("$ZodCheckStartsWith",(e,t)=>{Dt.init(e,t);const r=new RegExp(`^${Co(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),h1=J("$ZodCheckEndsWith",(e,t)=>{Dt.init(e,t);const r=new RegExp(`.*${Co(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),m1=J("$ZodCheckOverwrite",(e,t)=>{Dt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class g1{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 n=t.split(`
4
4
  `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.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,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
5
- `))}}const Qv={major:4,minor:0,patch:0},We=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Qv;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,i)=>{let l=ho(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const g=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&i?.async===!1)throw new uo;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==g&&(l||(l=ho(s,g)))});else{if(s.issues.length===g)continue;l||(l=ho(s,g))}}return c?c.then(()=>s):s};e._zod.run=(s,a)=>{const i=e._zod.parse(s,a);if(i instanceof Promise){if(a.async===!1)throw new uo;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=Nd(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return uv(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Ii=J("$ZodString",(e,t)=>{We.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Mv(e._zod.bag),e._zod.parse=(r,n)=>{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}}),et=J("$ZodStringFormat",(e,t)=>{vs.init(e,t),Ii.init(e,t)}),Xv=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=_v),et.init(e,t)}),e1=J("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ad(n))}else t.pattern??(t.pattern=Ad());et.init(e,t)}),t1=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=vv),et.init(e,t)}),r1=J("$ZodURL",(e,t)=>{et.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:xv.source,input:r.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)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),n1=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=bv()),et.init(e,t)}),o1=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=gv),et.init(e,t)}),s1=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=dv),et.init(e,t)}),a1=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=pv),et.init(e,t)}),i1=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=fv),et.init(e,t)}),l1=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=hv),et.init(e,t)}),c1=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=mv),et.init(e,t)}),u1=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Pv(t)),et.init(e,t)}),d1=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=$v),et.init(e,t)}),p1=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Rv(t)),et.init(e,t)}),f1=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=yv),et.init(e,t)}),h1=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=kv),et.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),m1=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Cv),et.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),g1=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Tv),et.init(e,t)}),y1=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Sv),et.init(e,t),e._zod.check=r=>{const[n,o]=r.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://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Fd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const _1=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Iv),et.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Fd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function v1(e){if(!qd.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Fd(r)}const w1=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=qd),et.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{v1(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),b1=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ev),et.init(e,t)});function k1(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const C1=J("$ZodJWT",(e,t)=>{et.init(e,t),e._zod.check=r=>{k1(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Vd=J("$ZodNumber",(e,t)=>{We.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ov,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),T1=J("$ZodNumber",(e,t)=>{Dv.init(e,t),Vd.init(e,t)}),S1=J("$ZodBoolean",(e,t)=>{We.init(e,t),e._zod.pattern=Av,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),I1=J("$ZodNull",(e,t)=>{We.init(e,t),e._zod.pattern=qv,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),x1=J("$ZodAny",(e,t)=>{We.init(e,t),e._zod.parse=r=>r}),E1=J("$ZodUnknown",(e,t)=>{We.init(e,t),e._zod.parse=r=>r}),$1=J("$ZodNever",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Zd(e,t,r){e.issues.length&&t.issues.push(...cn(r,e.issues)),t.value[r]=e.value}const R1=J("$ZodArray",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.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:[]},n);l instanceof Promise?s.push(l.then(c=>Zd(c,r,a))):Zd(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function ws(e,t,r){e.issues.length&&t.issues.push(...cn(r,e.issues)),t.value[r]=e.value}function Bd(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...cn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const P1=J("$ZodObject",(e,t)=>{We.init(e,t);const r=ki(()=>{const g=Object.keys(t.shape);for(const h of g)if(!(t.shape[h]instanceof We))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=Q_(t.shape);return{shape:t.shape,keys:g,keySet:new Set(g),numKeys:g.length,optionalKeys:new Set(p)}});Ze(e._zod,"propValues",()=>{const g=t.shape,p={};for(const h in g){const y=g[h]._zod;if(y.values){p[h]??(p[h]=new Set);for(const w of y.values)p[h].add(w)}}return p});const n=g=>{const p=new Yv(["shape","payload","ctx"]),h=r.value,y=_=>{const f=po(_);return`shape[${f}]._zod.run({ value: input[${f}], issues: [] }, ctx)`};p.write("const input = payload.value;");const w=Object.create(null);let m=0;for(const _ of h.keys)w[_]=`key_${m++}`;p.write("const newResult = {}");for(const _ of h.keys)if(h.optionalKeys.has(_)){const f=w[_];p.write(`const ${f} = ${y(_)};`);const C=po(_);p.write(`
6
- if (${f}.issues.length) {
7
- if (input[${C}] === undefined) {
8
- if (${C} in input) {
9
- newResult[${C}] = undefined;
5
+ `))}}const y1={major:4,minor:0,patch:0},Ge=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=y1;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,i)=>{let l=To(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const m=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&i?.async===!1)throw new bo;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==m&&(l||(l=To(s,m)))});else{if(s.issues.length===m)continue;l||(l=To(s,m))}}return c?c.then(()=>s):s};e._zod.run=(s,a)=>{const i=e._zod.parse(s,a);if(i instanceof Promise){if(a.async===!1)throw new bo;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=Kd(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return $v(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Zi=J("$ZodString",(e,t)=>{Ge.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Yv(e._zod.bag),e._zod.parse=(r,n)=>{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}}),et=J("$ZodStringFormat",(e,t)=>{Ns.init(e,t),Zi.init(e,t)}),_1=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Lv),et.init(e,t)}),v1=J("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Qd(n))}else t.pattern??(t.pattern=Qd());et.init(e,t)}),w1=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=jv),et.init(e,t)}),b1=J("$ZodURL",(e,t)=>{et.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Hv.source,input:r.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)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),k1=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Uv()),et.init(e,t)}),C1=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Av),et.init(e,t)}),T1=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Rv),et.init(e,t)}),S1=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pv),et.init(e,t)}),I1=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Nv),et.init(e,t)}),x1=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Mv),et.init(e,t)}),E1=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ov),et.init(e,t)}),$1=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Kv(t)),et.init(e,t)}),R1=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Gv),et.init(e,t)}),P1=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Wv(t)),et.init(e,t)}),N1=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=qv),et.init(e,t)}),M1=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=zv),et.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),O1=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Fv),et.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),A1=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Vv),et.init(e,t)}),q1=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Zv),et.init(e,t),e._zod.check=r=>{const[n,o]=r.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://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function sp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const L1=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Bv),et.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{sp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function j1(e){if(!Xd.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return sp(r)}const D1=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Xd),et.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{j1(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),U1=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Jv),et.init(e,t)});function z1(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const F1=J("$ZodJWT",(e,t)=>{et.init(e,t),e._zod.check=r=>{z1(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),ap=J("$ZodNumber",(e,t)=>{Ge.init(e,t),e._zod.pattern=e._zod.bag.pattern??Xv,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),V1=J("$ZodNumber",(e,t)=>{s1.init(e,t),ap.init(e,t)}),Z1=J("$ZodBoolean",(e,t)=>{Ge.init(e,t),e._zod.pattern=e1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),B1=J("$ZodNull",(e,t)=>{Ge.init(e,t),e._zod.pattern=t1,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),H1=J("$ZodAny",(e,t)=>{Ge.init(e,t),e._zod.parse=r=>r}),J1=J("$ZodUnknown",(e,t)=>{Ge.init(e,t),e._zod.parse=r=>r}),G1=J("$ZodNever",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function ip(e,t,r){e.issues.length&&t.issues.push(...vn(r,e.issues)),t.value[r]=e.value}const W1=J("$ZodArray",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.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:[]},n);l instanceof Promise?s.push(l.then(c=>ip(c,r,a))):ip(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Ms(e,t,r){e.issues.length&&t.issues.push(...vn(r,e.issues)),t.value[r]=e.value}function lp(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...vn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const K1=J("$ZodObject",(e,t)=>{Ge.init(e,t);const r=Ui(()=>{const m=Object.keys(t.shape);for(const f of m)if(!(t.shape[f]instanceof Ge))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const p=yv(t.shape);return{shape:t.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set(p)}});Fe(e._zod,"propValues",()=>{const m=t.shape,p={};for(const f in m){const g=m[f]._zod;if(g.values){p[f]??(p[f]=new Set);for(const v of g.values)p[f].add(v)}}return p});const n=m=>{const p=new g1(["shape","payload","ctx"]),f=r.value,g=_=>{const h=ko(_);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const _ of f.keys)v[_]=`key_${y++}`;p.write("const newResult = {}");for(const _ of f.keys)if(f.optionalKeys.has(_)){const h=v[_];p.write(`const ${h} = ${g(_)};`);const T=ko(_);p.write(`
6
+ if (${h}.issues.length) {
7
+ if (input[${T}] === undefined) {
8
+ if (${T} in input) {
9
+ newResult[${T}] = undefined;
10
10
  }
11
11
  } else {
12
12
  payload.issues = payload.issues.concat(
13
- ${f}.issues.map((iss) => ({
13
+ ${h}.issues.map((iss) => ({
14
14
  ...iss,
15
- path: iss.path ? [${C}, ...iss.path] : [${C}],
15
+ path: iss.path ? [${T}, ...iss.path] : [${T}],
16
16
  }))
17
17
  );
18
18
  }
19
- } else if (${f}.value === undefined) {
20
- if (${C} in input) newResult[${C}] = undefined;
19
+ } else if (${h}.value === undefined) {
20
+ if (${T} in input) newResult[${T}] = undefined;
21
21
  } else {
22
- newResult[${C}] = ${f}.value;
22
+ newResult[${T}] = ${h}.value;
23
23
  }
24
- `)}else{const f=w[_];p.write(`const ${f} = ${y(_)};`),p.write(`
25
- if (${f}.issues.length) payload.issues = payload.issues.concat(${f}.issues.map(iss => ({
24
+ `)}else{const h=v[_];p.write(`const ${h} = ${g(_)};`),p.write(`
25
+ if (${h}.issues.length) payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
26
26
  ...iss,
27
- path: iss.path ? [${po(_)}, ...iss.path] : [${po(_)}]
28
- })));`),p.write(`newResult[${po(_)}] = ${f}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const b=p.compile();return(_,f)=>b(g,_,f)};let o;const s=gs,a=!Id.jitless,l=a&&K_.value,c=t.catchall;let u;e._zod.parse=(g,p)=>{u??(u=r.value);const h=g.value;if(!s(h))return g.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),g;const y=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),g=o(g,p);else{g.value={};const f=u.shape;for(const C of u.keys){const k=f[C],v=k._zod.run({value:h[C],issues:[]},p),S=k._zod.optin==="optional"&&k._zod.optout==="optional";v instanceof Promise?y.push(v.then($=>S?Bd($,g,C,h):ws($,g,C))):S?Bd(v,g,C,h):ws(v,g,C)}}if(!c)return y.length?Promise.all(y).then(()=>g):g;const w=[],m=u.keySet,b=c._zod,_=b.def.type;for(const f of Object.keys(h)){if(m.has(f))continue;if(_==="never"){w.push(f);continue}const C=b.run({value:h[f],issues:[]},p);C instanceof Promise?y.push(C.then(k=>ws(k,g,f))):ws(C,g,f)}return w.length&&g.issues.push({code:"unrecognized_keys",keys:w,input:h,inst:e}),y.length?Promise.all(y).then(()=>g):g}});function Hd(e,t,r,n){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:r,errors:e.map(o=>o.issues.map(s=>Lr(s,n,qr())))}),t}const Jd=J("$ZodUnion",(e,t)=>{We.init(e,t),Ze(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ze(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ze(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Ze(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ti(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:r.value,issues:[]},n);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=>Hd(a,r,e,n)):Hd(s,r,e,n)}}),M1=J("$ZodDiscriminatedUnion",(e,t)=>{Jd.init(e,t);const r=e._zod.parse;Ze(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 c of l)o[i].add(c)}}return o});const n=ki(()=>{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(!gs(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=n.value.get(a?.[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),N1=J("$ZodIntersection",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>Gd(r,l,c)):Gd(r,s,a)}});function xi(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(ys(e)&&ys(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(const s of n){const a=xi(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 r=[];for(let n=0;n<e.length;n++){const o=e[n],s=t[n],a=xi(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Gd(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),ho(e))return e;const n=xi(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const O1=J("$ZodRecord",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!ys(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...cn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...cn(l,c.issues)),r.value[l]=c.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>Lr(c,n,qr())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...cn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...cn(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),A1=J("$ZodEnum",(e,t)=>{We.init(e,t);const r=xd(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Y_.has(typeof n)).map(n=>typeof n=="string"?fo(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),q1=J("$ZodLiteral",(e,t)=>{We.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?fo(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),L1=J("$ZodTransform",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new uo;return r.value=o,r}}),j1=J("$ZodOptional",(e,t)=>{We.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ti(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),U1=J("$ZodNullable",(e,t)=>{We.init(e,t),Ze(e._zod,"optin",()=>t.innerType._zod.optin),Ze(e._zod,"optout",()=>t.innerType._zod.optout),Ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ti(r.source)}|null)$`):void 0}),Ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),D1=J("$ZodDefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",Ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Wd(s,t)):Wd(o,t)}});function Wd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const z1=J("$ZodPrefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",Ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),F1=J("$ZodNonOptional",(e,t)=>{We.init(e,t),Ze(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Kd(s,e)):Kd(o,e)}});function Kd(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 V1=J("$ZodCatch",(e,t)=>{We.init(e,t),e._zod.optin="optional",Ze(e._zod,"optout",()=>t.innerType._zod.optout),Ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(a=>Lr(a,n,qr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Lr(s,n,qr()))},input:r.value}),r.issues=[]),r)}}),Z1=J("$ZodPipe",(e,t)=>{We.init(e,t),Ze(e._zod,"values",()=>t.in._zod.values),Ze(e._zod,"optin",()=>t.in._zod.optin),Ze(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Yd(s,t,n)):Yd(o,t,n)}});function Yd(e,t,r){return ho(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const B1=J("$ZodReadonly",(e,t)=>{We.init(e,t),Ze(e._zod,"propValues",()=>t.innerType._zod.propValues),Ze(e._zod,"values",()=>t.innerType._zod.values),Ze(e._zod,"optin",()=>t.innerType._zod.optin),Ze(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Qd):Qd(o)}});function Qd(e){return e.value=Object.freeze(e.value),e}const H1=J("$ZodLazy",(e,t)=>{We.init(e,t),Ze(e._zod,"innerType",()=>t.getter()),Ze(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Ze(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Ze(e._zod,"optin",()=>e._zod.innerType._zod.optin),Ze(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),J1=J("$ZodCustom",(e,t)=>{Nt.init(e,t),We.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>Xd(s,r,n,e));Xd(o,r,n,e)}});function Xd(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(mo(o))}}class ep{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function G1(){return new ep}const go=G1();function W1(e,t){return new e({type:"string",...de(t)})}function K1(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...de(t)})}function tp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...de(t)})}function Y1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...de(t)})}function Q1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(t)})}function X1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(t)})}function ew(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(t)})}function rp(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...de(t)})}function tw(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...de(t)})}function rw(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(t)})}function nw(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...de(t)})}function ow(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(t)})}function sw(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...de(t)})}function aw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...de(t)})}function iw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(t)})}function lw(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(t)})}function cw(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(t)})}function uw(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(t)})}function dw(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(t)})}function np(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...de(t)})}function pw(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...de(t)})}function fw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...de(t)})}function hw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...de(t)})}function mw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(t)})}function gw(e,t){return new e({type:"string",format:"date",check:"string_format",...de(t)})}function yw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...de(t)})}function _w(e,t){return new e({type:"string",format:"duration",check:"string_format",...de(t)})}function vw(e,t){return new e({type:"number",checks:[],...de(t)})}function ww(e,t){return new e({type:"number",coerce:!0,checks:[],...de(t)})}function bw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...de(t)})}function kw(e,t){return new e({type:"boolean",...de(t)})}function Cw(e,t){return new e({type:"null",...de(t)})}function Tw(e){return new e({type:"any"})}function Sw(e){return new e({type:"unknown"})}function Iw(e,t){return new e({type:"never",...de(t)})}function op(e,t){return new Dd({check:"less_than",...de(t),value:e,inclusive:!1})}function Ei(e,t){return new Dd({check:"less_than",...de(t),value:e,inclusive:!0})}function sp(e,t){return new zd({check:"greater_than",...de(t),value:e,inclusive:!1})}function $i(e,t){return new zd({check:"greater_than",...de(t),value:e,inclusive:!0})}function ap(e,t){return new Uv({check:"multiple_of",...de(t),value:e})}function ip(e,t){return new zv({check:"max_length",...de(t),maximum:e})}function bs(e,t){return new Fv({check:"min_length",...de(t),minimum:e})}function lp(e,t){return new Vv({check:"length_equals",...de(t),length:e})}function xw(e,t){return new Zv({check:"string_format",format:"regex",...de(t),pattern:e})}function Ew(e){return new Bv({check:"string_format",format:"lowercase",...de(e)})}function $w(e){return new Hv({check:"string_format",format:"uppercase",...de(e)})}function Rw(e,t){return new Jv({check:"string_format",format:"includes",...de(t),includes:e})}function Pw(e,t){return new Gv({check:"string_format",format:"starts_with",...de(t),prefix:e})}function Mw(e,t){return new Wv({check:"string_format",format:"ends_with",...de(t),suffix:e})}function yo(e){return new Kv({check:"overwrite",tx:e})}function Nw(e){return yo(t=>t.normalize(e))}function Ow(){return yo(e=>e.trim())}function Aw(){return yo(e=>e.toLowerCase())}function qw(){return yo(e=>e.toUpperCase())}function Lw(e,t,r){return new e({type:"array",element:t,...de(r)})}function jw(e,t,r){const n=de(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Uw(e,t,r){return new e({type:"custom",check:"custom",fn:t,...de(r)})}class cp{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??go,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;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++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const g={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,g),this.seen.get(p).isParent=!0;else{const h=i.schema;switch(o.type){case"string":{const y=h;y.type="string";const{minimum:w,maximum:m,format:b,patterns:_,contentEncoding:f}=t._zod.bag;if(typeof w=="number"&&(y.minLength=w),typeof m=="number"&&(y.maxLength=m),b&&(y.format=s[b]??b,y.format===""&&delete y.format),f&&(y.contentEncoding=f),_&&_.size>0){const C=[..._];C.length===1?y.pattern=C[0].source:C.length>1&&(i.schema.allOf=[...C.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const y=h,{minimum:w,maximum:m,format:b,multipleOf:_,exclusiveMaximum:f,exclusiveMinimum:C}=t._zod.bag;typeof b=="string"&&b.includes("int")?y.type="integer":y.type="number",typeof C=="number"&&(y.exclusiveMinimum=C),typeof w=="number"&&(y.minimum=w,typeof C=="number"&&(C>=w?delete y.minimum:delete y.exclusiveMinimum)),typeof f=="number"&&(y.exclusiveMaximum=f),typeof m=="number"&&(y.maximum=m,typeof f=="number"&&(f<=m?delete y.maximum:delete y.exclusiveMaximum)),typeof _=="number"&&(y.multipleOf=_);break}case"boolean":{const y=h;y.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const y=h,{minimum:w,maximum:m}=t._zod.bag;typeof w=="number"&&(y.minItems=w),typeof m=="number"&&(y.maxItems=m),y.type="array",y.items=this.process(o.element,{...g,path:[...g.path,"items"]});break}case"object":{const y=h;y.type="object",y.properties={};const w=o.shape;for(const _ in w)y.properties[_]=this.process(w[_],{...g,path:[...g.path,"properties",_]});const m=new Set(Object.keys(w)),b=new Set([...m].filter(_=>{const f=o.shape[_]._zod;return this.io==="input"?f.optin===void 0:f.optout===void 0}));b.size>0&&(y.required=Array.from(b)),o.catchall?._zod.def.type==="never"?y.additionalProperties=!1:o.catchall?o.catchall&&(y.additionalProperties=this.process(o.catchall,{...g,path:[...g.path,"additionalProperties"]})):this.io==="output"&&(y.additionalProperties=!1);break}case"union":{const y=h;y.anyOf=o.options.map((w,m)=>this.process(w,{...g,path:[...g.path,"anyOf",m]}));break}case"intersection":{const y=h,w=this.process(o.left,{...g,path:[...g.path,"allOf",0]}),m=this.process(o.right,{...g,path:[...g.path,"allOf",1]}),b=f=>"allOf"in f&&Object.keys(f).length===1,_=[...b(w)?w.allOf:[w],...b(m)?m.allOf:[m]];y.allOf=_;break}case"tuple":{const y=h;y.type="array";const w=o.items.map((_,f)=>this.process(_,{...g,path:[...g.path,"prefixItems",f]}));if(this.target==="draft-2020-12"?y.prefixItems=w:y.items=w,o.rest){const _=this.process(o.rest,{...g,path:[...g.path,"items"]});this.target==="draft-2020-12"?y.items=_:y.additionalItems=_}o.rest&&(y.items=this.process(o.rest,{...g,path:[...g.path,"items"]}));const{minimum:m,maximum:b}=t._zod.bag;typeof m=="number"&&(y.minItems=m),typeof b=="number"&&(y.maxItems=b);break}case"record":{const y=h;y.type="object",y.propertyNames=this.process(o.keyType,{...g,path:[...g.path,"propertyNames"]}),y.additionalProperties=this.process(o.valueType,{...g,path:[...g.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 y=h,w=xd(o.entries);w.every(m=>typeof m=="number")&&(y.type="number"),w.every(m=>typeof m=="string")&&(y.type="string"),y.enum=w;break}case"literal":{const y=h,w=[];for(const m of o.values)if(m===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof m=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(m))}else w.push(m);if(w.length!==0)if(w.length===1){const m=w[0];y.type=m===null?"null":typeof m,y.const=m}else w.every(m=>typeof m=="number")&&(y.type="number"),w.every(m=>typeof m=="string")&&(y.type="string"),w.every(m=>typeof m=="boolean")&&(y.type="string"),w.every(m=>m===null)&&(y.type="null"),y.enum=w;break}case"file":{const y=h,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:m,maximum:b,mime:_}=t._zod.bag;m!==void 0&&(w.minLength=m),b!==void 0&&(w.maxLength=b),_?_.length===1?(w.contentMediaType=_[0],Object.assign(y,w)):y.anyOf=_.map(f=>({...w,contentMediaType:f})):Object.assign(y,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const y=this.process(o.innerType,g);h.anyOf=[y,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,g),i.ref=o.innerType;break}case"success":{const y=h;y.type="boolean";break}case"default":{this.process(o.innerType,g),i.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,g),i.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,g),i.ref=o.innerType;let y;try{y=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=y;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const y=h,w=t._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");y.type="string",y.pattern=w.source;break}case"pipe":{const y=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(y,g),i.ref=y;break}case"readonly":{this.process(o.innerType,g),i.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,g),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,g),i.ref=o.innerType;break}case"lazy":{const y=t._zod.innerType;this.process(y,g),i.ref=y;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&dt(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const g=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const w=n.external.registry.get(u[0])?.id,m=n.external.uri??(_=>_);if(w)return{ref:m(w)};const b=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=b,{defId:b,ref:`${m("__shared")}#/${g}/${b}`}}if(u[1]===o)return{ref:"#"};const h=`#/${g}/`,y=u[1].schema.id??`__schema${this.counter++}`;return{defId:y,ref:h+y}},a=u=>{if(u[1].schema.$ref)return;const g=u[1],{ref:p,defId:h}=s(u);g.def={...g.schema},h&&(g.defId=h);const y=g.schema;for(const w in y)delete y[w];y.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const g=u[1];if(g.cycle)throw new Error(`Cycle detected: #/${g.cycle?.join("/")}/<root>
27
+ path: iss.path ? [${ko(_)}, ...iss.path] : [${ko(_)}]
28
+ })));`),p.write(`newResult[${ko(_)}] = ${h}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(_,h)=>w(m,_,h)};let o;const s=$s,a=!Vd.jitless,l=a&&mv.value,c=t.catchall;let u;e._zod.parse=(m,p)=>{u??(u=r.value);const f=m.value;if(!s(f))return m.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),m;const g=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),m=o(m,p);else{m.value={};const h=u.shape;for(const T of u.keys){const k=h[T],b=k._zod.run({value:f[T],issues:[]},p),S=k._zod.optin==="optional"&&k._zod.optout==="optional";b instanceof Promise?g.push(b.then(x=>S?lp(x,m,T,f):Ms(x,m,T))):S?lp(b,m,T,f):Ms(b,m,T)}}if(!c)return g.length?Promise.all(g).then(()=>m):m;const v=[],y=u.keySet,w=c._zod,_=w.def.type;for(const h of Object.keys(f)){if(y.has(h))continue;if(_==="never"){v.push(h);continue}const T=w.run({value:f[h],issues:[]},p);T instanceof Promise?g.push(T.then(k=>Ms(k,m,h))):Ms(T,m,h)}return v.length&&m.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),g.length?Promise.all(g).then(()=>m):m}});function cp(e,t,r,n){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:r,errors:e.map(o=>o.issues.map(s=>Gr(s,n,Jr())))}),t}const up=J("$ZodUnion",(e,t)=>{Ge.init(e,t),Fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Fe(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Fi(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:r.value,issues:[]},n);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=>cp(a,r,e,n)):cp(s,r,e,n)}}),Y1=J("$ZodDiscriminatedUnion",(e,t)=>{up.init(e,t);const r=e._zod.parse;Fe(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 c of l)o[i].add(c)}}return o});const n=Ui(()=>{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(!$s(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=n.value.get(a?.[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),Q1=J("$ZodIntersection",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>dp(r,l,c)):dp(r,s,a)}});function Bi(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(Rs(e)&&Rs(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(const s of n){const a=Bi(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 r=[];for(let n=0;n<e.length;n++){const o=e[n],s=t[n],a=Bi(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function dp(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),To(e))return e;const n=Bi(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const X1=J("$ZodRecord",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Rs(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...vn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...vn(l,c.issues)),r.value[l]=c.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>Gr(c,n,Jr())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...vn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...vn(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),ew=J("$ZodEnum",(e,t)=>{Ge.init(e,t);const r=Zd(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>gv.has(typeof n)).map(n=>typeof n=="string"?Co(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),tw=J("$ZodLiteral",(e,t)=>{Ge.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Co(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),rw=J("$ZodTransform",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new bo;return r.value=o,r}}),nw=J("$ZodOptional",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Fi(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),ow=J("$ZodNullable",(e,t)=>{Ge.init(e,t),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Fi(r.source)}|null)$`):void 0}),Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),sw=J("$ZodDefault",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>pp(s,t)):pp(o,t)}});function pp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const aw=J("$ZodPrefault",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),iw=J("$ZodNonOptional",(e,t)=>{Ge.init(e,t),Fe(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>fp(s,e)):fp(o,e)}});function fp(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 lw=J("$ZodCatch",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(a=>Gr(a,n,Jr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Gr(s,n,Jr()))},input:r.value}),r.issues=[]),r)}}),cw=J("$ZodPipe",(e,t)=>{Ge.init(e,t),Fe(e._zod,"values",()=>t.in._zod.values),Fe(e._zod,"optin",()=>t.in._zod.optin),Fe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>hp(s,t,n)):hp(o,t,n)}});function hp(e,t,r){return To(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const uw=J("$ZodReadonly",(e,t)=>{Ge.init(e,t),Fe(e._zod,"propValues",()=>t.innerType._zod.propValues),Fe(e._zod,"values",()=>t.innerType._zod.values),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(mp):mp(o)}});function mp(e){return e.value=Object.freeze(e.value),e}const dw=J("$ZodLazy",(e,t)=>{Ge.init(e,t),Fe(e._zod,"innerType",()=>t.getter()),Fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),Fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),pw=J("$ZodCustom",(e,t)=>{Dt.init(e,t),Ge.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>gp(s,r,n,e));gp(o,r,n,e)}});function gp(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(So(o))}}class yp{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function fw(){return new yp}const Io=fw();function hw(e,t){return new e({type:"string",...ue(t)})}function mw(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ue(t)})}function _p(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ue(t)})}function gw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ue(t)})}function yw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ue(t)})}function _w(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ue(t)})}function vw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ue(t)})}function vp(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ue(t)})}function ww(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ue(t)})}function bw(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ue(t)})}function kw(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ue(t)})}function Cw(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ue(t)})}function Tw(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ue(t)})}function Sw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ue(t)})}function Iw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ue(t)})}function xw(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ue(t)})}function Ew(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ue(t)})}function $w(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ue(t)})}function Rw(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ue(t)})}function wp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ue(t)})}function Pw(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ue(t)})}function Nw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ue(t)})}function Mw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ue(t)})}function Ow(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ue(t)})}function Aw(e,t){return new e({type:"string",format:"date",check:"string_format",...ue(t)})}function qw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ue(t)})}function Lw(e,t){return new e({type:"string",format:"duration",check:"string_format",...ue(t)})}function jw(e,t){return new e({type:"number",checks:[],...ue(t)})}function Dw(e,t){return new e({type:"number",coerce:!0,checks:[],...ue(t)})}function Uw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ue(t)})}function zw(e,t){return new e({type:"boolean",...ue(t)})}function Fw(e,t){return new e({type:"null",...ue(t)})}function Vw(e){return new e({type:"any"})}function Zw(e){return new e({type:"unknown"})}function Bw(e,t){return new e({type:"never",...ue(t)})}function bp(e,t){return new np({check:"less_than",...ue(t),value:e,inclusive:!1})}function Hi(e,t){return new np({check:"less_than",...ue(t),value:e,inclusive:!0})}function kp(e,t){return new op({check:"greater_than",...ue(t),value:e,inclusive:!1})}function Ji(e,t){return new op({check:"greater_than",...ue(t),value:e,inclusive:!0})}function Cp(e,t){return new o1({check:"multiple_of",...ue(t),value:e})}function Tp(e,t){return new a1({check:"max_length",...ue(t),maximum:e})}function Os(e,t){return new i1({check:"min_length",...ue(t),minimum:e})}function Sp(e,t){return new l1({check:"length_equals",...ue(t),length:e})}function Hw(e,t){return new c1({check:"string_format",format:"regex",...ue(t),pattern:e})}function Jw(e){return new u1({check:"string_format",format:"lowercase",...ue(e)})}function Gw(e){return new d1({check:"string_format",format:"uppercase",...ue(e)})}function Ww(e,t){return new p1({check:"string_format",format:"includes",...ue(t),includes:e})}function Kw(e,t){return new f1({check:"string_format",format:"starts_with",...ue(t),prefix:e})}function Yw(e,t){return new h1({check:"string_format",format:"ends_with",...ue(t),suffix:e})}function xo(e){return new m1({check:"overwrite",tx:e})}function Qw(e){return xo(t=>t.normalize(e))}function Xw(){return xo(e=>e.trim())}function eb(){return xo(e=>e.toLowerCase())}function tb(){return xo(e=>e.toUpperCase())}function rb(e,t,r){return new e({type:"array",element:t,...ue(r)})}function nb(e,t,r){const n=ue(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function ob(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ue(r)})}class Ip{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Io,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;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++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const m={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,m),this.seen.get(p).isParent=!0;else{const f=i.schema;switch(o.type){case"string":{const g=f;g.type="string";const{minimum:v,maximum:y,format:w,patterns:_,contentEncoding:h}=t._zod.bag;if(typeof v=="number"&&(g.minLength=v),typeof y=="number"&&(g.maxLength=y),w&&(g.format=s[w]??w,g.format===""&&delete g.format),h&&(g.contentEncoding=h),_&&_.size>0){const T=[..._];T.length===1?g.pattern=T[0].source:T.length>1&&(i.schema.allOf=[...T.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const g=f,{minimum:v,maximum:y,format:w,multipleOf:_,exclusiveMaximum:h,exclusiveMinimum:T}=t._zod.bag;typeof w=="string"&&w.includes("int")?g.type="integer":g.type="number",typeof T=="number"&&(g.exclusiveMinimum=T),typeof v=="number"&&(g.minimum=v,typeof T=="number"&&(T>=v?delete g.minimum:delete g.exclusiveMinimum)),typeof h=="number"&&(g.exclusiveMaximum=h),typeof y=="number"&&(g.maximum=y,typeof h=="number"&&(h<=y?delete g.maximum:delete g.exclusiveMaximum)),typeof _=="number"&&(g.multipleOf=_);break}case"boolean":{const g=f;g.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":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const g=f,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(g.minItems=v),typeof y=="number"&&(g.maxItems=y),g.type="array",g.items=this.process(o.element,{...m,path:[...m.path,"items"]});break}case"object":{const g=f;g.type="object",g.properties={};const v=o.shape;for(const _ in v)g.properties[_]=this.process(v[_],{...m,path:[...m.path,"properties",_]});const y=new Set(Object.keys(v)),w=new Set([...y].filter(_=>{const h=o.shape[_]._zod;return this.io==="input"?h.optin===void 0:h.optout===void 0}));w.size>0&&(g.required=Array.from(w)),o.catchall?._zod.def.type==="never"?g.additionalProperties=!1:o.catchall?o.catchall&&(g.additionalProperties=this.process(o.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(g.additionalProperties=!1);break}case"union":{const g=f;g.anyOf=o.options.map((v,y)=>this.process(v,{...m,path:[...m.path,"anyOf",y]}));break}case"intersection":{const g=f,v=this.process(o.left,{...m,path:[...m.path,"allOf",0]}),y=this.process(o.right,{...m,path:[...m.path,"allOf",1]}),w=h=>"allOf"in h&&Object.keys(h).length===1,_=[...w(v)?v.allOf:[v],...w(y)?y.allOf:[y]];g.allOf=_;break}case"tuple":{const g=f;g.type="array";const v=o.items.map((_,h)=>this.process(_,{...m,path:[...m.path,"prefixItems",h]}));if(this.target==="draft-2020-12"?g.prefixItems=v:g.items=v,o.rest){const _=this.process(o.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?g.items=_:g.additionalItems=_}o.rest&&(g.items=this.process(o.rest,{...m,path:[...m.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(g.minItems=y),typeof w=="number"&&(g.maxItems=w);break}case"record":{const g=f;g.type="object",g.propertyNames=this.process(o.keyType,{...m,path:[...m.path,"propertyNames"]}),g.additionalProperties=this.process(o.valueType,{...m,path:[...m.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 g=f,v=Zd(o.entries);v.every(y=>typeof y=="number")&&(g.type="number"),v.every(y=>typeof y=="string")&&(g.type="string"),g.enum=v;break}case"literal":{const g=f,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];g.type=y===null?"null":typeof y,g.const=y}else v.every(y=>typeof y=="number")&&(g.type="number"),v.every(y=>typeof y=="string")&&(g.type="string"),v.every(y=>typeof y=="boolean")&&(g.type="string"),v.every(y=>y===null)&&(g.type="null"),g.enum=v;break}case"file":{const g=f,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:_}=t._zod.bag;y!==void 0&&(v.minLength=y),w!==void 0&&(v.maxLength=w),_?_.length===1?(v.contentMediaType=_[0],Object.assign(g,v)):g.anyOf=_.map(h=>({...v,contentMediaType:h})):Object.assign(g,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const g=this.process(o.innerType,m);f.anyOf=[g,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,m),i.ref=o.innerType;break}case"success":{const g=f;g.type="boolean";break}case"default":{this.process(o.innerType,m),i.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,m),i.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,m),i.ref=o.innerType;let g;try{g=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=g;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const g=f,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");g.type="string",g.pattern=v.source;break}case"pipe":{const g=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(g,m),i.ref=g;break}case"readonly":{this.process(o.innerType,m),i.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,m),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,m),i.ref=o.innerType;break}case"lazy":{const g=t._zod.innerType;this.process(g,m),i.ref=g;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&_t(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const m=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,y=n.external.uri??(_=>_);if(v)return{ref:y(v)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${y("__shared")}#/${m}/${w}`}}if(u[1]===o)return{ref:"#"};const f=`#/${m}/`,g=u[1].schema.id??`__schema${this.counter++}`;return{defId:g,ref:f+g}},a=u=>{if(u[1].schema.$ref)return;const m=u[1],{ref:p,defId:f}=s(u);m.def={...m.schema},f&&(m.defId=f);const g=m.schema;for(const v in g)delete g[v];g.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const m=u[1];if(m.cycle)throw new Error(`Cycle detected: #/${m.cycle?.join("/")}/<root>
29
29
 
30
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const g=u[1];if(t===u[0]){a(u);continue}if(n.external){const h=n.external.registry.get(u[0])?.id;if(t!==u[0]&&h){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(g.cycle){a(u);continue}if(g.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,g)=>{const p=this.seen.get(u),h=p.def??p.schema,y={...h};if(p.ref===null)return;const w=p.ref;if(p.ref=null,w){i(w,g);const m=this.seen.get(w).schema;m.$ref&&g.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(m)):(Object.assign(h,m),Object.assign(h,y))}p.isParent||this.override({zodSchema:u,jsonSchema:h,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[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}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const g=u[1];g.def&&g.defId&&(c[g.defId]=g.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function Dw(e,t){if(e instanceof ep){const n=new cp(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;n.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;s[l]=n.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const r=new cp(t);return r.process(e),r.emit(e,t)}function dt(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.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 dt(o.element,r);case"object":{for(const s in o.shape)if(dt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(dt(s,r))return!0;return!1}case"intersection":return dt(o.left,r)||dt(o.right,r);case"tuple":{for(const s of o.items)if(dt(s,r))return!0;return!!(o.rest&&dt(o.rest,r))}case"record":return dt(o.keyType,r)||dt(o.valueType,r);case"map":return dt(o.keyType,r)||dt(o.valueType,r);case"set":return dt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return dt(o.innerType,r);case"lazy":return dt(o.getter(),r);case"default":return dt(o.innerType,r);case"prefault":return dt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return dt(o.in,r)||dt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const zw=J("ZodISODateTime",(e,t)=>{u1.init(e,t),rt.init(e,t)});function up(e){return mw(zw,e)}const Fw=J("ZodISODate",(e,t)=>{d1.init(e,t),rt.init(e,t)});function Vw(e){return gw(Fw,e)}const Zw=J("ZodISOTime",(e,t)=>{p1.init(e,t),rt.init(e,t)});function Bw(e){return yw(Zw,e)}const Hw=J("ZodISODuration",(e,t)=>{f1.init(e,t),rt.init(e,t)});function Jw(e){return _w(Hw,e)}const ks=J("ZodError",(e,t)=>{Rd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>iv(e,r)},flatten:{value:r=>av(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Gw=lv(ks),Ww=cv(ks),Kw=Md(ks),dp=Od(ks),Xe=J("ZodType",(e,t)=>(We.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>ln(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Gw(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Kw(e,r,n),e.parseAsync=async(r,n)=>Ww(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>dp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Db(r,n)),e.superRefine=r=>e.check(zb(r)),e.overwrite=r=>e.check(yo(r)),e.optional=()=>ie(e),e.nullable=()=>kp(e),e.nullish=()=>ie(kp(e)),e.nonoptional=r=>Mb(e,r),e.array=()=>q(e),e.or=r=>oe([e,r]),e.and=r=>Pi(e,r),e.transform=r=>Ni(e,wp(r)),e.default=r=>$b(e,r),e.prefault=r=>Pb(e,r),e.catch=r=>Ob(e,r),e.pipe=r=>Ni(e,r),e.readonly=()=>Lb(e),e.describe=r=>{const n=e.clone();return go.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return go.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return go.get(e);const n=e.clone();return go.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),pp=J("_ZodString",(e,t)=>{Ii.init(e,t),Xe.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(xw(...n)),e.includes=(...n)=>e.check(Rw(...n)),e.startsWith=(...n)=>e.check(Pw(...n)),e.endsWith=(...n)=>e.check(Mw(...n)),e.min=(...n)=>e.check(bs(...n)),e.max=(...n)=>e.check(ip(...n)),e.length=(...n)=>e.check(lp(...n)),e.nonempty=(...n)=>e.check(bs(1,...n)),e.lowercase=n=>e.check(Ew(n)),e.uppercase=n=>e.check($w(n)),e.trim=()=>e.check(Ow()),e.normalize=(...n)=>e.check(Nw(...n)),e.toLowerCase=()=>e.check(Aw()),e.toUpperCase=()=>e.check(qw())}),Yw=J("ZodString",(e,t)=>{Ii.init(e,t),pp.init(e,t),e.email=r=>e.check(K1(Qw,r)),e.url=r=>e.check(rp(hp,r)),e.jwt=r=>e.check(hw(fb,r)),e.emoji=r=>e.check(tw(eb,r)),e.guid=r=>e.check(tp(fp,r)),e.uuid=r=>e.check(Y1(Cs,r)),e.uuidv4=r=>e.check(Q1(Cs,r)),e.uuidv6=r=>e.check(X1(Cs,r)),e.uuidv7=r=>e.check(ew(Cs,r)),e.nanoid=r=>e.check(rw(tb,r)),e.guid=r=>e.check(tp(fp,r)),e.cuid=r=>e.check(nw(rb,r)),e.cuid2=r=>e.check(ow(nb,r)),e.ulid=r=>e.check(sw(ob,r)),e.base64=r=>e.check(np(mp,r)),e.base64url=r=>e.check(pw(db,r)),e.xid=r=>e.check(aw(sb,r)),e.ksuid=r=>e.check(iw(ab,r)),e.ipv4=r=>e.check(lw(ib,r)),e.ipv6=r=>e.check(cw(lb,r)),e.cidrv4=r=>e.check(uw(cb,r)),e.cidrv6=r=>e.check(dw(ub,r)),e.e164=r=>e.check(fw(pb,r)),e.datetime=r=>e.check(up(r)),e.date=r=>e.check(Vw(r)),e.time=r=>e.check(Bw(r)),e.duration=r=>e.check(Jw(r))});function d(e){return W1(Yw,e)}const rt=J("ZodStringFormat",(e,t)=>{et.init(e,t),pp.init(e,t)}),Qw=J("ZodEmail",(e,t)=>{t1.init(e,t),rt.init(e,t)}),fp=J("ZodGUID",(e,t)=>{Xv.init(e,t),rt.init(e,t)}),Cs=J("ZodUUID",(e,t)=>{e1.init(e,t),rt.init(e,t)}),hp=J("ZodURL",(e,t)=>{r1.init(e,t),rt.init(e,t)});function Xw(e){return rp(hp,e)}const eb=J("ZodEmoji",(e,t)=>{n1.init(e,t),rt.init(e,t)}),tb=J("ZodNanoID",(e,t)=>{o1.init(e,t),rt.init(e,t)}),rb=J("ZodCUID",(e,t)=>{s1.init(e,t),rt.init(e,t)}),nb=J("ZodCUID2",(e,t)=>{a1.init(e,t),rt.init(e,t)}),ob=J("ZodULID",(e,t)=>{i1.init(e,t),rt.init(e,t)}),sb=J("ZodXID",(e,t)=>{l1.init(e,t),rt.init(e,t)}),ab=J("ZodKSUID",(e,t)=>{c1.init(e,t),rt.init(e,t)}),ib=J("ZodIPv4",(e,t)=>{h1.init(e,t),rt.init(e,t)}),lb=J("ZodIPv6",(e,t)=>{m1.init(e,t),rt.init(e,t)}),cb=J("ZodCIDRv4",(e,t)=>{g1.init(e,t),rt.init(e,t)}),ub=J("ZodCIDRv6",(e,t)=>{y1.init(e,t),rt.init(e,t)}),mp=J("ZodBase64",(e,t)=>{_1.init(e,t),rt.init(e,t)});function gp(e){return np(mp,e)}const db=J("ZodBase64URL",(e,t)=>{w1.init(e,t),rt.init(e,t)}),pb=J("ZodE164",(e,t)=>{b1.init(e,t),rt.init(e,t)}),fb=J("ZodJWT",(e,t)=>{C1.init(e,t),rt.init(e,t)}),Ri=J("ZodNumber",(e,t)=>{Vd.init(e,t),Xe.init(e,t),e.gt=(n,o)=>e.check(sp(n,o)),e.gte=(n,o)=>e.check($i(n,o)),e.min=(n,o)=>e.check($i(n,o)),e.lt=(n,o)=>e.check(op(n,o)),e.lte=(n,o)=>e.check(Ei(n,o)),e.max=(n,o)=>e.check(Ei(n,o)),e.int=n=>e.check(yp(n)),e.safe=n=>e.check(yp(n)),e.positive=n=>e.check(sp(0,n)),e.nonnegative=n=>e.check($i(0,n)),e.negative=n=>e.check(op(0,n)),e.nonpositive=n=>e.check(Ei(0,n)),e.multipleOf=(n,o)=>e.check(ap(n,o)),e.step=(n,o)=>e.check(ap(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function j(e){return vw(Ri,e)}const hb=J("ZodNumberFormat",(e,t)=>{T1.init(e,t),Ri.init(e,t)});function yp(e){return bw(hb,e)}const mb=J("ZodBoolean",(e,t)=>{S1.init(e,t),Xe.init(e,t)});function fe(e){return kw(mb,e)}const gb=J("ZodNull",(e,t)=>{I1.init(e,t),Xe.init(e,t)});function Ts(e){return Cw(gb,e)}const yb=J("ZodAny",(e,t)=>{x1.init(e,t),Xe.init(e,t)});function ft(){return Tw(yb)}const _b=J("ZodUnknown",(e,t)=>{E1.init(e,t),Xe.init(e,t)});function Me(){return Sw(_b)}const vb=J("ZodNever",(e,t)=>{$1.init(e,t),Xe.init(e,t)});function wb(e){return Iw(vb,e)}const bb=J("ZodArray",(e,t)=>{R1.init(e,t),Xe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(bs(r,n)),e.nonempty=r=>e.check(bs(1,r)),e.max=(r,n)=>e.check(ip(r,n)),e.length=(r,n)=>e.check(lp(r,n)),e.unwrap=()=>e.element});function q(e,t){return Lw(bb,e,t)}const _p=J("ZodObject",(e,t)=>{P1.init(e,t),Xe.init(e,t),Ze(e,"shape",()=>t.shape),e.keyof=()=>Se(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Me()}),e.loose=()=>e.clone({...e._zod.def,catchall:Me()}),e.strict=()=>e.clone({...e._zod.def,catchall:wb()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>rv(e,r),e.merge=r=>nv(e,r),e.pick=r=>ev(e,r),e.omit=r=>tv(e,r),e.partial=(...r)=>ov(bp,e,r[0]),e.required=(...r)=>sv(Cp,e,r[0])});function T(e,t){const r={type:"object",get shape(){return ms(this,"shape",{...e}),this.shape},...de(t)};return new _p(r)}function nt(e,t){return new _p({type:"object",get shape(){return ms(this,"shape",{...e}),this.shape},catchall:Me(),...de(t)})}const vp=J("ZodUnion",(e,t)=>{Jd.init(e,t),Xe.init(e,t),e.options=t.options});function oe(e,t){return new vp({type:"union",options:e,...de(t)})}const kb=J("ZodDiscriminatedUnion",(e,t)=>{vp.init(e,t),M1.init(e,t)});function Qe(e,t,r){return new kb({type:"union",options:t,discriminator:e,...de(r)})}const Cb=J("ZodIntersection",(e,t)=>{N1.init(e,t),Xe.init(e,t)});function Pi(e,t){return new Cb({type:"intersection",left:e,right:t})}const Tb=J("ZodRecord",(e,t)=>{O1.init(e,t),Xe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function me(e,t,r){return new Tb({type:"record",keyType:e,valueType:t,...de(r)})}const Mi=J("ZodEnum",(e,t)=>{A1.init(e,t),Xe.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const a of n)if(r.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Mi({...t,checks:[],...de(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Mi({...t,checks:[],...de(o),entries:s})}});function Se(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Mi({type:"enum",entries:r,...de(t)})}const Sb=J("ZodLiteral",(e,t)=>{q1.init(e,t),Xe.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 P(e,t){return new Sb({type:"literal",values:Array.isArray(e)?e:[e],...de(t)})}const Ib=J("ZodTransform",(e,t)=>{L1.init(e,t),Xe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(mo(s,r.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(mo(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function wp(e){return new Ib({type:"transform",transform:e})}const bp=J("ZodOptional",(e,t)=>{j1.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ie(e){return new bp({type:"optional",innerType:e})}const xb=J("ZodNullable",(e,t)=>{U1.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function kp(e){return new xb({type:"nullable",innerType:e})}const Eb=J("ZodDefault",(e,t)=>{D1.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $b(e,t){return new Eb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Rb=J("ZodPrefault",(e,t)=>{z1.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Pb(e,t){return new Rb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Cp=J("ZodNonOptional",(e,t)=>{F1.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Mb(e,t){return new Cp({type:"nonoptional",innerType:e,...de(t)})}const Nb=J("ZodCatch",(e,t)=>{V1.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ob(e,t){return new Nb({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Ab=J("ZodPipe",(e,t)=>{Z1.init(e,t),Xe.init(e,t),e.in=t.in,e.out=t.out});function Ni(e,t){return new Ab({type:"pipe",in:e,out:t})}const qb=J("ZodReadonly",(e,t)=>{B1.init(e,t),Xe.init(e,t)});function Lb(e){return new qb({type:"readonly",innerType:e})}const jb=J("ZodLazy",(e,t)=>{H1.init(e,t),Xe.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Oi(e){return new jb({type:"lazy",getter:e})}const Ai=J("ZodCustom",(e,t)=>{J1.init(e,t),Xe.init(e,t)});function Ub(e){const t=new Nt({check:"custom"});return t._zod.check=e,t}function Tp(e,t){return jw(Ai,e??(()=>!0),t)}function Db(e,t={}){return Uw(Ai,e,t)}function zb(e){const t=Ub(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(mo(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(mo(o))}},e(r.value,r)));return t}function Ss(e,t={error:`Input not instance of ${e.name}`}){const r=new Ai({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...de(t)});return r._zod.bag.Class=e,r}function Sp(e,t){return Ni(wp(e),t)}const Ip={custom:"custom"};function xp(e){return ww(Ri,e)}var De;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,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 n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(De||(De={}));var Ep;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Ep||(Ep={}));const ue=De.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),jr=e=>{switch(typeof e){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return Number.isNaN(e)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(e)?ue.array:e===null?ue.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ue.promise:typeof Map<"u"&&e instanceof Map?ue.map:typeof Set<"u"&&e instanceof Set?ue.set:typeof Date<"u"&&e instanceof Date?ue.date:ue.object;default:return ue.unknown}},X=De.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 kr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_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)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof kr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,De.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}kr.create=e=>new kr(e);const qi=(e,t)=>{let r;switch(e.code){case X.invalid_type:e.received===ue.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,De.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:r=`Unrecognized key(s) in object: ${De.joinValues(e.keys,", ")}`;break;case X.invalid_union:r="Invalid input";break;case X.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${De.joinValues(e.options)}`;break;case X.invalid_enum_value:r=`Invalid enum value. Expected ${De.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:r="Invalid function arguments";break;case X.invalid_return_type:r="Invalid function return type";break;case X.invalid_date:r="Invalid date";break;case X.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:De.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case X.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case X.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case X.custom:r="Invalid input";break;case X.invalid_intersection_types:r="Intersection results could not be merged";break;case X.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:r="Number must be finite";break;default:r=t.defaultError,De.assertNever(e)}return{message:r}};let Fb=qi;function Vb(){return Fb}const Zb=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}};function se(e,t){const r=Vb(),n=Zb({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===qi?void 0:qi].filter(o=>!!o)});e.common.issues.push(n)}class jt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return xe;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,a=await o.value;n.push({key:s,value:a})}return jt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return xe;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:t.value,value:n}}}const xe=Object.freeze({status:"aborted"}),_o=e=>({status:"dirty",value:e}),Zt=e=>({status:"valid",value:e}),$p=e=>e.status==="aborted",Rp=e=>e.status==="dirty",Nn=e=>e.status==="valid",Is=e=>typeof Promise<"u"&&e instanceof Promise;var pe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(pe||(pe={}));class Ur{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,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 Pp=(e,t)=>{if(Nn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new kr(e.common.issues);return this._error=r,this._error}}};function Ae(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))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??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:o}}class je{get description(){return this._def.description}_getType(t){return jr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:jr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new jt,ctx:{common:t.parent.common,data:t.data,parsedType:jr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Is(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:jr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Pp(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:jr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Nn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Nn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:jr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Is(o)?o:Promise.resolve(o));return Pp(n,s)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:X.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Ln({schema:this,typeName:te.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:r=>this["~validate"](r)}}optional(){return Fr.create(this,this._def)}nullable(){return jn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pr.create(this)}promise(){return Rs.create(this,this._def)}or(t){return Es.create([this,t],this._def)}and(t){return $s.create(this,t,this._def)}transform(t){return new Ln({...Ae(this._def),schema:this,typeName:te.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new Ui({...Ae(this._def),innerType:this,defaultValue:r,typeName:te.ZodDefault})}brand(){return new f3({typeName:te.ZodBranded,type:this,...Ae(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new Di({...Ae(this._def),innerType:this,catchValue:r,typeName:te.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return zi.create(this,t)}readonly(){return Fi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Bb=/^c[^\s-]{8,}$/i,Hb=/^[0-9a-z]+$/,Jb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Gb=/^[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,Wb=/^[a-z0-9_-]{21}$/i,Kb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yb=/^[-+]?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)?)??$/,Qb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Li;const e3=/^(?:(?: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])$/,t3=/^(?:(?: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])$/,r3=/^(([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]))$/,n3=/^(([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])$/,o3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,s3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Mp="((\\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])))",a3=new RegExp(`^${Mp}$`);function Np(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function i3(e){return new RegExp(`^${Np(e)}$`)}function l3(e){let t=`${Mp}T${Np(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function c3(e,t){return!!((t==="v4"||!t)&&e3.test(e)||(t==="v6"||!t)&&r3.test(e))}function u3(e,t){if(!Kb.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function d3(e,t){return!!((t==="v4"||!t)&&t3.test(e)||(t==="v6"||!t)&&n3.test(e))}class Dr extends je{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ue.string){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:ue.string,received:s.parsedType}),xe}const n=new jt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.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?se(o,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&se(o,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Qb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"email",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Li||(Li=new RegExp(Xb,"u")),Li.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"emoji",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Gb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"uuid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Wb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"nanoid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Bb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"cuid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Hb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"cuid2",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Jb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"ulid",code:X.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),se(o,{validation:"url",code:X.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"regex",code:X.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.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),se(o,{code:X.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?l3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?a3.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?i3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{code:X.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Yb.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"duration",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?c3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"ip",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?u3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"jwt",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?d3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"cidr",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?o3.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"base64",code:X.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?s3.test(t.data)||(o=this._getOrReturnCtx(t,o),se(o,{validation:"base64url",code:X.invalid_string,message:s.message}),n.dirty()):De.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:X.invalid_string,...pe.errToObj(n)})}_addCheck(t){return new Dr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...pe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...pe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...pe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...pe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...pe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...pe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...pe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...pe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...pe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...pe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...pe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...pe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...pe.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...pe.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...pe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...pe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...pe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...pe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...pe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...pe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...pe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...pe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...pe.errToObj(r)})}nonempty(t){return this.min(1,pe.errToObj(t))}trim(){return new Dr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Dr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Dr({...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 r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}Dr.create=e=>new Dr({checks:[],typeName:te.ZodString,coerce:e?.coerce??!1,...Ae(e)});function p3(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}class On extends je{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)!==ue.number){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:ue.number,received:s.parsedType}),xe}let n;const o=new jt;for(const s of this._def.checks)s.kind==="int"?De.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),se(n,{code:X.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.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)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?p3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),se(n,{code:X.not_finite,message:s.message}),o.dirty()):De.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,pe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,pe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,pe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,pe.toString(r))}setLimit(t,r,n,o){return new On({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:pe.toString(o)}]})}_addCheck(t){return new On({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:pe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:pe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:pe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:pe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:pe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:pe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:pe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:pe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:pe.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&De.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}}On.create=e=>new On({checks:[],typeName:te.ZodNumber,coerce:e?.coerce||!1,...Ae(e)});class vo extends je{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)!==ue.bigint)return this._getInvalidInput(t);let n;const o=new jt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.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)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),se(n,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):De.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return se(r,{code:X.invalid_type,expected:ue.bigint,received:r.parsedType}),xe}gte(t,r){return this.setLimit("min",t,!0,pe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,pe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,pe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,pe.toString(r))}setLimit(t,r,n,o){return new vo({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:pe.toString(o)}]})}_addCheck(t){return new vo({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:pe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:pe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:pe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:pe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:pe.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}vo.create=e=>new vo({checks:[],typeName:te.ZodBigInt,coerce:e?.coerce??!1,...Ae(e)});class Op extends je{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ue.boolean){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ue.boolean,received:n.parsedType}),xe}return Zt(t.data)}}Op.create=e=>new Op({typeName:te.ZodBoolean,coerce:e?.coerce||!1,...Ae(e)});class xs extends je{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ue.date){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_type,expected:ue.date,received:s.parsedType}),xe}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return se(s,{code:X.invalid_date}),xe}const n=new jt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),se(o,{code:X.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):De.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new xs({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:pe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:pe.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}xs.create=e=>new xs({checks:[],coerce:e?.coerce||!1,typeName:te.ZodDate,...Ae(e)});class Ap extends je{_parse(t){if(this._getType(t)!==ue.symbol){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ue.symbol,received:n.parsedType}),xe}return Zt(t.data)}}Ap.create=e=>new Ap({typeName:te.ZodSymbol,...Ae(e)});class qp extends je{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ue.undefined,received:n.parsedType}),xe}return Zt(t.data)}}qp.create=e=>new qp({typeName:te.ZodUndefined,...Ae(e)});class Lp extends je{_parse(t){if(this._getType(t)!==ue.null){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ue.null,received:n.parsedType}),xe}return Zt(t.data)}}Lp.create=e=>new Lp({typeName:te.ZodNull,...Ae(e)});class jp extends je{constructor(){super(...arguments),this._any=!0}_parse(t){return Zt(t.data)}}jp.create=e=>new jp({typeName:te.ZodAny,...Ae(e)});class Up extends je{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Zt(t.data)}}Up.create=e=>new Up({typeName:te.ZodUnknown,...Ae(e)});class zr extends je{_parse(t){const r=this._getOrReturnCtx(t);return se(r,{code:X.invalid_type,expected:ue.never,received:r.parsedType}),xe}}zr.create=e=>new zr({typeName:te.ZodNever,...Ae(e)});class Dp extends je{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ue.void,received:n.parsedType}),xe}return Zt(t.data)}}Dp.create=e=>new Dp({typeName:te.ZodVoid,...Ae(e)});class pr extends je{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ue.array)return se(r,{code:X.invalid_type,expected:ue.array,received:r.parsedType}),xe;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(se(r,{code:a?X.too_big:X.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}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(se(r,{code:X.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(se(r,{code:X.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new Ur(r,a,r.path,i)))).then(a=>jt.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Ur(r,a,r.path,i)));return jt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new pr({...this._def,minLength:{value:t,message:pe.toString(r)}})}max(t,r){return new pr({...this._def,maxLength:{value:t,message:pe.toString(r)}})}length(t,r){return new pr({...this._def,exactLength:{value:t,message:pe.toString(r)}})}nonempty(t){return this.min(1,t)}}pr.create=(e,t)=>new pr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:te.ZodArray,...Ae(t)});function An(e){if(e instanceof ct){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Fr.create(An(n))}return new ct({...e._def,shape:()=>t})}else return e instanceof pr?new pr({...e._def,type:An(e.element)}):e instanceof Fr?Fr.create(An(e.unwrap())):e instanceof jn?jn.create(An(e.unwrap())):e instanceof un?un.create(e.items.map(t=>An(t))):e}class ct extends je{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(),r=De.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ue.object){const c=this._getOrReturnCtx(t);return se(c,{code:X.invalid_type,expected:ue.object,received:c.parsedType}),xe}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof zr&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=s[c],g=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ur(o,g,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof zr){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(se(o,{code:X.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const g=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ur(o,g,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const g=await u.key,p=await u.value;c.push({key:g,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>jt.mergeObjectSync(n,c)):jt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return pe.errToObj,new ct({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:pe.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new ct({...this._def,unknownKeys:"strip"})}passthrough(){return new ct({...this._def,unknownKeys:"passthrough"})}extend(t){return new ct({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ct({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:te.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new ct({...this._def,catchall:t})}pick(t){const r={};for(const n of De.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ct({...this._def,shape:()=>r})}omit(t){const r={};for(const n of De.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new ct({...this._def,shape:()=>r})}deepPartial(){return An(this)}partial(t){const r={};for(const n of De.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new ct({...this._def,shape:()=>r})}required(t){const r={};for(const n of De.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Fr;)s=s._def.innerType;r[n]=s}return new ct({...this._def,shape:()=>r})}keyof(){return Zp(De.objectKeys(this.shape))}}ct.create=(e,t)=>new ct({shape:()=>e,unknownKeys:"strip",catchall:zr.create(),typeName:te.ZodObject,...Ae(t)}),ct.strictCreate=(e,t)=>new ct({shape:()=>e,unknownKeys:"strict",catchall:zr.create(),typeName:te.ZodObject,...Ae(t)}),ct.lazycreate=(e,t)=>new ct({shape:e,unknownKeys:"strip",catchall:zr.create(),typeName:te.ZodObject,...Ae(t)});class Es extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n=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 r.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new kr(i.ctx.common.issues));return se(r,{code:X.invalid_union,unionErrors:a}),xe}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new kr(l));return se(r,{code:X.invalid_union,unionErrors:i}),xe}}get options(){return this._def.options}}Es.create=(e,t)=>new Es({options:e,typeName:te.ZodUnion,...Ae(t)});function ji(e,t){const r=jr(e),n=jr(t);if(e===t)return{valid:!0,data:e};if(r===ue.object&&n===ue.object){const o=De.objectKeys(t),s=De.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=ji(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===ue.array&&n===ue.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=ji(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ue.date&&n===ue.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class $s extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if($p(s)||$p(a))return xe;const i=ji(s.value,a.value);return i.valid?((Rp(s)||Rp(a))&&r.dirty(),{status:r.value,value:i.data}):(se(n,{code:X.invalid_intersection_types}),xe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}$s.create=(e,t,r)=>new $s({left:e,right:t,typeName:te.ZodIntersection,...Ae(r)});class un extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.array)return se(n,{code:X.invalid_type,expected:ue.array,received:n.parsedType}),xe;if(n.data.length<this._def.items.length)return se(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),xe;!this._def.rest&&n.data.length>this._def.items.length&&(se(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Ur(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>jt.mergeArray(r,a)):jt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new un({...this._def,rest:t})}}un.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new un({items:e,typeName:te.ZodTuple,rest:null,...Ae(t)})};class zp extends je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.map)return se(n,{code:X.invalid_type,expected:ue.map,received:n.parsedType}),xe;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Ur(n,i,n.path,[c,"key"])),value:s._parse(new Ur(n,l,n.path,[c,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of a){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}zp.create=(e,t,r)=>new zp({valueType:t,keyType:e,typeName:te.ZodMap,...Ae(r)});class wo extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.set)return se(n,{code:X.invalid_type,expected:ue.set,received:n.parsedType}),xe;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(se(n,{code:X.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(se(n,{code:X.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return xe;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>s._parse(new Ur(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new wo({...this._def,minSize:{value:t,message:pe.toString(r)}})}max(t,r){return new wo({...this._def,maxSize:{value:t,message:pe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}wo.create=(e,t)=>new wo({valueType:e,minSize:null,maxSize:null,typeName:te.ZodSet,...Ae(t)});class Fp extends je{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Fp.create=(e,t)=>new Fp({getter:e,typeName:te.ZodLazy,...Ae(t)});class Vp extends je{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return se(r,{received:r.data,code:X.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:t.data}}get value(){return this._def.value}}Vp.create=(e,t)=>new Vp({value:e,typeName:te.ZodLiteral,...Ae(t)});function Zp(e,t){return new qn({values:e,typeName:te.ZodEnum,...Ae(t)})}class qn extends je{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return se(r,{expected:De.joinValues(n),received:r.parsedType,code:X.invalid_type}),xe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return se(r,{received:r.data,code:X.invalid_enum_value,options:n}),xe}return Zt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return qn.create(t,{...this._def,...r})}exclude(t,r=this._def){return qn.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}qn.create=Zp;class Bp extends je{_parse(t){const r=De.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ue.string&&n.parsedType!==ue.number){const o=De.objectValues(r);return se(n,{expected:De.joinValues(o),received:n.parsedType,code:X.invalid_type}),xe}if(this._cache||(this._cache=new Set(De.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=De.objectValues(r);return se(n,{received:n.data,code:X.invalid_enum_value,options:o}),xe}return Zt(t.data)}get enum(){return this._def.values}}Bp.create=(e,t)=>new Bp({values:e,typeName:te.ZodNativeEnum,...Ae(t)});class Rs extends je{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ue.promise&&r.common.async===!1)return se(r,{code:X.invalid_type,expected:ue.promise,received:r.parsedType}),xe;const n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return Zt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Rs.create=(e,t)=>new Rs({type:e,typeName:te.ZodPromise,...Ae(t)});class Ln extends je{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===te.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{se(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return xe;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?xe:l.status==="dirty"||r.value==="dirty"?_o(l.value):l});{if(r.value==="aborted")return xe;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?xe:i.status==="dirty"||r.value==="dirty"?_o(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(n.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(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?xe:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?xe:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Nn(a))return xe;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:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Nn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):xe);De.assertNever(o)}}Ln.create=(e,t,r)=>new Ln({schema:e,typeName:te.ZodEffects,effect:t,...Ae(r)}),Ln.createWithPreprocess=(e,t,r)=>new Ln({schema:t,effect:{type:"preprocess",transform:e},typeName:te.ZodEffects,...Ae(r)});class Fr extends je{_parse(t){return this._getType(t)===ue.undefined?Zt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Fr.create=(e,t)=>new Fr({innerType:e,typeName:te.ZodOptional,...Ae(t)});class jn extends je{_parse(t){return this._getType(t)===ue.null?Zt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}jn.create=(e,t)=>new jn({innerType:e,typeName:te.ZodNullable,...Ae(t)});class Ui extends je{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===ue.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}Ui.create=(e,t)=>new Ui({innerType:e,typeName:te.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ae(t)});class Di extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Is(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new kr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new kr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Di.create=(e,t)=>new Di({innerType:e,typeName:te.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ae(t)});class Hp extends je{_parse(t){if(this._getType(t)!==ue.nan){const n=this._getOrReturnCtx(t);return se(n,{code:X.invalid_type,expected:ue.nan,received:n.parsedType}),xe}return{status:"valid",value:t.data}}}Hp.create=e=>new Hp({typeName:te.ZodNaN,...Ae(e)});class f3 extends je{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class zi extends je{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"?(r.dirty(),_o(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?xe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new zi({in:t,out:r,typeName:te.ZodPipeline})}}class Fi extends je{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Nn(o)&&(o.value=Object.freeze(o.value)),o);return Is(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}Fi.create=(e,t)=>new Fi({innerType:e,typeName:te.ZodReadonly,...Ae(t)});var te;(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"})(te||(te={}));const Ke=Dr.create,fr=On.create;zr.create;const Vr=pr.create,Yt=ct.create,Vi=Es.create;$s.create,un.create;const Ps=qn.create;Rs.create,Fr.create,jn.create;class Jp extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Zi(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=Zi,onError:r=Zi,onRetry:n=Zi,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(w){const m=a?w.replace(/^\xEF\xBB\xBF/,""):w,[b,_]=h3(`${s}${m}`);for(const f of b)g(f);s=_,a=!1}function g(w){if(w===""){h();return}if(w.startsWith(":")){o&&o(w.slice(w.startsWith(": ")?2:1));return}const m=w.indexOf(":");if(m!==-1){const b=w.slice(0,m),_=w[m+1]===" "?2:1,f=w.slice(m+_);p(b,f,w);return}p(w,"",w)}function p(w,m,b){switch(w){case"event":c=m;break;case"data":l=`${l}${m}
31
- `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):r(new Jp(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:b}));break;default:r(new Jp(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:m,line:b}));break}}function h(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
32
- `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function y(w={}){s&&w.consume&&g(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:y}}function h3(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
30
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const m=u[1];if(t===u[0]){a(u);continue}if(n.external){const f=n.external.registry.get(u[0])?.id;if(t!==u[0]&&f){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(m.cycle){a(u);continue}if(m.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,m)=>{const p=this.seen.get(u),f=p.def??p.schema,g={...f};if(p.ref===null)return;const v=p.ref;if(p.ref=null,v){i(v,m);const y=this.seen.get(v).schema;y.$ref&&m.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(y)):(Object.assign(f,y),Object.assign(f,g))}p.isParent||this.override({zodSchema:u,jsonSchema:f,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[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}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const m=u[1];m.def&&m.defId&&(c[m.defId]=m.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function sb(e,t){if(e instanceof yp){const n=new Ip(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;n.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;s[l]=n.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const r=new Ip(t);return r.process(e),r.emit(e,t)}function _t(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.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 _t(o.element,r);case"object":{for(const s in o.shape)if(_t(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(_t(s,r))return!0;return!1}case"intersection":return _t(o.left,r)||_t(o.right,r);case"tuple":{for(const s of o.items)if(_t(s,r))return!0;return!!(o.rest&&_t(o.rest,r))}case"record":return _t(o.keyType,r)||_t(o.valueType,r);case"map":return _t(o.keyType,r)||_t(o.valueType,r);case"set":return _t(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return _t(o.innerType,r);case"lazy":return _t(o.getter(),r);case"default":return _t(o.innerType,r);case"prefault":return _t(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return _t(o.in,r)||_t(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const ab=J("ZodISODateTime",(e,t)=>{$1.init(e,t),at.init(e,t)});function xp(e){return Ow(ab,e)}const ib=J("ZodISODate",(e,t)=>{R1.init(e,t),at.init(e,t)});function lb(e){return Aw(ib,e)}const cb=J("ZodISOTime",(e,t)=>{P1.init(e,t),at.init(e,t)});function ub(e){return qw(cb,e)}const db=J("ZodISODuration",(e,t)=>{N1.init(e,t),at.init(e,t)});function pb(e){return Lw(db,e)}const As=J("ZodError",(e,t)=>{Jd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Iv(e,r)},flatten:{value:r=>Sv(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),fb=xv(As),hb=Ev(As),mb=Wd(As),Ep=Yd(As),Ke=J("ZodType",(e,t)=>(Ge.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>_n(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>fb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>mb(e,r,n),e.parseAsync=async(r,n)=>hb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ep(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(s3(r,n)),e.superRefine=r=>e.check(a3(r)),e.overwrite=r=>e.check(xo(r)),e.optional=()=>le(e),e.nullable=()=>Dp(e),e.nullish=()=>le(Dp(e)),e.nonoptional=r=>Yb(e,r),e.array=()=>q(e),e.or=r=>oe([e,r]),e.and=r=>Wi(e,r),e.transform=r=>Yi(e,Lp(r)),e.default=r=>Gb(e,r),e.prefault=r=>Kb(e,r),e.catch=r=>Xb(e,r),e.pipe=r=>Yi(e,r),e.readonly=()=>r3(e),e.describe=r=>{const n=e.clone();return Io.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Io.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Io.get(e);const n=e.clone();return Io.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),$p=J("_ZodString",(e,t)=>{Zi.init(e,t),Ke.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Hw(...n)),e.includes=(...n)=>e.check(Ww(...n)),e.startsWith=(...n)=>e.check(Kw(...n)),e.endsWith=(...n)=>e.check(Yw(...n)),e.min=(...n)=>e.check(Os(...n)),e.max=(...n)=>e.check(Tp(...n)),e.length=(...n)=>e.check(Sp(...n)),e.nonempty=(...n)=>e.check(Os(1,...n)),e.lowercase=n=>e.check(Jw(n)),e.uppercase=n=>e.check(Gw(n)),e.trim=()=>e.check(Xw()),e.normalize=(...n)=>e.check(Qw(...n)),e.toLowerCase=()=>e.check(eb()),e.toUpperCase=()=>e.check(tb())}),gb=J("ZodString",(e,t)=>{Zi.init(e,t),$p.init(e,t),e.email=r=>e.check(mw(yb,r)),e.url=r=>e.check(vp(Pp,r)),e.jwt=r=>e.check(Mw(Nb,r)),e.emoji=r=>e.check(ww(vb,r)),e.guid=r=>e.check(_p(Rp,r)),e.uuid=r=>e.check(gw(qs,r)),e.uuidv4=r=>e.check(yw(qs,r)),e.uuidv6=r=>e.check(_w(qs,r)),e.uuidv7=r=>e.check(vw(qs,r)),e.nanoid=r=>e.check(bw(wb,r)),e.guid=r=>e.check(_p(Rp,r)),e.cuid=r=>e.check(kw(bb,r)),e.cuid2=r=>e.check(Cw(kb,r)),e.ulid=r=>e.check(Tw(Cb,r)),e.base64=r=>e.check(wp(Np,r)),e.base64url=r=>e.check(Pw(Rb,r)),e.xid=r=>e.check(Sw(Tb,r)),e.ksuid=r=>e.check(Iw(Sb,r)),e.ipv4=r=>e.check(xw(Ib,r)),e.ipv6=r=>e.check(Ew(xb,r)),e.cidrv4=r=>e.check($w(Eb,r)),e.cidrv6=r=>e.check(Rw($b,r)),e.e164=r=>e.check(Nw(Pb,r)),e.datetime=r=>e.check(xp(r)),e.date=r=>e.check(lb(r)),e.time=r=>e.check(ub(r)),e.duration=r=>e.check(pb(r))});function d(e){return hw(gb,e)}const at=J("ZodStringFormat",(e,t)=>{et.init(e,t),$p.init(e,t)}),yb=J("ZodEmail",(e,t)=>{w1.init(e,t),at.init(e,t)}),Rp=J("ZodGUID",(e,t)=>{_1.init(e,t),at.init(e,t)}),qs=J("ZodUUID",(e,t)=>{v1.init(e,t),at.init(e,t)}),Pp=J("ZodURL",(e,t)=>{b1.init(e,t),at.init(e,t)});function _b(e){return vp(Pp,e)}const vb=J("ZodEmoji",(e,t)=>{k1.init(e,t),at.init(e,t)}),wb=J("ZodNanoID",(e,t)=>{C1.init(e,t),at.init(e,t)}),bb=J("ZodCUID",(e,t)=>{T1.init(e,t),at.init(e,t)}),kb=J("ZodCUID2",(e,t)=>{S1.init(e,t),at.init(e,t)}),Cb=J("ZodULID",(e,t)=>{I1.init(e,t),at.init(e,t)}),Tb=J("ZodXID",(e,t)=>{x1.init(e,t),at.init(e,t)}),Sb=J("ZodKSUID",(e,t)=>{E1.init(e,t),at.init(e,t)}),Ib=J("ZodIPv4",(e,t)=>{M1.init(e,t),at.init(e,t)}),xb=J("ZodIPv6",(e,t)=>{O1.init(e,t),at.init(e,t)}),Eb=J("ZodCIDRv4",(e,t)=>{A1.init(e,t),at.init(e,t)}),$b=J("ZodCIDRv6",(e,t)=>{q1.init(e,t),at.init(e,t)}),Np=J("ZodBase64",(e,t)=>{L1.init(e,t),at.init(e,t)});function Mp(e){return wp(Np,e)}const Rb=J("ZodBase64URL",(e,t)=>{D1.init(e,t),at.init(e,t)}),Pb=J("ZodE164",(e,t)=>{U1.init(e,t),at.init(e,t)}),Nb=J("ZodJWT",(e,t)=>{F1.init(e,t),at.init(e,t)}),Gi=J("ZodNumber",(e,t)=>{ap.init(e,t),Ke.init(e,t),e.gt=(n,o)=>e.check(kp(n,o)),e.gte=(n,o)=>e.check(Ji(n,o)),e.min=(n,o)=>e.check(Ji(n,o)),e.lt=(n,o)=>e.check(bp(n,o)),e.lte=(n,o)=>e.check(Hi(n,o)),e.max=(n,o)=>e.check(Hi(n,o)),e.int=n=>e.check(Op(n)),e.safe=n=>e.check(Op(n)),e.positive=n=>e.check(kp(0,n)),e.nonnegative=n=>e.check(Ji(0,n)),e.negative=n=>e.check(bp(0,n)),e.nonpositive=n=>e.check(Hi(0,n)),e.multipleOf=(n,o)=>e.check(Cp(n,o)),e.step=(n,o)=>e.check(Cp(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function j(e){return jw(Gi,e)}const Mb=J("ZodNumberFormat",(e,t)=>{V1.init(e,t),Gi.init(e,t)});function Op(e){return Uw(Mb,e)}const Ob=J("ZodBoolean",(e,t)=>{Z1.init(e,t),Ke.init(e,t)});function pe(e){return zw(Ob,e)}const Ab=J("ZodNull",(e,t)=>{B1.init(e,t),Ke.init(e,t)});function Ls(e){return Fw(Ab,e)}const qb=J("ZodAny",(e,t)=>{H1.init(e,t),Ke.init(e,t)});function wt(){return Vw(qb)}const Lb=J("ZodUnknown",(e,t)=>{J1.init(e,t),Ke.init(e,t)});function $e(){return Zw(Lb)}const jb=J("ZodNever",(e,t)=>{G1.init(e,t),Ke.init(e,t)});function Db(e){return Bw(jb,e)}const Ub=J("ZodArray",(e,t)=>{W1.init(e,t),Ke.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Os(r,n)),e.nonempty=r=>e.check(Os(1,r)),e.max=(r,n)=>e.check(Tp(r,n)),e.length=(r,n)=>e.check(Sp(r,n)),e.unwrap=()=>e.element});function q(e,t){return rb(Ub,e,t)}const Ap=J("ZodObject",(e,t)=>{K1.init(e,t),Ke.init(e,t),Fe(e,"shape",()=>t.shape),e.keyof=()=>fe(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:$e()}),e.loose=()=>e.clone({...e._zod.def,catchall:$e()}),e.strict=()=>e.clone({...e._zod.def,catchall:Db()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>bv(e,r),e.merge=r=>kv(e,r),e.pick=r=>vv(e,r),e.omit=r=>wv(e,r),e.partial=(...r)=>Cv(jp,e,r[0]),e.required=(...r)=>Tv(Up,e,r[0])});function C(e,t){const r={type:"object",get shape(){return Es(this,"shape",{...e}),this.shape},...ue(t)};return new Ap(r)}function it(e,t){return new Ap({type:"object",get shape(){return Es(this,"shape",{...e}),this.shape},catchall:$e(),...ue(t)})}const qp=J("ZodUnion",(e,t)=>{up.init(e,t),Ke.init(e,t),e.options=t.options});function oe(e,t){return new qp({type:"union",options:e,...ue(t)})}const zb=J("ZodDiscriminatedUnion",(e,t)=>{qp.init(e,t),Y1.init(e,t)});function De(e,t,r){return new zb({type:"union",options:t,discriminator:e,...ue(r)})}const Fb=J("ZodIntersection",(e,t)=>{Q1.init(e,t),Ke.init(e,t)});function Wi(e,t){return new Fb({type:"intersection",left:e,right:t})}const Vb=J("ZodRecord",(e,t)=>{X1.init(e,t),Ke.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ge(e,t,r){return new Vb({type:"record",keyType:e,valueType:t,...ue(r)})}const Ki=J("ZodEnum",(e,t)=>{ew.init(e,t),Ke.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const a of n)if(r.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Ki({...t,checks:[],...ue(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Ki({...t,checks:[],...ue(o),entries:s})}});function fe(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ki({type:"enum",entries:r,...ue(t)})}const Zb=J("ZodLiteral",(e,t)=>{tw.init(e,t),Ke.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 R(e,t){return new Zb({type:"literal",values:Array.isArray(e)?e:[e],...ue(t)})}const Bb=J("ZodTransform",(e,t)=>{rw.init(e,t),Ke.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(So(s,r.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(So(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Lp(e){return new Bb({type:"transform",transform:e})}const jp=J("ZodOptional",(e,t)=>{nw.init(e,t),Ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function le(e){return new jp({type:"optional",innerType:e})}const Hb=J("ZodNullable",(e,t)=>{ow.init(e,t),Ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Dp(e){return new Hb({type:"nullable",innerType:e})}const Jb=J("ZodDefault",(e,t)=>{sw.init(e,t),Ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Gb(e,t){return new Jb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Wb=J("ZodPrefault",(e,t)=>{aw.init(e,t),Ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Kb(e,t){return new Wb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Up=J("ZodNonOptional",(e,t)=>{iw.init(e,t),Ke.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yb(e,t){return new Up({type:"nonoptional",innerType:e,...ue(t)})}const Qb=J("ZodCatch",(e,t)=>{lw.init(e,t),Ke.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Xb(e,t){return new Qb({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const e3=J("ZodPipe",(e,t)=>{cw.init(e,t),Ke.init(e,t),e.in=t.in,e.out=t.out});function Yi(e,t){return new e3({type:"pipe",in:e,out:t})}const t3=J("ZodReadonly",(e,t)=>{uw.init(e,t),Ke.init(e,t)});function r3(e){return new t3({type:"readonly",innerType:e})}const n3=J("ZodLazy",(e,t)=>{dw.init(e,t),Ke.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Qi(e){return new n3({type:"lazy",getter:e})}const Xi=J("ZodCustom",(e,t)=>{pw.init(e,t),Ke.init(e,t)});function o3(e){const t=new Dt({check:"custom"});return t._zod.check=e,t}function zp(e,t){return nb(Xi,e??(()=>!0),t)}function s3(e,t={}){return ob(Xi,e,t)}function a3(e){const t=o3(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(So(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(So(o))}},e(r.value,r)));return t}function js(e,t={error:`Input not instance of ${e.name}`}){const r=new Xi({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...ue(t)});return r._zod.bag.Class=e,r}function Fp(e,t){return Yi(Lp(e),t)}const Vp={custom:"custom"};function Zp(e){return Dw(Gi,e)}var Ue;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,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 n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Ue||(Ue={}));var Bp;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Bp||(Bp={}));const ce=Ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wr=e=>{switch(typeof e){case"undefined":return ce.undefined;case"string":return ce.string;case"number":return Number.isNaN(e)?ce.nan:ce.number;case"boolean":return ce.boolean;case"function":return ce.function;case"bigint":return ce.bigint;case"symbol":return ce.symbol;case"object":return Array.isArray(e)?ce.array:e===null?ce.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ce.promise:typeof Map<"u"&&e instanceof Map?ce.map:typeof Set<"u"&&e instanceof Set?ce.set:typeof Date<"u"&&e instanceof Date?ce.date:ce.object;default:return ce.unknown}},ee=Ue.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 Nr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_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)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof Nr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ue.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Nr.create=e=>new Nr(e);const el=(e,t)=>{let r;switch(e.code){case ee.invalid_type:e.received===ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ee.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ue.jsonStringifyReplacer)}`;break;case ee.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ue.joinValues(e.keys,", ")}`;break;case ee.invalid_union:r="Invalid input";break;case ee.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ue.joinValues(e.options)}`;break;case ee.invalid_enum_value:r=`Invalid enum value. Expected ${Ue.joinValues(e.options)}, received '${e.received}'`;break;case ee.invalid_arguments:r="Invalid function arguments";break;case ee.invalid_return_type:r="Invalid function return type";break;case ee.invalid_date:r="Invalid date";break;case ee.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Ue.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ee.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ee.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ee.custom:r="Invalid input";break;case ee.invalid_intersection_types:r="Intersection results could not be merged";break;case ee.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ee.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ue.assertNever(e)}return{message:r}};let i3=el;function l3(){return i3}const c3=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}};function ae(e,t){const r=l3(),n=c3({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===el?void 0:el].filter(o=>!!o)});e.common.issues.push(n)}class Zt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return xe;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,a=await o.value;n.push({key:s,value:a})}return Zt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return xe;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:t.value,value:n}}}const xe=Object.freeze({status:"aborted"}),Eo=e=>({status:"dirty",value:e}),Kt=e=>({status:"valid",value:e}),Hp=e=>e.status==="aborted",Jp=e=>e.status==="dirty",zn=e=>e.status==="valid",Ds=e=>typeof Promise<"u"&&e instanceof Promise;var de;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(de||(de={}));class Kr{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,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 Gp=(e,t)=>{if(zn(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 r=new Nr(e.common.issues);return this._error=r,this._error}}};function Ae(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))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??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:o}}class Le{get description(){return this._def.description}_getType(t){return Wr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Zt,ctx:{common:t.parent.common,data:t.data,parsedType:Wr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Ds(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Gp(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return zn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>zn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(Ds(o)?o:Promise.resolve(o));return Gp(n,s)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:ee.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Bn({schema:this,typeName:ne.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:r=>this["~validate"](r)}}optional(){return Xr.create(this,this._def)}nullable(){return Hn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return kr.create(this)}promise(){return Vs.create(this,this._def)}or(t){return zs.create([this,t],this._def)}and(t){return Fs.create(this,t,this._def)}transform(t){return new Bn({...Ae(this._def),schema:this,typeName:ne.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new nl({...Ae(this._def),innerType:this,defaultValue:r,typeName:ne.ZodDefault})}brand(){return new N3({typeName:ne.ZodBranded,type:this,...Ae(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new ol({...Ae(this._def),innerType:this,catchValue:r,typeName:ne.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return sl.create(this,t)}readonly(){return al.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const u3=/^c[^\s-]{8,}$/i,d3=/^[0-9a-z]+$/,p3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,f3=/^[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,h3=/^[a-z0-9_-]{21}$/i,m3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,g3=/^[-+]?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)?)??$/,y3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let tl;const v3=/^(?:(?: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])$/,w3=/^(?:(?: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])$/,b3=/^(([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]))$/,k3=/^(([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])$/,C3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,T3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Wp="((\\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])))",S3=new RegExp(`^${Wp}$`);function Kp(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function I3(e){return new RegExp(`^${Kp(e)}$`)}function x3(e){let t=`${Wp}T${Kp(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function E3(e,t){return!!((t==="v4"||!t)&&v3.test(e)||(t==="v6"||!t)&&b3.test(e))}function $3(e,t){if(!m3.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function R3(e,t){return!!((t==="v4"||!t)&&w3.test(e)||(t==="v6"||!t)&&k3.test(e))}class Yr extends Le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ce.string){const s=this._getOrReturnCtx(t);return ae(s,{code:ee.invalid_type,expected:ce.string,received:s.parsedType}),xe}const n=new Zt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.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?ae(o,{code:ee.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&ae(o,{code:ee.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")y3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"email",code:ee.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")tl||(tl=new RegExp(_3,"u")),tl.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"emoji",code:ee.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")f3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"uuid",code:ee.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")h3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"nanoid",code:ee.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")u3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"cuid",code:ee.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")d3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"cuid2",code:ee.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")p3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"ulid",code:ee.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ae(o,{validation:"url",code:ee.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"regex",code:ee.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.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),ae(o,{code:ee.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?x3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?S3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?I3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?g3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"duration",code:ee.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?E3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"ip",code:ee.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?$3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"jwt",code:ee.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?R3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"cidr",code:ee.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?C3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"base64",code:ee.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?T3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"base64url",code:ee.invalid_string,message:s.message}),n.dirty()):Ue.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:ee.invalid_string,...de.errToObj(n)})}_addCheck(t){return new Yr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...de.errToObj(t)})}url(t){return this._addCheck({kind:"url",...de.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...de.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...de.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...de.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...de.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...de.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...de.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...de.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...de.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...de.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...de.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...de.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...de.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...de.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...de.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...de.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...de.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...de.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...de.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...de.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...de.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...de.errToObj(r)})}nonempty(t){return this.min(1,de.errToObj(t))}trim(){return new Yr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Yr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Yr({...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 r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}Yr.create=e=>new Yr({checks:[],typeName:ne.ZodString,coerce:e?.coerce??!1,...Ae(e)});function P3(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}class Fn extends Le{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)!==ce.number){const s=this._getOrReturnCtx(t);return ae(s,{code:ee.invalid_type,expected:ce.number,received:s.parsedType}),xe}let n;const o=new Zt;for(const s of this._def.checks)s.kind==="int"?Ue.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.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)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?P3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.not_finite,message:s.message}),o.dirty()):Ue.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,de.toString(r))}gt(t,r){return this.setLimit("min",t,!1,de.toString(r))}lte(t,r){return this.setLimit("max",t,!0,de.toString(r))}lt(t,r){return this.setLimit("max",t,!1,de.toString(r))}setLimit(t,r,n,o){return new Fn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:de.toString(o)}]})}_addCheck(t){return new Fn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:de.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:de.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:de.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:de.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:de.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:de.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:de.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:de.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:de.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Ue.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}}Fn.create=e=>new Fn({checks:[],typeName:ne.ZodNumber,coerce:e?.coerce||!1,...Ae(e)});class $o extends Le{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)!==ce.bigint)return this._getInvalidInput(t);let n;const o=new Zt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.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)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:ee.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Ue.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return ae(r,{code:ee.invalid_type,expected:ce.bigint,received:r.parsedType}),xe}gte(t,r){return this.setLimit("min",t,!0,de.toString(r))}gt(t,r){return this.setLimit("min",t,!1,de.toString(r))}lte(t,r){return this.setLimit("max",t,!0,de.toString(r))}lt(t,r){return this.setLimit("max",t,!1,de.toString(r))}setLimit(t,r,n,o){return new $o({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:de.toString(o)}]})}_addCheck(t){return new $o({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:de.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:de.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:de.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:de.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:de.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}$o.create=e=>new $o({checks:[],typeName:ne.ZodBigInt,coerce:e?.coerce??!1,...Ae(e)});class Yp extends Le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ce.boolean){const n=this._getOrReturnCtx(t);return ae(n,{code:ee.invalid_type,expected:ce.boolean,received:n.parsedType}),xe}return Kt(t.data)}}Yp.create=e=>new Yp({typeName:ne.ZodBoolean,coerce:e?.coerce||!1,...Ae(e)});class Us extends Le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ce.date){const s=this._getOrReturnCtx(t);return ae(s,{code:ee.invalid_type,expected:ce.date,received:s.parsedType}),xe}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return ae(s,{code:ee.invalid_date}),xe}const n=new Zt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:ee.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ue.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Us({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:de.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:de.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}Us.create=e=>new Us({checks:[],coerce:e?.coerce||!1,typeName:ne.ZodDate,...Ae(e)});class Qp extends Le{_parse(t){if(this._getType(t)!==ce.symbol){const n=this._getOrReturnCtx(t);return ae(n,{code:ee.invalid_type,expected:ce.symbol,received:n.parsedType}),xe}return Kt(t.data)}}Qp.create=e=>new Qp({typeName:ne.ZodSymbol,...Ae(e)});class Xp extends Le{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return ae(n,{code:ee.invalid_type,expected:ce.undefined,received:n.parsedType}),xe}return Kt(t.data)}}Xp.create=e=>new Xp({typeName:ne.ZodUndefined,...Ae(e)});class ef extends Le{_parse(t){if(this._getType(t)!==ce.null){const n=this._getOrReturnCtx(t);return ae(n,{code:ee.invalid_type,expected:ce.null,received:n.parsedType}),xe}return Kt(t.data)}}ef.create=e=>new ef({typeName:ne.ZodNull,...Ae(e)});class tf extends Le{constructor(){super(...arguments),this._any=!0}_parse(t){return Kt(t.data)}}tf.create=e=>new tf({typeName:ne.ZodAny,...Ae(e)});class rf extends Le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Kt(t.data)}}rf.create=e=>new rf({typeName:ne.ZodUnknown,...Ae(e)});class Qr extends Le{_parse(t){const r=this._getOrReturnCtx(t);return ae(r,{code:ee.invalid_type,expected:ce.never,received:r.parsedType}),xe}}Qr.create=e=>new Qr({typeName:ne.ZodNever,...Ae(e)});class nf extends Le{_parse(t){if(this._getType(t)!==ce.undefined){const n=this._getOrReturnCtx(t);return ae(n,{code:ee.invalid_type,expected:ce.void,received:n.parsedType}),xe}return Kt(t.data)}}nf.create=e=>new nf({typeName:ne.ZodVoid,...Ae(e)});class kr extends Le{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ce.array)return ae(r,{code:ee.invalid_type,expected:ce.array,received:r.parsedType}),xe;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(ae(r,{code:a?ee.too_big:ee.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}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(ae(r,{code:ee.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(ae(r,{code:ee.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new Kr(r,a,r.path,i)))).then(a=>Zt.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Kr(r,a,r.path,i)));return Zt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new kr({...this._def,minLength:{value:t,message:de.toString(r)}})}max(t,r){return new kr({...this._def,maxLength:{value:t,message:de.toString(r)}})}length(t,r){return new kr({...this._def,exactLength:{value:t,message:de.toString(r)}})}nonempty(t){return this.min(1,t)}}kr.create=(e,t)=>new kr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ne.ZodArray,...Ae(t)});function Vn(e){if(e instanceof gt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Xr.create(Vn(n))}return new gt({...e._def,shape:()=>t})}else return e instanceof kr?new kr({...e._def,type:Vn(e.element)}):e instanceof Xr?Xr.create(Vn(e.unwrap())):e instanceof Hn?Hn.create(Vn(e.unwrap())):e instanceof wn?wn.create(e.items.map(t=>Vn(t))):e}class gt extends Le{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(),r=Ue.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ce.object){const c=this._getOrReturnCtx(t);return ae(c,{code:ee.invalid_type,expected:ce.object,received:c.parsedType}),xe}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Qr&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=s[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Kr(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Qr){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(ae(o,{code:ee.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const m=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Kr(o,m,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const m=await u.key,p=await u.value;c.push({key:m,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Zt.mergeObjectSync(n,c)):Zt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return de.errToObj,new gt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:de.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new gt({...this._def,unknownKeys:"strip"})}passthrough(){return new gt({...this._def,unknownKeys:"passthrough"})}extend(t){return new gt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new gt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ne.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new gt({...this._def,catchall:t})}pick(t){const r={};for(const n of Ue.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new gt({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ue.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new gt({...this._def,shape:()=>r})}deepPartial(){return Vn(this)}partial(t){const r={};for(const n of Ue.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new gt({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ue.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Xr;)s=s._def.innerType;r[n]=s}return new gt({...this._def,shape:()=>r})}keyof(){return lf(Ue.objectKeys(this.shape))}}gt.create=(e,t)=>new gt({shape:()=>e,unknownKeys:"strip",catchall:Qr.create(),typeName:ne.ZodObject,...Ae(t)}),gt.strictCreate=(e,t)=>new gt({shape:()=>e,unknownKeys:"strict",catchall:Qr.create(),typeName:ne.ZodObject,...Ae(t)}),gt.lazycreate=(e,t)=>new gt({shape:e,unknownKeys:"strip",catchall:Qr.create(),typeName:ne.ZodObject,...Ae(t)});class zs extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n=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 r.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new Nr(i.ctx.common.issues));return ae(r,{code:ee.invalid_union,unionErrors:a}),xe}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new Nr(l));return ae(r,{code:ee.invalid_union,unionErrors:i}),xe}}get options(){return this._def.options}}zs.create=(e,t)=>new zs({options:e,typeName:ne.ZodUnion,...Ae(t)});function rl(e,t){const r=Wr(e),n=Wr(t);if(e===t)return{valid:!0,data:e};if(r===ce.object&&n===ce.object){const o=Ue.objectKeys(t),s=Ue.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=rl(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===ce.array&&n===ce.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=rl(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ce.date&&n===ce.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Fs extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(Hp(s)||Hp(a))return xe;const i=rl(s.value,a.value);return i.valid?((Jp(s)||Jp(a))&&r.dirty(),{status:r.value,value:i.data}):(ae(n,{code:ee.invalid_intersection_types}),xe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Fs.create=(e,t,r)=>new Fs({left:e,right:t,typeName:ne.ZodIntersection,...Ae(r)});class wn extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.array)return ae(n,{code:ee.invalid_type,expected:ce.array,received:n.parsedType}),xe;if(n.data.length<this._def.items.length)return ae(n,{code:ee.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),xe;!this._def.rest&&n.data.length>this._def.items.length&&(ae(n,{code:ee.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Kr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>Zt.mergeArray(r,a)):Zt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new wn({...this._def,rest:t})}}wn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wn({items:e,typeName:ne.ZodTuple,rest:null,...Ae(t)})};class of extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.map)return ae(n,{code:ee.invalid_type,expected:ce.map,received:n.parsedType}),xe;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Kr(n,i,n.path,[c,"key"])),value:s._parse(new Kr(n,l,n.path,[c,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of a){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}of.create=(e,t,r)=>new of({valueType:t,keyType:e,typeName:ne.ZodMap,...Ae(r)});class Ro extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ce.set)return ae(n,{code:ee.invalid_type,expected:ce.set,received:n.parsedType}),xe;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ae(n,{code:ee.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(ae(n,{code:ee.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return xe;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>s._parse(new Kr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Ro({...this._def,minSize:{value:t,message:de.toString(r)}})}max(t,r){return new Ro({...this._def,maxSize:{value:t,message:de.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Ro.create=(e,t)=>new Ro({valueType:e,minSize:null,maxSize:null,typeName:ne.ZodSet,...Ae(t)});class sf extends Le{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}sf.create=(e,t)=>new sf({getter:e,typeName:ne.ZodLazy,...Ae(t)});class af extends Le{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ae(r,{received:r.data,code:ee.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:t.data}}get value(){return this._def.value}}af.create=(e,t)=>new af({value:e,typeName:ne.ZodLiteral,...Ae(t)});function lf(e,t){return new Zn({values:e,typeName:ne.ZodEnum,...Ae(t)})}class Zn extends Le{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ae(r,{expected:Ue.joinValues(n),received:r.parsedType,code:ee.invalid_type}),xe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return ae(r,{received:r.data,code:ee.invalid_enum_value,options:n}),xe}return Kt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return Zn.create(t,{...this._def,...r})}exclude(t,r=this._def){return Zn.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}Zn.create=lf;class cf extends Le{_parse(t){const r=Ue.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ce.string&&n.parsedType!==ce.number){const o=Ue.objectValues(r);return ae(n,{expected:Ue.joinValues(o),received:n.parsedType,code:ee.invalid_type}),xe}if(this._cache||(this._cache=new Set(Ue.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Ue.objectValues(r);return ae(n,{received:n.data,code:ee.invalid_enum_value,options:o}),xe}return Kt(t.data)}get enum(){return this._def.values}}cf.create=(e,t)=>new cf({values:e,typeName:ne.ZodNativeEnum,...Ae(t)});class Vs extends Le{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ce.promise&&r.common.async===!1)return ae(r,{code:ee.invalid_type,expected:ce.promise,received:r.parsedType}),xe;const n=r.parsedType===ce.promise?r.data:Promise.resolve(r.data);return Kt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Vs.create=(e,t)=>new Vs({type:e,typeName:ne.ZodPromise,...Ae(t)});class Bn extends Le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ne.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{ae(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return xe;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?xe:l.status==="dirty"||r.value==="dirty"?Eo(l.value):l});{if(r.value==="aborted")return xe;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?xe:i.status==="dirty"||r.value==="dirty"?Eo(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(n.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(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?xe:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?xe:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!zn(a))return xe;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:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>zn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):xe);Ue.assertNever(o)}}Bn.create=(e,t,r)=>new Bn({schema:e,typeName:ne.ZodEffects,effect:t,...Ae(r)}),Bn.createWithPreprocess=(e,t,r)=>new Bn({schema:t,effect:{type:"preprocess",transform:e},typeName:ne.ZodEffects,...Ae(r)});class Xr extends Le{_parse(t){return this._getType(t)===ce.undefined?Kt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Xr.create=(e,t)=>new Xr({innerType:e,typeName:ne.ZodOptional,...Ae(t)});class Hn extends Le{_parse(t){return this._getType(t)===ce.null?Kt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Hn.create=(e,t)=>new Hn({innerType:e,typeName:ne.ZodNullable,...Ae(t)});class nl extends Le{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===ce.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}nl.create=(e,t)=>new nl({innerType:e,typeName:ne.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ae(t)});class ol extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ds(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Nr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Nr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ol.create=(e,t)=>new ol({innerType:e,typeName:ne.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ae(t)});class uf extends Le{_parse(t){if(this._getType(t)!==ce.nan){const n=this._getOrReturnCtx(t);return ae(n,{code:ee.invalid_type,expected:ce.nan,received:n.parsedType}),xe}return{status:"valid",value:t.data}}}uf.create=e=>new uf({typeName:ne.ZodNaN,...Ae(e)});class N3 extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class sl extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"?(r.dirty(),Eo(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?xe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new sl({in:t,out:r,typeName:ne.ZodPipeline})}}class al extends Le{_parse(t){const r=this._def.innerType._parse(t),n=o=>(zn(o)&&(o.value=Object.freeze(o.value)),o);return Ds(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}al.create=(e,t)=>new al({innerType:e,typeName:ne.ZodReadonly,...Ae(t)});var ne;(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"})(ne||(ne={}));const We=Yr.create,Cr=Fn.create;Qr.create;const en=kr.create,sr=gt.create,il=zs.create;Fs.create,wn.create;const Zs=Zn.create;Vs.create,Xr.create,Hn.create;class df extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function ll(e){}function pf(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=ll,onError:r=ll,onRetry:n=ll,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[w,_]=M3(`${s}${y}`);for(const h of w)m(h);s=_,a=!1}function m(v){if(v===""){f();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const w=v.slice(0,y),_=v[y+1]===" "?2:1,h=v.slice(y+_);p(w,h,v);return}p(v,"",v)}function p(v,y,w){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
31
+ `;break;case"id":i=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new df(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new df(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:y,line:w}));break}}function f(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
32
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function g(v={}){s&&v.consume&&m(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:g}}function M3(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
33
33
  `,n);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){r=e.slice(n);break}else{const i=e.slice(n,a);t.push(i),n=a+1,e[n-1]==="\r"&&e[n]===`
34
- `&&n++}}return[t,r]}class Un extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){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:r,onComment:n})},transform(s){o.feed(s)}})}}function It(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function m3({tools:e=[],providerToolNames:t}){const r={},n={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];r[o.name]=s,n[s]=o.name}return{toProviderToolName:o=>{var s;return(s=r[o])!=null?s:o},toCustomToolName:o=>{var s;return(s=n[o])!=null?s:o}}}async function g3(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(Wp());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(Wp())};r?.addEventListener("abort",i)})}function Wp(){return new DOMException("Delay was aborted","AbortError")}var bo=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))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function Dn(e){return Object.fromEntries([...e.headers])}var{btoa:y3,atob:_3}=globalThis;function zn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=_3(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Fn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return y3(t)}function Vn(e){return e instanceof Uint8Array?Fn(e):e}function v3(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){n.append(o,s[0]);continue}const a=r?`${o}[]`:o;for(const i of s)n.append(a,i);continue}n.append(o,s)}return n}var Kp="AI_DownloadError",Yp=`vercel.ai.error.${Kp}`,w3=Symbol.for(Yp),Qp,Xp,Zr=class extends(Xp=he,Qp=w3,Xp){constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:Kp,message:o,cause:n}),this[Qp]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return he.hasMarker(e,Yp)}},Bi=2*1024*1024*1024;async function ef({response:e,url:t,maxBytes:r=Bi}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Zr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let i=0;try{for(;;){const{done:u,value:g}=await s.read();if(u)break;if(i+=g.length,i>r)throw new Zr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(g)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(i);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}async function tf(e,t){var r,n;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new Zr({url:e,statusCode:o.status,statusText:o.statusText});const s=await ef({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:Bi}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw Zr.isInstance(o)?o:new Zr({url:e,cause:o})}}var ko=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new Ku({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Et=ko();function Hi(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function dn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var b3=["fetch failed","failed to fetch"],k3=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function C3(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&k3.includes(t))}function rf({error:e,url:t,requestBodyValues:r}){if(dn(e))return e;if(e instanceof TypeError&&b3.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ut({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return C3(e)?new ut({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Co(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function T3(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function Br(e,...t){const r=new Headers(T3(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var nf="4.0.15",S3=()=>globalThis.fetch,of=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=S3()})=>{try{const a=await s(e,{method:"GET",headers:Br(t,`ai-sdk/provider-utils/${nf}`,Co()),signal:o}),i=Dn(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw dn(c)||ut.isInstance(c)?c:new ut({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(dn(l)||ut.isInstance(l))?l:new ut({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw rf({error:a,url:e,requestBodyValues:{}})}};function I3(e){return e!=null}function x3({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function E3({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new hs({message:`${n} API key must be a string.`});if(typeof process>"u")throw new hs({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new hs({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new hs({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function To({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}function $3(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var R3=/"__proto__"\s*:/,P3=/"constructor"\s*:/;function sf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||R3.test(e)===!1&&P3.test(e)===!1?t:M3(t)}function M3(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Ji(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return sf(e)}try{return sf(e)}finally{Error.stackTraceLimit=t}}function Gi(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=pn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(pn):pn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(pn)),e.allOf!=null&&(e.allOf=e.allOf.map(pn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(pn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=pn(t[r]);return e}function pn(e){return typeof e=="boolean"?e:Gi(e)}var N3=Symbol("Let zodToJsonSchema decide on which parser to use"),af={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},O3=e=>typeof e=="string"?{...af,name:e}:{...af,...e};function Ut(){return{}}function A3(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==te.ZodAny&&(s.items=Be(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function q3(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function L3(){return{type:"boolean"}}function lf(e,t){return Be(e.type._def,t)}var j3=(e,t)=>Be(e.innerType._def,t);function cf(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>cf(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return U3(e)}}var U3=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function D3(e,t){return{...Be(e.innerType._def,t),default:e.defaultValue()}}function z3(e,t){return t.effectStrategy==="input"?Be(e.schema._def,t):Ut()}function F3(e){return{type:"string",enum:Array.from(e.values)}}var V3=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Z3(e,t){const r=[Be(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Be(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(V3(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}n.push(s)}}),n.length?{allOf:n}:void 0}function B3(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Wi=void 0,Qt={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:()=>(Wi===void 0&&(Wi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wi),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 uf(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Xt(r,"email",n.message,t);break;case"format:idn-email":Xt(r,"idn-email",n.message,t);break;case"pattern:zod":$t(r,Qt.email,n.message,t);break}break;case"url":Xt(r,"uri",n.message,t);break;case"uuid":Xt(r,"uuid",n.message,t);break;case"regex":$t(r,n.regex,n.message,t);break;case"cuid":$t(r,Qt.cuid,n.message,t);break;case"cuid2":$t(r,Qt.cuid2,n.message,t);break;case"startsWith":$t(r,RegExp(`^${Ki(n.value,t)}`),n.message,t);break;case"endsWith":$t(r,RegExp(`${Ki(n.value,t)}$`),n.message,t);break;case"datetime":Xt(r,"date-time",n.message,t);break;case"date":Xt(r,"date",n.message,t);break;case"time":Xt(r,"time",n.message,t);break;case"duration":Xt(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{$t(r,RegExp(Ki(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Xt(r,"ipv4",n.message,t),n.version!=="v4"&&Xt(r,"ipv6",n.message,t);break}case"base64url":$t(r,Qt.base64url,n.message,t);break;case"jwt":$t(r,Qt.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&$t(r,Qt.ipv4Cidr,n.message,t),n.version!=="v4"&&$t(r,Qt.ipv6Cidr,n.message,t);break}case"emoji":$t(r,Qt.emoji(),n.message,t);break;case"ulid":{$t(r,Qt.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Xt(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{$t(r,Qt.base64,n.message,t);break}}break}case"nanoid":$t(r,Qt.nanoid,n.message,t)}return r}function Ki(e,t){return t.patternStrategy==="escape"?J3(e):e}var H3=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function J3(e){let t="";for(let r=0;r<e.length;r++)H3.has(e[r])||(t+="\\"),t+=e[r];return t}function Xt(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function $t(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:df(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=df(t,n)}function df(e,t){var r;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")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
34
+ `&&n++}}return[t,r]}class Jn extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=pf({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}function Nt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function O3({tools:e=[],providerToolNames:t}){const r={},n={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];r[o.name]=s,n[s]=o.name}return{toProviderToolName:o=>{var s;return(s=r[o])!=null?s:o},toCustomToolName:o=>{var s;return(s=n[o])!=null?s:o}}}async function A3(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(ff());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(ff())};r?.addEventListener("abort",i)})}function ff(){return new DOMException("Delay was aborted","AbortError")}var Po=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))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function Gn(e){return Object.fromEntries([...e.headers])}var{btoa:q3,atob:L3}=globalThis;function Wn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=L3(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Kn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return q3(t)}function Yn(e){return e instanceof Uint8Array?Kn(e):e}function j3(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){n.append(o,s[0]);continue}const a=r?`${o}[]`:o;for(const i of s)n.append(a,i);continue}n.append(o,s)}return n}var hf="AI_DownloadError",mf=`vercel.ai.error.${hf}`,D3=Symbol.for(mf),gf,yf,tn=class extends(yf=me,gf=D3,yf){constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:hf,message:o,cause:n}),this[gf]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return me.hasMarker(e,mf)}},cl=2*1024*1024*1024;async function _f({response:e,url:t,maxBytes:r=cl}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new tn({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let i=0;try{for(;;){const{done:u,value:m}=await s.read();if(u)break;if(i+=m.length,i>r)throw new tn({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(m)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(i);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}async function vf(e,t){var r,n;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new tn({url:e,statusCode:o.status,statusText:o.statusText});const s=await _f({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:cl}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw tn.isInstance(o)?o:new tn({url:e,cause:o})}}var No=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new fd({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},At=No();function ul(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function bn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var U3=["fetch failed","failed to fetch"],z3=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function F3(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&z3.includes(t))}function wf({error:e,url:t,requestBodyValues:r}){if(bn(e))return e;if(e instanceof TypeError&&U3.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new st({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return F3(e)?new st({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Mo(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function V3(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function rn(e,...t){const r=new Headers(V3(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var bf="4.0.15",Z3=()=>globalThis.fetch,kf=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=Z3()})=>{try{const a=await s(e,{method:"GET",headers:rn(t,`ai-sdk/provider-utils/${bf}`,Mo()),signal:o}),i=Gn(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw bn(c)||st.isInstance(c)?c:new st({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(bn(l)||st.isInstance(l))?l:new st({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw wf({error:a,url:e,requestBodyValues:{}})}};function B3(e){return e!=null}function H3({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function J3({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new xs({message:`${n} API key must be a string.`});if(typeof process>"u")throw new xs({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new xs({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new xs({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Qn({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}function G3(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var W3=/"__proto__"\s*:/,K3=/"constructor"\s*:/;function Cf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||W3.test(e)===!1&&K3.test(e)===!1?t:Y3(t)}function Y3(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function dl(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Cf(e)}try{return Cf(e)}finally{Error.stackTraceLimit=t}}function pl(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=kn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(kn):kn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(kn)),e.allOf!=null&&(e.allOf=e.allOf.map(kn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(kn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=kn(t[r]);return e}function kn(e){return typeof e=="boolean"?e:pl(e)}var Q3=Symbol("Let zodToJsonSchema decide on which parser to use"),Tf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},X3=e=>typeof e=="string"?{...Tf,name:e}:{...Tf,...e};function Bt(){return{}}function e9(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==ne.ZodAny&&(s.items=Ve(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function t9(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function r9(){return{type:"boolean"}}function Sf(e,t){return Ve(e.type._def,t)}var n9=(e,t)=>Ve(e.innerType._def,t);function If(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>If(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return o9(e)}}var o9=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function s9(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function a9(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Bt()}function i9(e){return{type:"string",enum:Array.from(e.values)}}var l9=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function c9(e,t){const r=[Ve(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ve(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(l9(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}n.push(s)}}),n.length?{allOf:n}:void 0}function u9(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var fl=void 0,ar={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:()=>(fl===void 0&&(fl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),fl),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 xf(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":ir(r,"email",n.message,t);break;case"format:idn-email":ir(r,"idn-email",n.message,t);break;case"pattern:zod":qt(r,ar.email,n.message,t);break}break;case"url":ir(r,"uri",n.message,t);break;case"uuid":ir(r,"uuid",n.message,t);break;case"regex":qt(r,n.regex,n.message,t);break;case"cuid":qt(r,ar.cuid,n.message,t);break;case"cuid2":qt(r,ar.cuid2,n.message,t);break;case"startsWith":qt(r,RegExp(`^${hl(n.value,t)}`),n.message,t);break;case"endsWith":qt(r,RegExp(`${hl(n.value,t)}$`),n.message,t);break;case"datetime":ir(r,"date-time",n.message,t);break;case"date":ir(r,"date",n.message,t);break;case"time":ir(r,"time",n.message,t);break;case"duration":ir(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{qt(r,RegExp(hl(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&ir(r,"ipv4",n.message,t),n.version!=="v4"&&ir(r,"ipv6",n.message,t);break}case"base64url":qt(r,ar.base64url,n.message,t);break;case"jwt":qt(r,ar.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&qt(r,ar.ipv4Cidr,n.message,t),n.version!=="v4"&&qt(r,ar.ipv6Cidr,n.message,t);break}case"emoji":qt(r,ar.emoji(),n.message,t);break;case"ulid":{qt(r,ar.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ir(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{qt(r,ar.base64,n.message,t);break}}break}case"nanoid":qt(r,ar.nanoid,n.message,t)}return r}function hl(e,t){return t.patternStrategy==="escape"?p9(e):e}var d9=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function p9(e){let t="";for(let r=0;r<e.length;r++)d9.has(e[r])||(t+="\\"),t+=e[r];return t}function ir(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function qt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Ef(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Ef(t,n)}function Ef(e,t){var r;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")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
35
35
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
36
36
  ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
37
37
  `:`[${o[c]}\r
38
- ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function pf(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===te.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=uf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===te.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===te.ZodBranded&&e.keyType._def.type._def.typeName===te.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=lf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function G3(e,t){if(t.mapStrategy==="record")return pf(e,t);const r=Be(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ut(),n=Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ut();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function W3(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function K3(){return{not:Ut()}}function Y3(){return{type:"null"}}var Yi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Q3(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Yi&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Yi[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.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(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return X3(e,t)}var X3=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Be(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function e9(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Yi[e.innerType._def.typeName],"null"]};const r=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function t9(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function r9(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=o9(i),c=Be(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=n9(e,t);return s!==void 0&&(r.additionalProperties=s),r}function n9(e,t){if(e.catchall._def.typeName!=="ZodNever")return Be(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 o9(e){try{return e.isOptional()}catch{return!0}}var s9=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Be(e.innerType._def,t);const n=Be(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Ut()},n]}:Ut()},a9=(e,t)=>{if(t.pipeStrategy==="input")return Be(e.in._def,t);if(t.pipeStrategy==="output")return Be(e.out._def,t);const r=Be(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Be(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function i9(e,t){return Be(e.type._def,t)}function l9(e,t){const n={type:"array",uniqueItems:!0,items:Be(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function c9(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Be(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Be(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function u9(){return{not:Ut()}}function d9(){return Ut()}var p9=(e,t)=>Be(e.innerType._def,t),f9=(e,t,r)=>{switch(t){case te.ZodString:return uf(e,r);case te.ZodNumber:return t9(e);case te.ZodObject:return r9(e,r);case te.ZodBigInt:return q3(e);case te.ZodBoolean:return L3();case te.ZodDate:return cf(e,r);case te.ZodUndefined:return u9();case te.ZodNull:return Y3();case te.ZodArray:return A3(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return Q3(e,r);case te.ZodIntersection:return Z3(e,r);case te.ZodTuple:return c9(e,r);case te.ZodRecord:return pf(e,r);case te.ZodLiteral:return B3(e);case te.ZodEnum:return F3(e);case te.ZodNativeEnum:return W3(e);case te.ZodNullable:return e9(e,r);case te.ZodOptional:return s9(e,r);case te.ZodMap:return G3(e,r);case te.ZodSet:return l9(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return i9(e,r);case te.ZodNaN:case te.ZodNever:return K3();case te.ZodEffects:return z3(e,r);case te.ZodAny:return Ut();case te.ZodUnknown:return d9();case te.ZodDefault:return D3(e,r);case te.ZodBranded:return lf(e,r);case te.ZodReadonly:return p9(e,r);case te.ZodCatch:return j3(e,r);case te.ZodPipeline:return a9(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(n=>{})()}},h9=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Be(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==N3)return l}if(o&&!r){const l=m9(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=f9(e,e.typeName,t),i=typeof a=="function"?Be(a(),t):a;if(i&&g9(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var m9=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:h9(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ut()):t.$refStrategy==="seen"?Ut():void 0}},g9=(e,t,r)=>(e.description&&(r.description=e.description),r),y9=e=>{const t=O3(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},_9=(e,t)=>{var r;const n=y9(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,g])=>{var p;return{...c,[u]:(p=Be(g._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:Ut()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Be(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:Ut(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Qi=Symbol.for("vercel.ai.schema");function Te(e){let t;return()=>(t==null&&(t=e()),t)}function Zn(e,{validate:t}={}){return{[Qi]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function v9(e){return typeof e=="object"&&e!==null&&Qi in e&&e[Qi]===!0&&"jsonSchema"in e&&"validate"in e}function fn(e){return e==null?Zn({properties:{},additionalProperties:!1}):v9(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?be(e):w9(e):e()}function w9(e){return Zn(()=>Gi(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new an({value:t,cause:r.issues})}}})}function b9(e,t){var r;const n=(r=void 0)!=null?r:!1;return Zn(()=>_9(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function k9(e,t){var r;const n=(r=void 0)!=null?r:!1;return Zn(()=>Gi(Dw(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await dp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function C9(e){return"_zod"in e}function be(e,t){return C9(e)?k9(e):b9(e)}async function Rt({value:e,schema:t,context:r}){const n=await Bt({value:e,schema:t,context:r});if(!n.success)throw an.wrap({value:e,cause:n.error,context:r});return n.value}async function Bt({value:e,schema:t,context:r}){const n=fn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:an.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:an.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function T9({text:e,schema:t}){try{const r=Ji(e);return t==null?r:Rt({value:r,schema:t})}catch(r){throw fs.isInstance(r)||an.isInstance(r)?r:new fs({text:e,cause:r})}}async function Ht({text:e,schema:t}){try{const r=Ji(e);return t==null?{success:!0,value:r,rawValue:r}:await Bt({value:r,schema:t})}catch(r){return{success:!1,error:fs.isInstance(r)?r:new fs({text:e,cause:r}),rawValue:void 0}}}function ff(e){try{return Ji(e),!0}catch{return!1}}function S9({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Un).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Ht({text:r,schema:t}))}}))}async function Cr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Bt({value:t[e],schema:r});if(!n.success)throw new Ku({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var I9=()=>globalThis.fetch,Ot=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>mf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),hf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>mf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),mf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=I9()})=>{try{const i=await a(e,{method:"POST",headers:Br(t,`ai-sdk/provider-utils/${nf}`,Co()),body:r.content,signal:s}),l=Dn(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw dn(u)||ut.isInstance(u)?u:new ut({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(dn(c)||ut.isInstance(c))?c:new ut({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw rf({error:i,url:e,requestBodyValues:r.values})}};function lE(e){return e}function gf(e){return{...e,type:"dynamic"}}function er({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function At(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Hr=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Dn(n);if(a.trim()==="")return{responseHeaders:i,value:new ut({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await T9({text:a,schema:e});return{responseHeaders:i,value:new ut({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new ut({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Ms=e=>async({response:t})=>{const r=Dn(t);if(t.body==null)throw new j_({});return{responseHeaders:r,value:S9({stream:t.body,schema:e})}},Dt=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Ht({text:o,schema:e}),a=Dn(t);if(!s.success)throw new ut({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},x9=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Dn(e);if(!e.body)throw new ut({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new ut({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function yf(e){return e?.replace(/\/$/,"")}function E9(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*$9({execute:e,input:t,options:r}){const n=e(t,r);if(E9(n)){let o;for await(const s of n)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await n}}function Xi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var el,_f;function R9(){if(_f)return el;_f=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,g)=>{for(var p in g)e(u,p,{get:g[p],enumerable:!0})},s=(u,g,p,h)=>{if(g&&typeof g=="object"||typeof g=="function")for(let y of r(g))!n.call(u,y)&&y!==p&&e(u,y,{get:()=>g[y],enumerable:!(h=t(g,y))||h.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),el=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return el}var tl,vf;function P9(){if(vf)return tl;vf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(g,p)=>{for(var h in p)e(g,h,{get:p[h],enumerable:!0})},s=(g,p,h,y)=>{if(p&&typeof p=="object"||typeof p=="function")for(let w of r(p))!n.call(g,w)&&w!==h&&e(g,w,{get:()=>p[w],enumerable:!(y=t(p,w))||y.enumerable});return g},a=g=>s(e({},"__esModule",{value:!0}),g),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),tl=a(i);var l=R9();async function c(){return""}function u(){return""}return tl}var wf=P9(),M9="vercel.ai.gateway.error",rl=Symbol.for(M9),bf,kf,Pt=class P_ extends(kf=Error,bf=rl,kf){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[bf]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return P_.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&rl in t&&t[rl]===!0}},Cf="GatewayAuthenticationError",N9=`vercel.ai.gateway.error.${Cf}`,Tf=Symbol.for(N9),Sf,If,nl=class M_ extends(If=Pt,Sf=Tf,If){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Sf]=!0,this.name=Cf,this.type="authentication_error"}static isInstance(t){return Pt.hasMarker(t)&&Tf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
38
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function $f(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===ne.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=xf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===ne.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===ne.ZodBranded&&e.keyType._def.type._def.typeName===ne.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=Sf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function f9(e,t){if(t.mapStrategy==="record")return $f(e,t);const r=Ve(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Bt(),n=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Bt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function h9(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function m9(){return{not:Bt()}}function g9(){return{type:"null"}}var ml={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function y9(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in ml&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=ml[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.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(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return _9(e,t)}var _9=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ve(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function v9(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[ml[e.innerType._def.typeName],"null"]};const r=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function w9(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function b9(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=C9(i),c=Ve(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=k9(e,t);return s!==void 0&&(r.additionalProperties=s),r}function k9(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ve(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 C9(e){try{return e.isOptional()}catch{return!0}}var T9=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ve(e.innerType._def,t);const n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Bt()},n]}:Bt()},S9=(e,t)=>{if(t.pipeStrategy==="input")return Ve(e.in._def,t);if(t.pipeStrategy==="output")return Ve(e.out._def,t);const r=Ve(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ve(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function I9(e,t){return Ve(e.type._def,t)}function x9(e,t){const n={type:"array",uniqueItems:!0,items:Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function E9(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ve(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function $9(){return{not:Bt()}}function R9(){return Bt()}var P9=(e,t)=>Ve(e.innerType._def,t),N9=(e,t,r)=>{switch(t){case ne.ZodString:return xf(e,r);case ne.ZodNumber:return w9(e);case ne.ZodObject:return b9(e,r);case ne.ZodBigInt:return t9(e);case ne.ZodBoolean:return r9();case ne.ZodDate:return If(e,r);case ne.ZodUndefined:return $9();case ne.ZodNull:return g9();case ne.ZodArray:return e9(e,r);case ne.ZodUnion:case ne.ZodDiscriminatedUnion:return y9(e,r);case ne.ZodIntersection:return c9(e,r);case ne.ZodTuple:return E9(e,r);case ne.ZodRecord:return $f(e,r);case ne.ZodLiteral:return u9(e);case ne.ZodEnum:return i9(e);case ne.ZodNativeEnum:return h9(e);case ne.ZodNullable:return v9(e,r);case ne.ZodOptional:return T9(e,r);case ne.ZodMap:return f9(e,r);case ne.ZodSet:return x9(e,r);case ne.ZodLazy:return()=>e.getter()._def;case ne.ZodPromise:return I9(e,r);case ne.ZodNaN:case ne.ZodNever:return m9();case ne.ZodEffects:return a9(e,r);case ne.ZodAny:return Bt();case ne.ZodUnknown:return R9();case ne.ZodDefault:return s9(e,r);case ne.ZodBranded:return Sf(e,r);case ne.ZodReadonly:return P9(e,r);case ne.ZodCatch:return n9(e,r);case ne.ZodPipeline:return S9(e,r);case ne.ZodFunction:case ne.ZodVoid:case ne.ZodSymbol:return;default:return(n=>{})()}},M9=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Ve(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==Q3)return l}if(o&&!r){const l=O9(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=N9(e,e.typeName,t),i=typeof a=="function"?Ve(a(),t):a;if(i&&A9(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var O9=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:M9(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Bt()):t.$refStrategy==="seen"?Bt():void 0}},A9=(e,t,r)=>(e.description&&(r.description=e.description),r),q9=e=>{const t=X3(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},L9=(e,t)=>{var r;const n=q9(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,m])=>{var p;return{...c,[u]:(p=Ve(m._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:Bt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Ve(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:Bt(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},gl=Symbol.for("vercel.ai.schema");function be(e){let t;return()=>(t==null&&(t=e()),t)}function Xn(e,{validate:t}={}){return{[gl]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function j9(e){return typeof e=="object"&&e!==null&&gl in e&&e[gl]===!0&&"jsonSchema"in e&&"validate"in e}function Cn(e){return e==null?Xn({properties:{},additionalProperties:!1}):j9(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?we(e):D9(e):e()}function D9(e){return Xn(()=>pl(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new yn({value:t,cause:r.issues})}}})}function U9(e,t){var r;const n=(r=void 0)!=null?r:!1;return Xn(()=>L9(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function z9(e,t){var r;const n=(r=void 0)!=null?r:!1;return Xn(()=>pl(sb(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Ep(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function F9(e){return"_zod"in e}function we(e,t){return F9(e)?z9(e):U9(e)}async function St({value:e,schema:t,context:r}){const n=await Yt({value:e,schema:t,context:r});if(!n.success)throw yn.wrap({value:e,cause:n.error,context:r});return n.value}async function Yt({value:e,schema:t,context:r}){const n=Cn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:yn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:yn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function V9({text:e,schema:t}){try{const r=dl(e);return t==null?r:St({value:r,schema:t})}catch(r){throw Is.isInstance(r)||yn.isInstance(r)?r:new Is({text:e,cause:r})}}async function Qt({text:e,schema:t}){try{const r=dl(e);return t==null?{success:!0,value:r,rawValue:r}:await Yt({value:r,schema:t})}catch(r){return{success:!1,error:Is.isInstance(r)?r:new Is({text:e,cause:r}),rawValue:void 0}}}function Rf(e){try{return dl(e),!0}catch{return!1}}function Pf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Qt({text:r,schema:t}))}}))}async function Mr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Yt({value:t[e],schema:r});if(!n.success)throw new fd({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Z9=()=>globalThis.fetch,Ut=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Mf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Nf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Mf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Mf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=Z9()})=>{try{const i=await a(e,{method:"POST",headers:rn(t,`ai-sdk/provider-utils/${bf}`,Mo()),body:r.content,signal:s}),l=Gn(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw bn(u)||st.isInstance(u)?u:new st({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(bn(c)||st.isInstance(c))?c:new st({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw wf({error:i,url:e,requestBodyValues:r.values})}};function $E(e){return e}function Of(e){return{...e,type:"dynamic"}}function lr({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function zt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var nn=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Gn(n);if(a.trim()==="")return{responseHeaders:i,value:new st({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await V9({text:a,schema:e});return{responseHeaders:i,value:new st({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new st({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Bs=e=>async({response:t})=>{const r=Gn(t);if(t.body==null)throw new nv({});return{responseHeaders:r,value:Pf({stream:t.body,schema:e})}},Xt=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Qt({text:o,schema:e}),a=Gn(t);if(!s.success)throw new st({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},B9=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Gn(e);if(!e.body)throw new st({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new st({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function Af(e){return e?.replace(/\/$/,"")}function H9(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*J9({execute:e,input:t,options:r}){const n=e(t,r);if(H9(n)){let o;for await(const s of n)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await n}}function yl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _l,qf;function G9(){if(qf)return _l;qf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,m)=>{for(var p in m)e(u,p,{get:m[p],enumerable:!0})},s=(u,m,p,f)=>{if(m&&typeof m=="object"||typeof m=="function")for(let g of r(m))!n.call(u,g)&&g!==p&&e(u,g,{get:()=>m[g],enumerable:!(f=t(m,g))||f.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),_l=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return _l}var vl,Lf;function W9(){if(Lf)return vl;Lf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(m,p)=>{for(var f in p)e(m,f,{get:p[f],enumerable:!0})},s=(m,p,f,g)=>{if(p&&typeof p=="object"||typeof p=="function")for(let v of r(p))!n.call(m,v)&&v!==f&&e(m,v,{get:()=>p[v],enumerable:!(g=t(p,v))||g.enumerable});return m},a=m=>s(e({},"__esModule",{value:!0}),m),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),vl=a(i);var l=G9();async function c(){return""}function u(){return""}return vl}var jf=W9(),K9="vercel.ai.gateway.error",wl=Symbol.for(K9),Df,Uf,Lt=class K_ extends(Uf=Error,Df=wl,Uf){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[Df]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return K_.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&wl in t&&t[wl]===!0}},zf="GatewayAuthenticationError",Y9=`vercel.ai.gateway.error.${zf}`,Ff=Symbol.for(Y9),Vf,Zf,bl=class Y_ extends(Zf=Lt,Vf=Ff,Zf){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Vf]=!0,this.name=zf,this.type="authentication_error"}static isInstance(t){return Lt.hasMarker(t)&&Ff in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
39
39
 
40
40
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
41
41
 
@@ -50,9 +50,9 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
50
50
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
51
51
 
52
52
  Option 2 - OIDC token:
53
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new M_({message:i,statusCode:o,cause:s,generationId:a})}},xf="GatewayInvalidRequestError",O9=`vercel.ai.gateway.error.${xf}`,Ef=Symbol.for(O9),$f,Rf,A9=class extends(Rf=Pt,$f=Ef,Rf){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[$f]=!0,this.name=xf,this.type="invalid_request_error"}static isInstance(e){return Pt.hasMarker(e)&&Ef in e}},Pf="GatewayRateLimitError",q9=`vercel.ai.gateway.error.${Pf}`,Mf=Symbol.for(q9),Nf,Of,L9=class extends(Of=Pt,Nf=Mf,Of){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Nf]=!0,this.name=Pf,this.type="rate_limit_exceeded"}static isInstance(e){return Pt.hasMarker(e)&&Mf in e}},Af="GatewayModelNotFoundError",j9=`vercel.ai.gateway.error.${Af}`,qf=Symbol.for(j9),U9=Te(()=>be(T({modelId:d()}))),Lf,jf,D9=class extends(jf=Pt,Lf=qf,jf){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[Lf]=!0,this.name=Af,this.type="model_not_found",this.modelId=r}static isInstance(e){return Pt.hasMarker(e)&&qf in e}},Uf="GatewayInternalServerError",z9=`vercel.ai.gateway.error.${Uf}`,Df=Symbol.for(z9),zf,Ff,Vf=class extends(Ff=Pt,zf=Df,Ff){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[zf]=!0,this.name=Uf,this.type="internal_server_error"}static isInstance(e){return Pt.hasMarker(e)&&Df in e}},Zf="GatewayResponseError",F9=`vercel.ai.gateway.error.${Zf}`,Bf=Symbol.for(F9),Hf,Jf,V9=class extends(Jf=Pt,Hf=Bf,Jf){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[Hf]=!0,this.name=Zf,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Pt.hasMarker(e)&&Bf in e}};async function Gf({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await Bt({value:e,schema:Z9});if(!a.success){const g=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new V9({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:g})}const i=a.value,l=i.error.type,c=i.error.message,u=(s=i.generationId)!=null?s:void 0;switch(l){case"authentication_error":return nl.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new A9({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new L9({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const g=await Bt({value:i.error.param,schema:U9});return new D9({message:c,statusCode:t,modelId:g.success?g.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Vf({message:c,statusCode:t,cause:n,generationId:u});default:return new Vf({message:c,statusCode:t,cause:n,generationId:u})}}var Z9=Te(()=>be(T({error:T({message:d(),type:d().nullish(),param:Me().nullish(),code:oe([d(),j()]).nullish()}),generationId:d().nullish()}))),Wf="GatewayTimeoutError",B9=`vercel.ai.gateway.error.${Wf}`,Kf=Symbol.for(B9),Yf,Qf,Xf=class N_ extends(Qf=Pt,Yf=Kf,Qf){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Yf]=!0,this.name=Wf,this.type="timeout_error"}static isInstance(t){return Pt.hasMarker(t)&&Kf in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
53
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Y_({message:i,statusCode:o,cause:s,generationId:a})}},Bf="GatewayInvalidRequestError",Q9=`vercel.ai.gateway.error.${Bf}`,Hf=Symbol.for(Q9),Jf,Gf,X9=class extends(Gf=Lt,Jf=Hf,Gf){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Jf]=!0,this.name=Bf,this.type="invalid_request_error"}static isInstance(e){return Lt.hasMarker(e)&&Hf in e}},Wf="GatewayRateLimitError",e4=`vercel.ai.gateway.error.${Wf}`,Kf=Symbol.for(e4),Yf,Qf,t4=class extends(Qf=Lt,Yf=Kf,Qf){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Yf]=!0,this.name=Wf,this.type="rate_limit_exceeded"}static isInstance(e){return Lt.hasMarker(e)&&Kf in e}},Xf="GatewayModelNotFoundError",r4=`vercel.ai.gateway.error.${Xf}`,eh=Symbol.for(r4),n4=be(()=>we(C({modelId:d()}))),th,rh,o4=class extends(rh=Lt,th=eh,rh){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[th]=!0,this.name=Xf,this.type="model_not_found",this.modelId=r}static isInstance(e){return Lt.hasMarker(e)&&eh in e}},nh="GatewayInternalServerError",s4=`vercel.ai.gateway.error.${nh}`,oh=Symbol.for(s4),sh,ah,ih=class extends(ah=Lt,sh=oh,ah){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[sh]=!0,this.name=nh,this.type="internal_server_error"}static isInstance(e){return Lt.hasMarker(e)&&oh in e}},lh="GatewayResponseError",a4=`vercel.ai.gateway.error.${lh}`,ch=Symbol.for(a4),uh,dh,i4=class extends(dh=Lt,uh=ch,dh){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[uh]=!0,this.name=lh,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Lt.hasMarker(e)&&ch in e}};async function ph({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await Yt({value:e,schema:l4});if(!a.success){const m=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new i4({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:m})}const i=a.value,l=i.error.type,c=i.error.message,u=(s=i.generationId)!=null?s:void 0;switch(l){case"authentication_error":return bl.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new X9({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new t4({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const m=await Yt({value:i.error.param,schema:n4});return new o4({message:c,statusCode:t,modelId:m.success?m.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new ih({message:c,statusCode:t,cause:n,generationId:u});default:return new ih({message:c,statusCode:t,cause:n,generationId:u})}}var l4=be(()=>we(C({error:C({message:d(),type:d().nullish(),param:$e().nullish(),code:oe([d(),j()]).nullish()}),generationId:d().nullish()}))),fh="GatewayTimeoutError",c4=`vercel.ai.gateway.error.${fh}`,hh=Symbol.for(c4),mh,gh,yh=class Q_ extends(gh=Lt,mh=hh,gh){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[mh]=!0,this.name=fh,this.type="timeout_error"}static isInstance(t){return Lt.hasMarker(t)&&hh in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
54
54
 
55
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new N_({message:s,statusCode:r,cause:n,generationId:o})}};function eh(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function Tr(e,t){var r;return Pt.isInstance(e)?e:eh(e)?Xf.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ut.isInstance(e)?e.cause&&eh(e.cause)?Xf.createTimeoutError({originalMessage:e.message,cause:e}):await Gf({response:H9(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Gf({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function H9(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 th="ai-gateway-auth-method";async function hn(e){const t=await Bt({value:e[th],schema:J9});return t.success?t.value:void 0}var J9=Te(()=>be(oe([P("api-key"),P("oidc")]))),rh=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await of({url:`${this.config.baseURL}/config`,headers:await At(this.config.headers()),successfulResponseHandler:Dt(G9),failedResponseHandler:Hr({errorSchema:ft(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Tr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await of({url:`${e.origin}/v1/credits`,headers:await At(this.config.headers()),successfulResponseHandler:Dt(W9),failedResponseHandler:Hr({errorSchema:ft(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Tr(e)}}},G9=Te(()=>be(T({models:q(T({id:d(),name:d(),description:d().nullish(),pricing:T({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:T({specificationVersion:P("v3"),provider:d(),modelId:d()}),modelType:Se(["embedding","image","language","video"]).nullish()}))}))),W9=Te(()=>be(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),K9=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await At(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Ot({url:this.getUrl(),headers:It(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await At(this.config.o11yHeaders)),body:t,successfulResponseHandler:Dt(ft()),failedResponseHandler:Hr({errorSchema:ft(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:r}}catch(s){throw await Tr(s,await hn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await At(this.config.headers());try{const{value:s,responseHeaders:a}=await Ot({url:this.getUrl(),headers:It(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await At(this.config.o11yHeaders)),body:t,successfulResponseHandler:Ms(ft()),failedResponseHandler:Hr({errorSchema:ft(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await Tr(s,await hn(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Y9=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await At(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Ot({url:this.getUrl(),headers:It(s,t??{},this.getModelConfigHeaders(),await At(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Dt(Q9),failedResponseHandler:Hr({errorSchema:ft(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l},warnings:[]}}catch(a){throw await Tr(a,await hn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},Q9=Te(()=>be(T({embeddings:q(q(j())),usage:T({tokens:j()}).nullish(),providerMetadata:me(d(),me(d(),Me())).optional()}))),X9=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:s,mask:a,providerOptions:i,headers:l,abortSignal:c}){var u,g,p,h;const y=await At(this.config.headers());try{const{responseHeaders:w,value:m,rawValue:b}=await Ot({url:this.getUrl(),headers:It(y,l??{},this.getModelConfigHeaders(),await At(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(_=>nh(_))},...a&&{mask:nh(a)}},successfulResponseHandler:Dt(n4),failedResponseHandler:Hr({errorSchema:ft(),errorToMessage:_=>_}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:m.images,warnings:(u=m.warnings)!=null?u:[],providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:w},...m.usage!=null&&{usage:{inputTokens:(g=m.usage.inputTokens)!=null?g:void 0,outputTokens:(p=m.usage.outputTokens)!=null?p:void 0,totalTokens:(h=m.usage.totalTokens)!=null?h:void 0}}}}catch(w){throw await Tr(w,await hn(y))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function nh(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Fn(e.data)}:e}var e4=T({images:q(Me()).optional()}).catchall(Me()),t4=Qe("type",[T({type:P("unsupported"),feature:d(),details:d().optional()}),T({type:P("compatibility"),feature:d(),details:d().optional()}),T({type:P("other"),message:d()})]),r4=T({inputTokens:j().nullish(),outputTokens:j().nullish(),totalTokens:j().nullish()}),n4=T({images:q(d()),warnings:q(t4).optional(),providerMetadata:me(d(),e4).optional(),usage:r4.optional()}),o4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:s,seed:a,image:i,providerOptions:l,headers:c,abortSignal:u}){var g;const p=await At(this.config.headers());try{const{responseHeaders:h,value:y,rawValue:w}=await Ot({url:this.getUrl(),headers:It(p,c??{},this.getModelConfigHeaders(),await At(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...a&&{seed:a},...l&&{providerOptions:l},...i&&{image:s4(i)}},successfulResponseHandler:Dt(c4),failedResponseHandler:Hr({errorSchema:ft(),errorToMessage:m=>m}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:y.videos,warnings:(g=y.warnings)!=null?g:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await Tr(h,await hn(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function s4(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Fn(e.data)}:e}var a4=T({videos:q(Me()).optional()}).catchall(Me()),i4=oe([T({type:P("url"),url:d(),mediaType:d()}),T({type:P("base64"),data:d(),mediaType:d()})]),l4=Qe("type",[T({type:P("unsupported"),feature:d(),details:d().optional()}),T({type:P("compatibility"),feature:d(),details:d().optional()}),T({type:P("other"),message:d()})]),c4=T({videos:q(i4),warnings:q(l4).optional(),providerMetadata:me(d(),a4).optional()}),u4=Te(()=>be(Yt({objective:Ke().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:Vr(Ke()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Ps(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:fr().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:Yt({include_domains:Vr(Ke()).optional().describe("List of domains to include in search results."),exclude_domains:Vr(Ke()).optional().describe("List of domains to exclude from search results."),after_date:Ke().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:Yt({max_chars_per_result:fr().optional().describe("Maximum characters per result."),max_chars_total:fr().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:Yt({max_age_seconds:fr().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),d4=Te(()=>be(Vi([Yt({searchId:Ke(),results:Vr(Yt({url:Ke(),title:Ke(),excerpt:Ke(),publishDate:Ke().nullable().optional(),relevanceScore:fr().optional()}))}),Yt({error:Ps(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:fr().optional(),message:Ke()})]))),p4=er({id:"gateway.parallel_search",inputSchema:u4,outputSchema:d4}),f4=(e={})=>p4(e),h4=Te(()=>be(Yt({query:Vi([Ke(),Vr(Ke())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:fr().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:fr().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:fr().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ke().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Vr(Ke()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Vr(Ke()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ke().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Ke().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Ke().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Ke().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Ps(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),m4=Te(()=>be(Vi([Yt({results:Vr(Yt({title:Ke(),url:Ke(),snippet:Ke(),date:Ke().optional(),lastUpdated:Ke().optional()})),id:Ke()}),Yt({error:Ps(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:fr().optional(),message:Ke()})]))),g4=er({id:"gateway.perplexity_search",inputSchema:h4,outputSchema:m4}),y4=(e={})=>g4(e),_4={parallelSearch:f4,perplexitySearch:y4};async function v4(){var e;return(e=wf.getContext().headers)==null?void 0:e["x-vercel-id"]}var w4="3.0.45",b4="0.0.1";function k4(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(r=yf(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const w=await T4(e);return Br({Authorization:`Bearer ${w.token}`,"ai-gateway-protocol-version":b4,[th]:w.authMethod,...e.headers},`ai-sdk/gateway/${w4}`)}catch(w){throw nl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:w})}},c=()=>{const w=To({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),m=To({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=To({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const _=await v4();return{...w&&{"ai-o11y-deployment-id":w},...m&&{"ai-o11y-environment":m},...b&&{"ai-o11y-region":b},..._&&{"ai-o11y-request-id":_}}}},u=w=>new K9(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),g=async()=>{var w,m,b;const _=(b=(m=(w=e._internal)==null?void 0:w.currentDate)==null?void 0:m.call(w).getTime())!=null?b:Date.now();return(!n||_-a>s)&&(a=_,n=new rh({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(f=>(o=f,f)).catch(async f=>{throw await Tr(f,await hn(await l()))})),o?Promise.resolve(o):n},p=async()=>new rh({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async w=>{throw await Tr(w,await hn(await l()))}),h=function(w){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(w)};h.specificationVersion="v3",h.getAvailableModels=g,h.getCredits=p,h.imageModel=w=>new X9(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h.languageModel=u;const y=w=>new Y9(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return h.embeddingModel=y,h.textEmbeddingModel=y,h.videoModel=w=>new o4(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),h.chat=h.languageModel,h.embedding=h.embeddingModel,h.image=h.imageModel,h.video=h.videoModel,h.tools=_4,h}var C4=k4();async function T4(e){const t=To({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await wf.getVercelOidcToken(),authMethod:"oidc"}}var S4=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},mn="1.9.0",oh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function I4(e){var t=new Set([e]),r=new Set,n=e.match(oh);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return r.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(oh);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):s(l):o.minor<=u.minor?a(l):s(l)}}var x4=I4(mn),E4=mn.split(".")[0],So=Symbol.for("opentelemetry.js.api."+E4),Io=S4;function xo(e,t,r,n){var o;n===void 0&&(n=!1);var s=Io[So]=(o=Io[So])!==null&&o!==void 0?o:{version:mn};if(!n&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}if(s.version!==mn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+mn);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+mn+"."),!0}function gn(e){var t,r,n=(t=Io[So])===null||t===void 0?void 0:t.version;if(!(!n||!x4(n)))return(r=Io[So])===null||r===void 0?void 0:r[e]}function Eo(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+mn+".");var r=Io[So];r&&delete r[e]}var $4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},R4=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},P4=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return $o("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return $o("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return $o("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return $o("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return $o("verbose",this._namespace,t)},e})();function $o(e,t,r){var n=gn("diag");if(n)return r.unshift(t),n[e].apply(n,R4([],$4(r),!1))}var zt;(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"})(zt||(zt={}));function M4(e,t){e<zt.NONE?e=zt.NONE:e>zt.ALL&&(e=zt.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",zt.ERROR),warn:r("warn",zt.WARN),info:r("info",zt.INFO),debug:r("debug",zt.DEBUG),verbose:r("verbose",zt.VERBOSE)}}var N4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},O4=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},A4="diag",hr=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=gn("diag");if(i)return i[o].apply(i,O4([],N4(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:zt.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=gn("diag"),g=M4((i=s.logLevel)!==null&&i!==void 0?i:zt.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),g.warn("Current logger will overwrite one already registered from "+p)}return xo("diag",g,r,!0)};r.setLogger=n,r.disable=function(){Eo(A4,r)},r.createComponentLogger=function(o){return new P4(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),q4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},L4=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},j4=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=q4(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var a=L4(n),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();hr.instance();function U4(e){return e===void 0&&(e={}),new j4(new Map(Object.entries(e)))}function sh(e){return Symbol.for(e)}var D4=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var s=new e(r._currentContext);return s._currentContext.set(n,o),s},r.deleteValue=function(n){var o=new e(r._currentContext);return o._currentContext.delete(n),o}}return e})(),z4=new D4,yn=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),F4=(function(){function e(){}return e.prototype.createGauge=function(t,r){return Q4},e.prototype.createHistogram=function(t,r){return X4},e.prototype.createCounter=function(t,r){return Y4},e.prototype.createUpDownCounter=function(t,r){return e6},e.prototype.createObservableGauge=function(t,r){return r6},e.prototype.createObservableCounter=function(t,r){return t6},e.prototype.createObservableUpDownCounter=function(t,r){return n6},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Ns=(function(){function e(){}return e})(),V4=(function(e){yn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Ns),Z4=(function(e){yn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Ns),B4=(function(e){yn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Ns),H4=(function(e){yn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Ns),ol=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),J4=(function(e){yn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(ol),G4=(function(e){yn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(ol),W4=(function(e){yn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(ol),K4=new F4,Y4=new V4,Q4=new B4,X4=new H4,e6=new Z4,t6=new J4,r6=new G4,n6=new W4,o6={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},s6={set:function(e,t,r){e!=null&&(e[t]=r)}},a6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},i6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},l6=(function(){function e(){}return e.prototype.active=function(){return z4},e.prototype.with=function(t,r,n){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return r.call.apply(r,i6([n],a6(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),c6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},u6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},sl="context",d6=new l6,Os=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return xo(sl,t,hr.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,u6([t,r,n],c6(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return gn(sl)||d6},e.prototype.disable=function(){this._getContextManager().disable(),Eo(sl,hr.instance())},e})(),al;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(al||(al={}));var ah="0000000000000000",ih="00000000000000000000000000000000",p6={traceId:ih,spanId:ah,traceFlags:al.NONE},Ro=(function(){function e(t){t===void 0&&(t=p6),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){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,r){},e})(),il=sh("OpenTelemetry Context Key SPAN");function ll(e){return e.getValue(il)||void 0}function f6(){return ll(Os.getInstance().active())}function cl(e,t){return e.setValue(il,t)}function h6(e){return e.deleteValue(il)}function m6(e,t){return cl(e,new Ro(t))}function lh(e){var t;return(t=ll(e))===null||t===void 0?void 0:t.spanContext()}var g6=/^([0-9a-f]{32})$/i,y6=/^[0-9a-f]{16}$/i;function _6(e){return g6.test(e)&&e!==ih}function v6(e){return y6.test(e)&&e!==ah}function ch(e){return _6(e.traceId)&&v6(e.spanId)}function w6(e){return new Ro(e)}var ul=Os.getInstance(),uh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=ul.active());var o=!!r?.root;if(o)return new Ro;var s=n&&lh(n);return b6(s)&&ch(s)?new Ro(s):new Ro},e.prototype.startActiveSpan=function(t,r,n,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=n):(s=r,a=n,i=o);var l=a??ul.active(),c=this.startSpan(t,s,l),u=cl(l,c);return ul.with(u,i,void 0,c)}},e})();function b6(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var k6=new uh,C6=(function(){function e(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,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):k6},e})(),T6=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new uh},e})(),S6=new T6,dh=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new C6(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:S6},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)},e})(),As;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(As||(As={}));var ph=Os.getInstance();hr.instance();var I6=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return K4},e})(),x6=new I6,dl="metrics",E6=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return xo(dl,t,hr.instance())},e.prototype.getMeterProvider=function(){return gn(dl)||x6},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Eo(dl,hr.instance())},e})();E6.getInstance();var $6=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),pl=sh("OpenTelemetry Baggage Key");function fh(e){return e.getValue(pl)||void 0}function R6(){return fh(Os.getInstance().active())}function P6(e,t){return e.setValue(pl,t)}function M6(e){return e.deleteValue(pl)}var fl="propagation",N6=new $6,O6=(function(){function e(){this.createBaggage=U4,this.getBaggage=fh,this.getActiveBaggage=R6,this.setBaggage=P6,this.deleteBaggage=M6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return xo(fl,t,hr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=s6),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=o6),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Eo(fl,hr.instance())},e.prototype._getGlobalPropagator=function(){return gn(fl)||N6},e})();O6.getInstance();var hl="trace",A6=(function(){function e(){this._proxyTracerProvider=new dh,this.wrapSpanContext=w6,this.isSpanContextValid=ch,this.deleteSpan=h6,this.getSpan=ll,this.getActiveSpan=f6,this.getSpanContext=lh,this.setSpan=cl,this.setSpanContext=m6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=xo(hl,this._proxyTracerProvider,hr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return gn(hl)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Eo(hl,hr.instance()),this._proxyTracerProvider=new dh},e})(),q6=A6.getInstance(),L6=Object.defineProperty,j6=(e,t)=>{for(var r in t)L6(e,r,{get:t[r],enumerable:!0})},hh="AI_InvalidArgumentError",mh=`vercel.ai.error.${hh}`,U6=Symbol.for(mh),gh,mr=class extends he{constructor({parameter:t,value:r,message:n}){super({name:hh,message:`Invalid argument for parameter ${t}: ${n}`}),this[gh]=!0,this.parameter=t,this.value=r}static isInstance(t){return he.hasMarker(t,mh)}};gh=U6;var yh="AI_InvalidToolApprovalError",_h=`vercel.ai.error.${yh}`,D6=Symbol.for(_h),vh,z6=class extends he{constructor({approvalId:e}){super({name:yh,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[vh]=!0,this.approvalId=e}static isInstance(e){return he.hasMarker(e,_h)}};vh=D6;var wh="AI_InvalidToolInputError",bh=`vercel.ai.error.${wh}`,F6=Symbol.for(bh),kh,ml=class extends he{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${on(r)}`}){super({name:wh,message:n,cause:r}),this[kh]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return he.hasMarker(e,bh)}};kh=F6;var Ch="AI_ToolCallNotFoundForApprovalError",Th=`vercel.ai.error.${Ch}`,V6=Symbol.for(Th),Sh,gl=class extends he{constructor({toolCallId:e,approvalId:t}){super({name:Ch,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Sh]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return he.hasMarker(e,Th)}};Sh=V6;var Ih="AI_MissingToolResultsError",xh=`vercel.ai.error.${Ih}`,Z6=Symbol.for(xh),Eh,$h=class extends he{constructor({toolCallIds:e}){super({name:Ih,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Eh]=!0,this.toolCallIds=e}static isInstance(e){return he.hasMarker(e,xh)}};Eh=Z6;var Rh="AI_NoObjectGeneratedError",Ph=`vercel.ai.error.${Rh}`,B6=Symbol.for(Ph),Mh,Jr=class extends he{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Rh,message:e,cause:t}),this[Mh]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return he.hasMarker(e,Ph)}};Mh=B6;var Nh="AI_NoOutputGeneratedError",Oh=`vercel.ai.error.${Nh}`,H6=Symbol.for(Oh),Ah,qh=class extends he{constructor({message:e="No output generated.",cause:t}={}){super({name:Nh,message:e,cause:t}),this[Ah]=!0}static isInstance(e){return he.hasMarker(e,Oh)}};Ah=H6;var Lh="AI_NoSuchToolError",jh=`vercel.ai.error.${Lh}`,J6=Symbol.for(jh),Uh,yl=class extends he{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Lh,message:r}),this[Uh]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return he.hasMarker(e,jh)}};Uh=J6;var Dh="AI_ToolCallRepairError",zh=`vercel.ai.error.${Dh}`,G6=Symbol.for(zh),Fh,W6=class extends he{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${on(e)}`}){super({name:Dh,message:r,cause:e}),this[Fh]=!0,this.originalError=t}static isInstance(e){return he.hasMarker(e,zh)}};Fh=G6;var K6=class extends he{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}},Vh="AI_UIMessageStreamError",Zh=`vercel.ai.error.${Vh}`,Y6=Symbol.for(Zh),Bh,Bn=class extends he{constructor({chunkType:e,chunkId:t,message:r}){super({name:Vh,message:r}),this[Bh]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return he.hasMarker(e,Zh)}};Bh=Y6;var Hh="AI_InvalidMessageRoleError",Jh=`vercel.ai.error.${Hh}`,Q6=Symbol.for(Jh),Gh,X6=class extends he{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Hh,message:t}),this[Gh]=!0,this.role=e}static isInstance(e){return he.hasMarker(e,Jh)}};Gh=Q6;var Wh="AI_RetryError",Kh=`vercel.ai.error.${Wh}`,e5=Symbol.for(Kh),Yh,Qh=class extends he{constructor({message:e,reason:t,errors:r}){super({name:Wh,message:e}),this[Yh]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return he.hasMarker(e,Kh)}};Yh=e5;function t5({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var r5="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Xh=!1,_l=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}Xh||(Xh=!0,console.info(r5));for(const r of e.warnings)console.warn(t5({warning:r,provider:e.provider,model:e.model}))}};function n5({provider:e,modelId:t}){_l({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function o5(e){return e.specificationVersion==="v3"?e:(n5({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:e0(o.finishReason),usage:t0(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:s5(o.stream)}};default:return t[r]}}}))}function s5(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:e0(t.finishReason),usage:t0(t.usage)});break;default:r.enqueue(t);break}}}))}function e0(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function t0(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function qs(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new K6({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return o5(e)}return a5().languageModel(e)}function a5(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:C4}function vl(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function r0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function i5(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var l5=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],c5=e=>{const t=typeof e=="string"?zn(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function u5(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?c5(e):e}function d5({data:e,signatures:t}){const r=u5(e),n=typeof r=="string"?zn(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||n[a]===s))return o.mediaType}var n0="6.0.85",p5=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const s=await fetch(o,{headers:Br({},`ai-sdk/${n0}`,Co()),signal:r});if(!s.ok)throw new Zr({url:o,statusCode:s.status,statusText:s.statusText});return{data:await ef({response:s,url:o,maxBytes:t??Bi}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Zr.isInstance(s)?s:new Zr({url:o,cause:s})}},f5=(e=p5)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function h5(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var o0=oe([d(),Ss(Uint8Array),Ss(ArrayBuffer),Tp(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function s0(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:r}=h5(e.toString());if(t==null||r==null)throw new he({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function m5(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Fn(new Uint8Array(e)):Fn(e)}function Po(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function a0({prompt:e,supportedUrls:t,download:r=f5()}){const n=await y5(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const g=o.get(u.approvalId);g&&s.add(g)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Po(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>g5({message:c,downloadedAssets:n}))],i=[];for(const c of a){if(c.role!=="tool"){i.push(c);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...c.content):i.push(c)}const l=new Set;for(const c of i)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of s)l.delete(u);if(l.size>0)throw new $h({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new $h({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function g5({message:e,downloadedAssets:t}){const r=e.role;switch(r){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(n=>_5(n,t)).filter(n=>n.type!=="text"||n.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(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=s0(n.data);return{type:"file",data:s,filename:n.filename,mediaType:a??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:i0(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:i0(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new X6({role:n})}}}async function y5(e,t,r){const n=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).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&x3({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,a)=>s==null?null:[n[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function _5(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=s0(n);let i=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=d5({data:l,signatures:l5}))!=null?r: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 i0(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}async function Mo({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:on(r)}:o==="json"?{type:"error-json",value:l0(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:l0(r)}}function l0(e){return e===void 0?null:e}function wl({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new mr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new mr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new mr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new mr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new mr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new mr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new mr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new mr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function v5(e){return e!=null&&Object.keys(e).length>0}async function c0({tools:e,toolChoice:t,activeTools:r}){if(!v5(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e),o=[];for(const[s,a]of n){const i=a.type;switch(i){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await fn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=i;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var No=Oi(()=>oe([Ts(),d(),j(),fe(),me(d(),No.optional()),q(No)])),ot=me(d(),me(d(),No.optional())),u0=T({type:P("text"),text:d(),providerOptions:ot.optional()}),w5=T({type:P("image"),image:oe([o0,Ss(URL)]),mediaType:d().optional(),providerOptions:ot.optional()}),d0=T({type:P("file"),data:oe([o0,Ss(URL)]),filename:d().optional(),mediaType:d(),providerOptions:ot.optional()}),b5=T({type:P("reasoning"),text:d(),providerOptions:ot.optional()}),k5=T({type:P("tool-call"),toolCallId:d(),toolName:d(),input:Me(),providerOptions:ot.optional(),providerExecuted:fe().optional()}),C5=Qe("type",[T({type:P("text"),value:d(),providerOptions:ot.optional()}),T({type:P("json"),value:No,providerOptions:ot.optional()}),T({type:P("execution-denied"),reason:d().optional(),providerOptions:ot.optional()}),T({type:P("error-text"),value:d(),providerOptions:ot.optional()}),T({type:P("error-json"),value:No,providerOptions:ot.optional()}),T({type:P("content"),value:q(oe([T({type:P("text"),text:d(),providerOptions:ot.optional()}),T({type:P("media"),data:d(),mediaType:d()}),T({type:P("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:ot.optional()}),T({type:P("file-url"),url:d(),providerOptions:ot.optional()}),T({type:P("file-id"),fileId:oe([d(),me(d(),d())]),providerOptions:ot.optional()}),T({type:P("image-data"),data:d(),mediaType:d(),providerOptions:ot.optional()}),T({type:P("image-url"),url:d(),providerOptions:ot.optional()}),T({type:P("image-file-id"),fileId:oe([d(),me(d(),d())]),providerOptions:ot.optional()}),T({type:P("custom"),providerOptions:ot.optional()})]))})]),p0=T({type:P("tool-result"),toolCallId:d(),toolName:d(),output:C5,providerOptions:ot.optional()}),T5=T({type:P("tool-approval-request"),approvalId:d(),toolCallId:d()}),S5=T({type:P("tool-approval-response"),approvalId:d(),approved:fe(),reason:d().optional()}),I5=T({role:P("system"),content:d(),providerOptions:ot.optional()}),x5=T({role:P("user"),content:oe([d(),q(oe([u0,w5,d0]))]),providerOptions:ot.optional()}),E5=T({role:P("assistant"),content:oe([d(),q(oe([u0,d0,b5,k5,p0,T5]))]),providerOptions:ot.optional()}),$5=T({role:P("tool"),content:q(oe([p0,S5])),providerOptions:ot.optional()}),R5=oe([I5,x5,E5,$5]);async function f0(e){if(e.prompt==null&&e.messages==null)throw new sn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new sn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Po(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new sn({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new sn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new sn({prompt:e,message:"messages must not be empty"});const r=await Bt({value:t,schema:q(R5)});if(!r.success)throw new sn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function h0(e){if(!nl.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new he({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
55
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new Q_({message:s,statusCode:r,cause:n,generationId:o})}};function _h(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function Or(e,t){var r;return Lt.isInstance(e)?e:_h(e)?yh.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):st.isInstance(e)?e.cause&&_h(e.cause)?yh.createTimeoutError({originalMessage:e.message,cause:e}):await ph({response:u4(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await ph({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function u4(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 vh="ai-gateway-auth-method";async function Tn(e){const t=await Yt({value:e[vh],schema:d4});return t.success?t.value:void 0}var d4=be(()=>we(oe([R("api-key"),R("oidc")]))),wh=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await kf({url:`${this.config.baseURL}/config`,headers:await zt(this.config.headers()),successfulResponseHandler:Xt(p4),failedResponseHandler:nn({errorSchema:wt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Or(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await kf({url:`${e.origin}/v1/credits`,headers:await zt(this.config.headers()),successfulResponseHandler:Xt(f4),failedResponseHandler:nn({errorSchema:wt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Or(e)}}},p4=be(()=>we(C({models:q(C({id:d(),name:d(),description:d().nullish(),pricing:C({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:R("v3"),provider:d(),modelId:d()}),modelType:fe(["embedding","image","language","video"]).nullish()}))}))),f4=be(()=>we(C({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),h4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await zt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Ut({url:this.getUrl(),headers:Nt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await zt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Xt(wt()),failedResponseHandler:nn({errorSchema:wt(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:r}}catch(s){throw await Or(s,await Tn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await zt(this.config.headers());try{const{value:s,responseHeaders:a}=await Ut({url:this.getUrl(),headers:Nt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await zt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Bs(wt()),failedResponseHandler:nn({errorSchema:wt(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await Or(s,await Tn(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},m4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await zt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Ut({url:this.getUrl(),headers:Nt(s,t??{},this.getModelConfigHeaders(),await zt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Xt(g4),failedResponseHandler:nn({errorSchema:wt(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l},warnings:[]}}catch(a){throw await Or(a,await Tn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},g4=be(()=>we(C({embeddings:q(q(j())),usage:C({tokens:j()}).nullish(),providerMetadata:ge(d(),ge(d(),$e())).optional()}))),y4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:s,mask:a,providerOptions:i,headers:l,abortSignal:c}){var u,m,p,f;const g=await zt(this.config.headers());try{const{responseHeaders:v,value:y,rawValue:w}=await Ut({url:this.getUrl(),headers:Nt(g,l??{},this.getModelConfigHeaders(),await zt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(_=>bh(_))},...a&&{mask:bh(a)}},successfulResponseHandler:Xt(b4),failedResponseHandler:nn({errorSchema:wt(),errorToMessage:_=>_}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:y.images,warnings:(u=y.warnings)!=null?u:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:v},...y.usage!=null&&{usage:{inputTokens:(m=y.usage.inputTokens)!=null?m:void 0,outputTokens:(p=y.usage.outputTokens)!=null?p:void 0,totalTokens:(f=y.usage.totalTokens)!=null?f:void 0}}}}catch(v){throw await Or(v,await Tn(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function bh(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Kn(e.data)}:e}var _4=C({images:q($e()).optional()}).catchall($e()),v4=De("type",[C({type:R("unsupported"),feature:d(),details:d().optional()}),C({type:R("compatibility"),feature:d(),details:d().optional()}),C({type:R("other"),message:d()})]),w4=C({inputTokens:j().nullish(),outputTokens:j().nullish(),totalTokens:j().nullish()}),b4=C({images:q(d()),warnings:q(v4).optional(),providerMetadata:ge(d(),_4).optional(),usage:w4.optional()}),k4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:s,seed:a,image:i,providerOptions:l,headers:c,abortSignal:u}){var m;const p=await zt(this.config.headers());try{const{responseHeaders:f,value:g}=await Ut({url:this.getUrl(),headers:Nt(p,c??{},this.getModelConfigHeaders(),await zt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...a&&{seed:a},...l&&{providerOptions:l},...i&&{image:C4(i)}},successfulResponseHandler:async({response:v,url:y,requestBodyValues:w})=>{if(v.body==null)throw new st({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:v.status});const h=Pf({stream:v.body,schema:x4}).getReader(),{done:T,value:k}=await h.read();if(h.releaseLock(),T||!k)throw new st({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:v.status});if(!k.success)throw new st({message:"Failed to parse video SSE event",cause:k.error,url:y,requestBodyValues:w,statusCode:v.status});const b=k.value;if(b.type==="error")throw new st({message:b.message,statusCode:b.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([...v.headers]),responseBody:JSON.stringify(b),data:{error:{message:b.message,type:b.errorType,param:b.param}}});return{value:{videos:b.videos,warnings:b.warnings,providerMetadata:b.providerMetadata},responseHeaders:Object.fromEntries([...v.headers])}},failedResponseHandler:nn({errorSchema:wt(),errorToMessage:v=>v}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:g.videos,warnings:(m=g.warnings)!=null?m:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f}}}catch(f){throw await Or(f,await Tn(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function C4(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Kn(e.data)}:e}var T4=C({videos:q($e()).optional()}).catchall($e()),S4=oe([C({type:R("url"),url:d(),mediaType:d()}),C({type:R("base64"),data:d(),mediaType:d()})]),I4=De("type",[C({type:R("unsupported"),feature:d(),details:d().optional()}),C({type:R("compatibility"),feature:d(),details:d().optional()}),C({type:R("other"),message:d()})]),x4=De("type",[C({type:R("result"),videos:q(S4),warnings:q(I4).optional(),providerMetadata:ge(d(),T4).optional()}),C({type:R("error"),message:d(),errorType:d(),statusCode:j(),param:$e().nullable()})]),E4=be(()=>we(sr({objective:We().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:en(We()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Zs(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:Cr().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:sr({include_domains:en(We()).optional().describe("List of domains to include in search results."),exclude_domains:en(We()).optional().describe("List of domains to exclude from search results."),after_date:We().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:sr({max_chars_per_result:Cr().optional().describe("Maximum characters per result."),max_chars_total:Cr().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:sr({max_age_seconds:Cr().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),$4=be(()=>we(il([sr({searchId:We(),results:en(sr({url:We(),title:We(),excerpt:We(),publishDate:We().nullable().optional(),relevanceScore:Cr().optional()}))}),sr({error:Zs(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Cr().optional(),message:We()})]))),R4=lr({id:"gateway.parallel_search",inputSchema:E4,outputSchema:$4}),P4=(e={})=>R4(e),N4=be(()=>we(sr({query:il([We(),en(We())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Cr().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Cr().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Cr().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:We().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:en(We()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:en(We()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:We().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:We().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:We().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:We().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Zs(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),M4=be(()=>we(il([sr({results:en(sr({title:We(),url:We(),snippet:We(),date:We().optional(),lastUpdated:We().optional()})),id:We()}),sr({error:Zs(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Cr().optional(),message:We()})]))),O4=lr({id:"gateway.perplexity_search",inputSchema:N4,outputSchema:M4}),A4=(e={})=>O4(e),q4={parallelSearch:P4,perplexitySearch:A4};async function L4(){var e;return(e=jf.getContext().headers)==null?void 0:e["x-vercel-id"]}var j4="3.0.58",D4="0.0.1";function U4(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(r=Af(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const v=await F4(e);return rn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":D4,[vh]:v.authMethod,...e.headers},`ai-sdk/gateway/${j4}`)}catch(v){throw bl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},c=()=>{const v=Qn({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Qn({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=Qn({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),_=Qn({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const h=await L4();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...w&&{"ai-o11y-region":w},...h&&{"ai-o11y-request-id":h},..._&&{"ai-o11y-project-id":_}}}},u=v=>new h4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),m=async()=>{var v,y,w;const _=(w=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?w:Date.now();return(!n||_-a>s)&&(a=_,n=new wh({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(h=>(o=h,h)).catch(async h=>{throw await Or(h,await Tn(await l()))})),o?Promise.resolve(o):n},p=async()=>new wh({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await Or(v,await Tn(await l()))}),f=function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(v)};f.specificationVersion="v3",f.getAvailableModels=m,f.getCredits=p,f.imageModel=v=>new y4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const g=v=>new m4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=g,f.textEmbeddingModel=g,f.videoModel=v=>new k4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.chat=f.languageModel,f.embedding=f.embeddingModel,f.image=f.imageModel,f.video=f.videoModel,f.tools=q4,f}var z4=U4();async function F4(e){const t=Qn({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await jf.getVercelOidcToken(),authMethod:"oidc"}}var V4=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Sn="1.9.0",kh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Z4(e){var t=new Set([e]),r=new Set,n=e.match(kh);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return r.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(kh);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):s(l):o.minor<=u.minor?a(l):s(l)}}var B4=Z4(Sn),H4=Sn.split(".")[0],Oo=Symbol.for("opentelemetry.js.api."+H4),Ao=V4;function qo(e,t,r,n){var o;n===void 0&&(n=!1);var s=Ao[Oo]=(o=Ao[Oo])!==null&&o!==void 0?o:{version:Sn};if(!n&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}if(s.version!==Sn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Sn);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Sn+"."),!0}function In(e){var t,r,n=(t=Ao[Oo])===null||t===void 0?void 0:t.version;if(!(!n||!B4(n)))return(r=Ao[Oo])===null||r===void 0?void 0:r[e]}function Lo(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Sn+".");var r=Ao[Oo];r&&delete r[e]}var J4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},G4=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},W4=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return jo("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return jo("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return jo("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return jo("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return jo("verbose",this._namespace,t)},e})();function jo(e,t,r){var n=In("diag");if(n)return r.unshift(t),n[e].apply(n,G4([],J4(r),!1))}var Ht;(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"})(Ht||(Ht={}));function K4(e,t){e<Ht.NONE?e=Ht.NONE:e>Ht.ALL&&(e=Ht.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",Ht.ERROR),warn:r("warn",Ht.WARN),info:r("info",Ht.INFO),debug:r("debug",Ht.DEBUG),verbose:r("verbose",Ht.VERBOSE)}}var Y4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},Q4=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},X4="diag",Tr=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=In("diag");if(i)return i[o].apply(i,Q4([],Y4(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:Ht.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=In("diag"),m=K4((i=s.logLevel)!==null&&i!==void 0?i:Ht.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),m.warn("Current logger will overwrite one already registered from "+p)}return qo("diag",m,r,!0)};r.setLogger=n,r.disable=function(){Lo(X4,r)},r.createComponentLogger=function(o){return new W4(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),e6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},t6=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},r6=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=e6(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var a=t6(n),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();Tr.instance();function n6(e){return e===void 0&&(e={}),new r6(new Map(Object.entries(e)))}function Ch(e){return Symbol.for(e)}var o6=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var s=new e(r._currentContext);return s._currentContext.set(n,o),s},r.deleteValue=function(n){var o=new e(r._currentContext);return o._currentContext.delete(n),o}}return e})(),s6=new o6,xn=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),a6=(function(){function e(){}return e.prototype.createGauge=function(t,r){return g6},e.prototype.createHistogram=function(t,r){return y6},e.prototype.createCounter=function(t,r){return m6},e.prototype.createUpDownCounter=function(t,r){return _6},e.prototype.createObservableGauge=function(t,r){return w6},e.prototype.createObservableCounter=function(t,r){return v6},e.prototype.createObservableUpDownCounter=function(t,r){return b6},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Hs=(function(){function e(){}return e})(),i6=(function(e){xn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Hs),l6=(function(e){xn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Hs),c6=(function(e){xn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Hs),u6=(function(e){xn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Hs),kl=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),d6=(function(e){xn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(kl),p6=(function(e){xn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(kl),f6=(function(e){xn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(kl),h6=new a6,m6=new i6,g6=new c6,y6=new u6,_6=new l6,v6=new d6,w6=new p6,b6=new f6,k6={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},C6={set:function(e,t,r){e!=null&&(e[t]=r)}},T6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},S6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},I6=(function(){function e(){}return e.prototype.active=function(){return s6},e.prototype.with=function(t,r,n){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return r.call.apply(r,S6([n],T6(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),x6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},E6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},Cl="context",$6=new I6,Js=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return qo(Cl,t,Tr.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,E6([t,r,n],x6(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return In(Cl)||$6},e.prototype.disable=function(){this._getContextManager().disable(),Lo(Cl,Tr.instance())},e})(),Tl;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Tl||(Tl={}));var Th="0000000000000000",Sh="00000000000000000000000000000000",R6={traceId:Sh,spanId:Th,traceFlags:Tl.NONE},Do=(function(){function e(t){t===void 0&&(t=R6),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){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,r){},e})(),Sl=Ch("OpenTelemetry Context Key SPAN");function Il(e){return e.getValue(Sl)||void 0}function P6(){return Il(Js.getInstance().active())}function xl(e,t){return e.setValue(Sl,t)}function N6(e){return e.deleteValue(Sl)}function M6(e,t){return xl(e,new Do(t))}function Ih(e){var t;return(t=Il(e))===null||t===void 0?void 0:t.spanContext()}var O6=/^([0-9a-f]{32})$/i,A6=/^[0-9a-f]{16}$/i;function q6(e){return O6.test(e)&&e!==Sh}function L6(e){return A6.test(e)&&e!==Th}function xh(e){return q6(e.traceId)&&L6(e.spanId)}function j6(e){return new Do(e)}var El=Js.getInstance(),Eh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=El.active());var o=!!r?.root;if(o)return new Do;var s=n&&Ih(n);return D6(s)&&xh(s)?new Do(s):new Do},e.prototype.startActiveSpan=function(t,r,n,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=n):(s=r,a=n,i=o);var l=a??El.active(),c=this.startSpan(t,s,l),u=xl(l,c);return El.with(u,i,void 0,c)}},e})();function D6(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var U6=new Eh,z6=(function(){function e(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,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):U6},e})(),F6=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Eh},e})(),V6=new F6,$h=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new z6(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:V6},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)},e})(),Gs;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Gs||(Gs={}));var Rh=Js.getInstance();Tr.instance();var Z6=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return h6},e})(),B6=new Z6,$l="metrics",H6=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return qo($l,t,Tr.instance())},e.prototype.getMeterProvider=function(){return In($l)||B6},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Lo($l,Tr.instance())},e})();H6.getInstance();var J6=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Rl=Ch("OpenTelemetry Baggage Key");function Ph(e){return e.getValue(Rl)||void 0}function G6(){return Ph(Js.getInstance().active())}function W6(e,t){return e.setValue(Rl,t)}function K6(e){return e.deleteValue(Rl)}var Pl="propagation",Y6=new J6,Q6=(function(){function e(){this.createBaggage=n6,this.getBaggage=Ph,this.getActiveBaggage=G6,this.setBaggage=W6,this.deleteBaggage=K6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return qo(Pl,t,Tr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=C6),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=k6),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Lo(Pl,Tr.instance())},e.prototype._getGlobalPropagator=function(){return In(Pl)||Y6},e})();Q6.getInstance();var Nl="trace",X6=(function(){function e(){this._proxyTracerProvider=new $h,this.wrapSpanContext=j6,this.isSpanContextValid=xh,this.deleteSpan=N6,this.getSpan=Il,this.getActiveSpan=P6,this.getSpanContext=Ih,this.setSpan=xl,this.setSpanContext=M6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=qo(Nl,this._proxyTracerProvider,Tr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return In(Nl)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Lo(Nl,Tr.instance()),this._proxyTracerProvider=new $h},e})(),ek=X6.getInstance(),tk=Object.defineProperty,rk=(e,t)=>{for(var r in t)tk(e,r,{get:t[r],enumerable:!0})},Nh="AI_InvalidArgumentError",Mh=`vercel.ai.error.${Nh}`,nk=Symbol.for(Mh),Oh,Sr=class extends me{constructor({parameter:t,value:r,message:n}){super({name:Nh,message:`Invalid argument for parameter ${t}: ${n}`}),this[Oh]=!0,this.parameter=t,this.value=r}static isInstance(t){return me.hasMarker(t,Mh)}};Oh=nk;var Ah="AI_InvalidToolApprovalError",qh=`vercel.ai.error.${Ah}`,ok=Symbol.for(qh),Lh,sk=class extends me{constructor({approvalId:e}){super({name:Ah,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[Lh]=!0,this.approvalId=e}static isInstance(e){return me.hasMarker(e,qh)}};Lh=ok;var jh="AI_InvalidToolInputError",Dh=`vercel.ai.error.${jh}`,ak=Symbol.for(Dh),Uh,Ml=class extends me{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${mn(r)}`}){super({name:jh,message:n,cause:r}),this[Uh]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return me.hasMarker(e,Dh)}};Uh=ak;var zh="AI_ToolCallNotFoundForApprovalError",Fh=`vercel.ai.error.${zh}`,ik=Symbol.for(Fh),Vh,Ol=class extends me{constructor({toolCallId:e,approvalId:t}){super({name:zh,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Vh]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return me.hasMarker(e,Fh)}};Vh=ik;var Zh="AI_MissingToolResultsError",Bh=`vercel.ai.error.${Zh}`,lk=Symbol.for(Bh),Hh,Jh=class extends me{constructor({toolCallIds:e}){super({name:Zh,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Hh]=!0,this.toolCallIds=e}static isInstance(e){return me.hasMarker(e,Bh)}};Hh=lk;var Gh="AI_NoObjectGeneratedError",Wh=`vercel.ai.error.${Gh}`,ck=Symbol.for(Wh),Kh,on=class extends me{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Gh,message:e,cause:t}),this[Kh]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return me.hasMarker(e,Wh)}};Kh=ck;var Yh="AI_NoOutputGeneratedError",Qh=`vercel.ai.error.${Yh}`,uk=Symbol.for(Qh),Xh,e0=class extends me{constructor({message:e="No output generated.",cause:t}={}){super({name:Yh,message:e,cause:t}),this[Xh]=!0}static isInstance(e){return me.hasMarker(e,Qh)}};Xh=uk;var t0="AI_NoSuchToolError",r0=`vercel.ai.error.${t0}`,dk=Symbol.for(r0),n0,Al=class extends me{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:t0,message:r}),this[n0]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return me.hasMarker(e,r0)}};n0=dk;var o0="AI_ToolCallRepairError",s0=`vercel.ai.error.${o0}`,pk=Symbol.for(s0),a0,fk=class extends me{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${mn(e)}`}){super({name:o0,message:r,cause:e}),this[a0]=!0,this.originalError=t}static isInstance(e){return me.hasMarker(e,s0)}};a0=pk;var hk=class extends me{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}},i0="AI_UIMessageStreamError",l0=`vercel.ai.error.${i0}`,mk=Symbol.for(l0),c0,eo=class extends me{constructor({chunkType:e,chunkId:t,message:r}){super({name:i0,message:r}),this[c0]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return me.hasMarker(e,l0)}};c0=mk;var u0="AI_InvalidMessageRoleError",d0=`vercel.ai.error.${u0}`,gk=Symbol.for(d0),p0,yk=class extends me{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:u0,message:t}),this[p0]=!0,this.role=e}static isInstance(e){return me.hasMarker(e,d0)}};p0=gk;var f0="AI_RetryError",h0=`vercel.ai.error.${f0}`,_k=Symbol.for(h0),m0,g0=class extends me{constructor({message:e,reason:t,errors:r}){super({name:f0,message:e}),this[m0]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return me.hasMarker(e,h0)}};m0=_k;function to(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function cr(e){for(const t of to(e.callbacks))try{await t(e.event)}catch{}}function vk({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var wk="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",y0=!1,ql=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}y0||(y0=!0,console.info(wk));for(const r of e.warnings)console.warn(vk({warning:r,provider:e.provider,model:e.model}))}};function bk({provider:e,modelId:t}){ql({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function kk(e){return e.specificationVersion==="v3"?e:(bk({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:_0(o.finishReason),usage:v0(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:Ck(o.stream)}};default:return t[r]}}}))}function Ck(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:_0(t.finishReason),usage:v0(t.usage)});break;default:r.enqueue(t);break}}}))}function _0(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function v0(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function Ws(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new hk({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return kk(e)}return Tk().languageModel(e)}function Tk(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:z4}function Ll(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function w0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function Sk(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var Ik=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],xk=e=>{const t=typeof e=="string"?Wn(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function Ek(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?xk(e):e}function $k({data:e,signatures:t}){const r=Ek(e),n=typeof r=="string"?Wn(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||n[a]===s))return o.mediaType}var b0="6.0.104",Rk=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const s=await fetch(o,{headers:rn({},`ai-sdk/${b0}`,Mo()),signal:r});if(!s.ok)throw new tn({url:o,statusCode:s.status,statusText:s.statusText});return{data:await _f({response:s,url:o,maxBytes:t??cl}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw tn.isInstance(s)?s:new tn({url:o,cause:s})}},Pk=(e=Rk)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function Nk(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var k0=oe([d(),js(Uint8Array),js(ArrayBuffer),zp(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function C0(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:r}=Nk(e.toString());if(t==null||r==null)throw new me({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function Mk(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Kn(new Uint8Array(e)):Kn(e)}async function T0({prompt:e,supportedUrls:t,download:r=Pk()}){const n=await Ak(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const m=o.get(u.approvalId);m&&s.add(m)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:to(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>Ok({message:c,downloadedAssets:n}))],i=[];for(const c of a){if(c.role!=="tool"){i.push(c);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...c.content):i.push(c)}const l=new Set;for(const c of i)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of s)l.delete(u);if(l.size>0)throw new Jh({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Jh({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function Ok({message:e,downloadedAssets:t}){const r=e.role;switch(r){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(n=>qk(n,t)).filter(n=>n.type!=="text"||n.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(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=C0(n.data);return{type:"file",data:s,filename:n.filename,mediaType:a??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:S0(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:S0(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new yk({role:n})}}}async function Ak(e,t,r){const n=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).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&H3({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,a)=>s==null?null:[n[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function qk(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=C0(n);let i=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=$k({data:l,signatures:Ik}))!=null?r: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 S0(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}async function Uo({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:mn(r)}:o==="json"?{type:"error-json",value:I0(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:I0(r)}}function I0(e){return e===void 0?null:e}function jl({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new Sr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Sr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Sr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Sr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Sr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Sr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Sr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Sr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function Lk(e){return e!=null&&Object.keys(e).length>0}async function x0({tools:e,toolChoice:t,activeTools:r}){if(!Lk(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e),o=[];for(const[s,a]of n){const i=a.type;switch(i){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await Cn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=i;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var zo=Qi(()=>oe([Ls(),d(),j(),pe(),ge(d(),zo.optional()),q(zo)])),lt=ge(d(),ge(d(),zo.optional())),E0=C({type:R("text"),text:d(),providerOptions:lt.optional()}),jk=C({type:R("image"),image:oe([k0,js(URL)]),mediaType:d().optional(),providerOptions:lt.optional()}),$0=C({type:R("file"),data:oe([k0,js(URL)]),filename:d().optional(),mediaType:d(),providerOptions:lt.optional()}),Dk=C({type:R("reasoning"),text:d(),providerOptions:lt.optional()}),Uk=C({type:R("tool-call"),toolCallId:d(),toolName:d(),input:$e(),providerOptions:lt.optional(),providerExecuted:pe().optional()}),zk=De("type",[C({type:R("text"),value:d(),providerOptions:lt.optional()}),C({type:R("json"),value:zo,providerOptions:lt.optional()}),C({type:R("execution-denied"),reason:d().optional(),providerOptions:lt.optional()}),C({type:R("error-text"),value:d(),providerOptions:lt.optional()}),C({type:R("error-json"),value:zo,providerOptions:lt.optional()}),C({type:R("content"),value:q(oe([C({type:R("text"),text:d(),providerOptions:lt.optional()}),C({type:R("media"),data:d(),mediaType:d()}),C({type:R("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:lt.optional()}),C({type:R("file-url"),url:d(),providerOptions:lt.optional()}),C({type:R("file-id"),fileId:oe([d(),ge(d(),d())]),providerOptions:lt.optional()}),C({type:R("image-data"),data:d(),mediaType:d(),providerOptions:lt.optional()}),C({type:R("image-url"),url:d(),providerOptions:lt.optional()}),C({type:R("image-file-id"),fileId:oe([d(),ge(d(),d())]),providerOptions:lt.optional()}),C({type:R("custom"),providerOptions:lt.optional()})]))})]),R0=C({type:R("tool-result"),toolCallId:d(),toolName:d(),output:zk,providerOptions:lt.optional()}),Fk=C({type:R("tool-approval-request"),approvalId:d(),toolCallId:d()}),Vk=C({type:R("tool-approval-response"),approvalId:d(),approved:pe(),reason:d().optional()}),Zk=C({role:R("system"),content:d(),providerOptions:lt.optional()}),Bk=C({role:R("user"),content:oe([d(),q(oe([E0,jk,$0]))]),providerOptions:lt.optional()}),Hk=C({role:R("assistant"),content:oe([d(),q(oe([E0,$0,Dk,Uk,R0,Fk]))]),providerOptions:lt.optional()}),Jk=C({role:R("tool"),content:q(oe([R0,Vk])),providerOptions:lt.optional()}),Gk=oe([Zk,Bk,Hk,Jk]);async function P0(e){if(e.prompt==null&&e.messages==null)throw new gn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new gn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!to(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new gn({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new gn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new gn({prompt:e,message:"messages must not be empty"});const r=await Yt({value:t,schema:q(Gk)});if(!r.success)throw new gn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function N0(e){if(!bl.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new me({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
56
56
 
57
57
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
58
58
 
@@ -60,32 +60,32 @@ Alternatively, you can use a provider module instead of the AI Gateway.
60
60
 
61
61
  Learn more: \x1B[34m${r}\x1B[0m
62
62
 
63
- `),{name:"GatewayAuthenticationError"})}function Oo({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function m0({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>{if(a==="timeout"){const l=vl(i);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=i;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(n??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var P5={startSpan(){return Ls},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Ls);if(typeof r=="function")return r(Ls);if(typeof n=="function")return n(Ls)}},Ls={spanContext(){return M5},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}},M5={traceId:"",spanId:"",traceFlags:0};function g0({isEnabled:e=!1,tracer:t}={}){return e?t||q6.getTracer("ai"):P5}async function Ao({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=ph.active();try{const i=await ph.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{y0(s,i)}finally{s.end()}throw i}})}function y0(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:As.ERROR,message:t.message})):e.setStatus({code:As.ERROR})}async function gr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function _0(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?m5(r.data):r.data}:r)})))}function v0(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:tr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function bl(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function w0(e,t){var r,n,o,s,a,i,l,c,u,g;return{inputTokens:tr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:tr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:tr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:tr((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:tr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:tr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:tr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(g=t.outputTokenDetails)==null?void 0:g.reasoningTokens)},totalTokens:tr(e.totalTokens,t.totalTokens),reasoningTokens:tr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:tr(e.cachedInputTokens,t.cachedInputTokens)}}function tr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function js(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]: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?r[n]=js(s,o):r[n]=o}return r}function N5({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(n=a)}const s=r["retry-after"];if(s&&n===void 0){const a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var O5=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>b0(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function b0(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(dn(a)||t===0)throw a;const i=Hi(a),l=[...s,a],c=l.length;if(c>t)throw new Qh({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&ut.isInstance(a)&&a.isRetryable===!0&&c<=t)return await g3(N5({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),b0(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new Qh({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function k0({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new mr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new mr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:O5({maxRetries:r,abortSignal:t})}}function C0({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],i=t.content.filter(l=>l.type==="tool-approval-response");for(const l of i){const c=n[l.approvalId];if(c==null)throw new z6({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new gl({toolCallId:c.toolCallId,approvalId:c.approvalId});const g={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(g):a.push(g)}return{approvedToolApprovals:s,deniedToolApprovals:a}}async function kl({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,onPreliminaryToolResult:i}){const{toolName:l,toolCallId:c,input:u}=e,g=t?.[l];if(g?.execute!=null)return Ao({name:"ai.toolCall",attributes:gr({telemetry:n,attributes:{...Oo({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":l,"ai.toolCall.id":c,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async p=>{let h;try{const y=$9({execute:g.execute.bind(g),input:u,options:{toolCallId:c,messages:o,abortSignal:s,experimental_context:a}});for await(const w of y)w.type==="preliminary"?i?.({...e,type:"tool-result",output:w.output,preliminary:!0}):h=w.output}catch(y){return y0(p,y),{type:"tool-error",toolCallId:c,toolName:l,input:u,error:y,dynamic:g.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}try{p.setAttributes(await gr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(h)}}}))}catch{}return{type:"tool-result",toolCallId:c,toolName:l,input:u,output:h,dynamic:g.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function T0(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
64
- `)}function S0(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var I0=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Fn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=zn(this.base64Data)),this.uint8ArrayData}},A5=class extends I0{constructor(e){super(e),this.type="file"}};async function x0({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var q5={};j6(q5,{array:()=>U5,choice:()=>D5,json:()=>z5,object:()=>j5,text:()=>Us});function L5(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),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":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,l+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=e.slice(0,r+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 u=e.substring(n,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function qo(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ht({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ht({text:L5(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Us=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),j5=({schema:e,name:t,description:r})=>{const n=fn(e);return{name:"object",responseFormat:At(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await Ht({text:o});if(!a.success)throw new Jr({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=await Bt({value:a.value,schema:n});if(!i.success)throw new Jr({message:"No object generated: response did not match schema.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return i.value},async parsePartialOutput({text:o}){const s=await qo(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},U5=({element:e,name:t,description:r})=>{const n=fn(e);return{name:"array",responseFormat:At(n.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const a=await Ht({text:o});if(!a.success)throw new Jr({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))throw new Jr({message:"No object generated: response did not match schema.",cause:new an({value:i,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of i.elements){const c=await Bt({value:l,schema:n});if(!c.success)throw new Jr({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return i.elements},async parsePartialOutput({text:o}){const s=await qo(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const i=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of i){const u=await Bt({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},D5=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const s=await Ht({text:n});if(!s.success)throw new Jr({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new Jr({message:"No object generated: response did not match schema.",cause:new an({value:a,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:n}){const o=await qo(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(i=>i.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),z5=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await Ht({text:r});if(!o.success)throw new Jr({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await qo(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function E0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await $0(e);throw new yl({toolName:e.toolName})}try{return await R0({toolCall:e,tools:t})}catch(a){if(r==null||!(yl.isInstance(a)||ml.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await fn(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new W6({cause:l,originalError:a})}if(i==null)throw a;return await R0({toolCall:i,tools:t})}}catch(a){const i=await Ht({text:e.input}),l=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function $0(e){const t=e.input.trim()===""?{success:!0,value:{}}:await Ht({text:e.input});if(t.success===!1)throw new ml({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function R0({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await $0(e);throw new yl({toolName:e.toolName,availableTools:Object.keys(t)})}const o=fn(n.inputSchema),s=e.input.trim()===""?await Bt({value:{},schema:o}):await Ht({text:e.input,schema:o});if(s.success===!1)throw new ml({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}var P0=class{constructor({content:e,finishReason:t,rawFinishReason:r,usage:n,warnings:o,request:s,response:a,providerMetadata:i}){this.content=e,this.finishReason=t,this.rawFinishReason=r,this.usage=n,this.warnings=o,this.request=s,this.response=a,this.providerMetadata=i}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!==!0)}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!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function Cl(e){return({steps:t})=>t.length===e}async function M0({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Tl({content:e,tools:t}){const r=[],n=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":n.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":n.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await Mo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await Mo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await Mo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function N0(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var F5=ko({prefix:"aitxt",size:24});async function O0({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Cl(1),experimental_output:g,output:p=g,experimental_telemetry:h,providerOptions:y,experimental_activeTools:w,activeTools:m=w,experimental_prepareStep:b,prepareStep:_=b,experimental_repairToolCall:f,experimental_download:C,experimental_context:k,experimental_include:v,_internal:{generateId:S=F5}={},onStepFinish:$,onFinish:E,...D}){const M=qs(e),N=Po(u),O=vl(l),L=r0(l),K=L!=null?new AbortController:void 0,H=N0(i,O!=null?AbortSignal.timeout(O):void 0,K?.signal),{maxRetries:le,retry:W}=k0({maxRetries:a,abortSignal:H}),Ee=wl(D),F=Br(c??{},`ai/${n0}`),A=m0({model:M,telemetry:h,headers:F,settings:{...Ee,maxRetries:le}}),B=await f0({system:n,prompt:o,messages:s}),z=g0(h);try{return await Ao({name:"ai.generateText",attributes:gr({telemetry:h,attributes:{...Oo({operationId:"ai.generateText",telemetry:h}),...A,"ai.model.provider":M.provider,"ai.model.id":M.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:z,fn:async I=>{var x,Z,ee,Y,ye,Ie,U,V,G,Q,ce;const ve=B.messages,R=[],{approvedToolApprovals:re,deniedToolApprovals:ge}=C0({messages:ve}),we=re.filter(Ve=>!Ve.toolCall.providerExecuted);if(ge.length>0||we.length>0){const Ve=await A0({toolCalls:we.map(Ce=>Ce.toolCall),tools:t,tracer:z,telemetry:h,messages:ve,abortSignal:H,experimental_context:k}),Ct=[];for(const Ce of Ve){const Ye=await Mo({toolCallId:Ce.toolCallId,input:Ce.input,tool:t?.[Ce.toolName],output:Ce.type==="tool-result"?Ce.output:Ce.error,errorMode:Ce.type==="tool-error"?"json":"none"});Ct.push({type:"tool-result",toolCallId:Ce.toolCallId,toolName:Ce.toolName,output:Ye})}for(const Ce of ge)Ct.push({type:"tool-result",toolCallId:Ce.toolCall.toolCallId,toolName:Ce.toolCall.toolName,output:{type:"execution-denied",reason:Ce.approvalResponse.reason,...Ce.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ce.approvalResponse.approvalId}}}}});R.push({role:"tool",content:Ct})}const Re=[...re,...ge].filter(Ve=>Ve.toolCall.providerExecuted);Re.length>0&&R.push({role:"tool",content:Re.map(Ve=>({type:"tool-approval-response",approvalId:Ve.approvalResponse.approvalId,approved:Ve.approvalResponse.approved,reason:Ve.approvalResponse.reason,providerExecuted:!0}))});const Ge=wl(D);let ae,st=[],kt=[];const ne=[],Ue=new Map;do{const Ve=L!=null?setTimeout(()=>K.abort(),L):void 0;try{const Ct=[...ve,...R],Ce=await _?.({model:M,steps:ne,stepNumber:ne.length,messages:Ct,experimental_context:k}),Ye=qs((x=Ce?.model)!=null?x:M),at=await a0({prompt:{system:(Z=Ce?.system)!=null?Z:B.system,messages:(ee=Ce?.messages)!=null?ee:Ct},supportedUrls:await Ye.supportedUrls,download:C});k=(Y=Ce?.experimental_context)!=null?Y:k;const{toolChoice:tn,tools:io}=await c0({tools:t,toolChoice:(ye=Ce?.toolChoice)!=null?ye:r,activeTools:(Ie=Ce?.activeTools)!=null?Ie:m});ae=await W(()=>{var Pe;return Ao({name:"ai.generateText.doGenerate",attributes:gr({telemetry:h,attributes:{...Oo({operationId:"ai.generateText.doGenerate",telemetry:h}),...A,"ai.model.provider":Ye.provider,"ai.model.id":Ye.modelId,"ai.prompt.messages":{input:()=>_0(at)},"ai.prompt.tools":{input:()=>io?.map(xt=>JSON.stringify(xt))},"ai.prompt.toolChoice":{input:()=>tn!=null?JSON.stringify(tn):void 0},"gen_ai.system":Ye.provider,"gen_ai.request.model":Ye.modelId,"gen_ai.request.frequency_penalty":D.frequencyPenalty,"gen_ai.request.max_tokens":D.maxOutputTokens,"gen_ai.request.presence_penalty":D.presencePenalty,"gen_ai.request.stop_sequences":D.stopSequences,"gen_ai.request.temperature":(Pe=D.temperature)!=null?Pe:void 0,"gen_ai.request.top_k":D.topK,"gen_ai.request.top_p":D.topP}}),tracer:z,fn:async xt=>{var Pn,Or,_i,vi,cs,lo,Ar,us;const xu=js(y,Ce?.providerOptions),gt=await Ye.doGenerate({...Ge,tools:io,toolChoice:tn,responseFormat:await p?.responseFormat,prompt:at,providerOptions:xu,abortSignal:H,headers:F}),Kt={id:(Or=(Pn=gt.response)==null?void 0:Pn.id)!=null?Or:S(),timestamp:(vi=(_i=gt.response)==null?void 0:_i.timestamp)!=null?vi:new Date,modelId:(lo=(cs=gt.response)==null?void 0:cs.modelId)!=null?lo:Ye.modelId,headers:(Ar=gt.response)==null?void 0:Ar.headers,body:(us=gt.response)==null?void 0:us.body};return xt.setAttributes(await gr({telemetry:h,attributes:{"ai.response.finishReason":gt.finishReason.unified,"ai.response.text":{output:()=>S0(gt.content)},"ai.response.reasoning":{output:()=>T0(gt.content)},"ai.response.toolCalls":{output:()=>{const nn=q0(gt.content);return nn==null?void 0:JSON.stringify(nn)}},"ai.response.id":Kt.id,"ai.response.model":Kt.modelId,"ai.response.timestamp":Kt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(gt.providerMetadata),"ai.usage.promptTokens":gt.usage.inputTokens.total,"ai.usage.completionTokens":gt.usage.outputTokens.total,"gen_ai.response.finish_reasons":[gt.finishReason.unified],"gen_ai.response.id":Kt.id,"gen_ai.response.model":Kt.modelId,"gen_ai.usage.input_tokens":gt.usage.inputTokens.total,"gen_ai.usage.output_tokens":gt.usage.outputTokens.total}})),{...gt,response:Kt}}})});const rn=await Promise.all(ae.content.filter(Pe=>Pe.type==="tool-call").map(Pe=>E0({toolCall:Pe,tools:t,repairToolCall:f,system:n,messages:Ct}))),_r={};for(const Pe of rn){if(Pe.invalid)continue;const xt=t?.[Pe.toolName];xt!=null&&(xt?.onInputAvailable!=null&&await xt.onInputAvailable({input:Pe.input,toolCallId:Pe.toolCallId,messages:Ct,abortSignal:H,experimental_context:k}),await x0({tool:xt,toolCall:Pe,messages:Ct,experimental_context:k})&&(_r[Pe.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Pe}))}const Iu=rn.filter(Pe=>Pe.invalid&&Pe.dynamic);kt=[];for(const Pe of Iu)kt.push({type:"tool-error",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:Pe.input,error:Hi(Pe.error),dynamic:!0});st=rn.filter(Pe=>!Pe.providerExecuted),t!=null&&kt.push(...await A0({toolCalls:st.filter(Pe=>!Pe.invalid&&_r[Pe.toolCallId]==null),tools:t,tracer:z,telemetry:h,messages:Ct,abortSignal:H,experimental_context:k}));for(const Pe of rn){if(!Pe.providerExecuted)continue;const xt=t?.[Pe.toolName];xt?.type==="provider"&&xt.supportsDeferredResults&&(ae.content.some(Or=>Or.type==="tool-result"&&Or.toolCallId===Pe.toolCallId)||Ue.set(Pe.toolCallId,{toolName:Pe.toolName}))}for(const Pe of ae.content)Pe.type==="tool-result"&&Ue.delete(Pe.toolCallId);const ls=Z5({content:ae.content,toolCalls:rn,toolOutputs:kt,toolApprovalRequests:Object.values(_r),tools:t});R.push(...await Tl({content:ls,tools:t}));const yi=(U=v?.requestBody)==null||U?(V=ae.request)!=null?V:{}:{...ae.request,body:void 0},Rn={...ae.response,messages:structuredClone(R),body:(G=v?.responseBody)==null||G?(Q=ae.response)==null?void 0:Q.body:void 0},Tt=new P0({content:ls,finishReason:ae.finishReason.unified,rawFinishReason:ae.finishReason.raw,usage:v0(ae.usage),warnings:ae.warnings,providerMetadata:ae.providerMetadata,request:yi,response:Rn});_l({warnings:(ce=ae.warnings)!=null?ce:[],provider:Ye.provider,model:Ye.modelId}),ne.push(Tt),await $?.(Tt)}finally{Ve!=null&&clearTimeout(Ve)}}while((st.length>0&&kt.length===st.length||Ue.size>0)&&!await M0({stopConditions:N,steps:ne}));I.setAttributes(await gr({telemetry:h,attributes:{"ai.response.finishReason":ae.finishReason.unified,"ai.response.text":{output:()=>S0(ae.content)},"ai.response.reasoning":{output:()=>T0(ae.content)},"ai.response.toolCalls":{output:()=>{const Ve=q0(ae.content);return Ve==null?void 0:JSON.stringify(Ve)}},"ai.response.providerMetadata":JSON.stringify(ae.providerMetadata),"ai.usage.promptTokens":ae.usage.inputTokens.total,"ai.usage.completionTokens":ae.usage.outputTokens.total}}));const Le=ne[ne.length-1],cr=ne.reduce((Ve,Ct)=>w0(Ve,Ct.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await E?.({finishReason:Le.finishReason,rawFinishReason:Le.rawFinishReason,usage:Le.usage,content:Le.content,text:Le.text,reasoningText:Le.reasoningText,reasoning:Le.reasoning,files:Le.files,sources:Le.sources,toolCalls:Le.toolCalls,staticToolCalls:Le.staticToolCalls,dynamicToolCalls:Le.dynamicToolCalls,toolResults:Le.toolResults,staticToolResults:Le.staticToolResults,dynamicToolResults:Le.dynamicToolResults,request:Le.request,response:Le.response,warnings:Le.warnings,providerMetadata:Le.providerMetadata,steps:ne,totalUsage:cr,experimental_context:k});let Nr;return Le.finishReason==="stop"&&(Nr=await(p??Us()).parseCompleteOutput({text:Le.text},{response:Le.response,usage:Le.usage,finishReason:Le.finishReason})),new V5({steps:ne,totalUsage:cr,output:Nr})}})}catch(I){throw h0(I)}}async function A0({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async l=>kl({toolCall:l,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a})))).filter(l=>l!=null)}var V5=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new qh;return this._output}};function q0(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function Z5({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new I0(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(i=>i.toolCallId===a.toolCallId));break}case"tool-result":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,error:a.result,providerExecuted:!0,dynamic:i.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,output:a.result,providerExecuted:!0,dynamic:i.dynamic});break}case"tool-approval-request":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null)throw new gl({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function Ds(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function B5({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Ds(r,{"content-type":"text/plain; charset=utf-8"})})}function L0({response:e,status:t,statusText:r,headers:n,stream:o}){const s=t??200;r!==void 0?e.writeHead(s,r,n):e.writeHead(s,n);const a=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await a.read();if(l)break;e.write(c)||await new Promise(g=>{e.once("drain",g)})}}catch(l){throw l}finally{e.end()}})()}function H5({response:e,status:t,statusText:r,headers:n,textStream:o}){L0({response:e,status:t,statusText:r,headers:Object.fromEntries(Ds(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var j0=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
63
+ `),{name:"GatewayAuthenticationError"})}function Fo({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function M0({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>{if(a==="timeout"){const l=Ll(i);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=i;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(n??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var Wk={startSpan(){return Ks},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Ks);if(typeof r=="function")return r(Ks);if(typeof n=="function")return n(Ks)}},Ks={spanContext(){return Kk},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}},Kk={traceId:"",spanId:"",traceFlags:0};function O0({isEnabled:e=!1,tracer:t}={}){return e?t||ek.getTracer("ai"):Wk}async function Vo({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=Rh.active();try{const i=await Rh.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{A0(s,i)}finally{s.end()}throw i}})}function A0(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Gs.ERROR,message:t.message})):e.setStatus({code:Gs.ERROR})}async function Ir({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function q0(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?Mk(r.data):r.data}:r)})))}function L0(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:ur(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Dl(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function j0(e,t){var r,n,o,s,a,i,l,c,u,m;return{inputTokens:ur(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:ur((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:ur((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:ur((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:ur(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:ur((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:ur((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:ur(e.totalTokens,t.totalTokens),reasoningTokens:ur(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:ur(e.cachedInputTokens,t.cachedInputTokens)}}function ur(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Ys(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]: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?r[n]=Ys(s,o):r[n]=o}return r}function Yk({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(n=a)}const s=r["retry-after"];if(s&&n===void 0){const a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var Qk=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>D0(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function D0(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(bn(a)||t===0)throw a;const i=ul(a),l=[...s,a],c=l.length;if(c>t)throw new g0({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&st.isInstance(a)&&a.isRetryable===!0&&c<=t)return await A3(Yk({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),D0(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new g0({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function U0({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Sr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Sr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:Qk({maxRetries:r,abortSignal:t})}}function z0({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],i=t.content.filter(l=>l.type==="tool-approval-response");for(const l of i){const c=n[l.approvalId];if(c==null)throw new sk({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new Ol({toolCallId:c.toolCallId,approvalId:c.approvalId});const m={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(m):a.push(m)}return{approvedToolApprovals:s,deniedToolApprovals:a}}function Qs(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Ul({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:m}){const{toolName:p,toolCallId:f,input:g}=e,v=t?.[p];if(v?.execute==null)return;const y={stepNumber:i,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:a};return Vo({name:"ai.toolCall",attributes:Ir({telemetry:n,attributes:{...Fo({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":f,"ai.toolCall.args":{output:()=>JSON.stringify(g)}}}),tracer:r,fn:async w=>{let _;await cr({event:y,callbacks:u});const h=Qs();try{const k=J9({execute:v.execute.bind(v),input:g,options:{toolCallId:f,messages:o,abortSignal:s,experimental_context:a}});for await(const b of k)b.type==="preliminary"?c?.({...e,type:"tool-result",output:b.output,preliminary:!0}):_=b.output}catch(k){const b=Qs()-h;return await cr({event:{...y,success:!1,error:k,durationMs:b},callbacks:m}),A0(w,k),{type:"tool-error",toolCallId:f,toolName:p,input:g,error:k,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const T=Qs()-h;await cr({event:{...y,success:!0,output:_,durationMs:T},callbacks:m});try{w.setAttributes(await Ir({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(_)}}}))}catch{}return{type:"tool-result",toolCallId:f,toolName:p,input:g,output:_,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function F0(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
64
+ `)}function V0(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Z0=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Kn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Wn(this.base64Data)),this.uint8ArrayData}},Xk=class extends Z0{constructor(e){super(e),this.type="file"}};async function B0({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var e5={};rk(e5,{array:()=>n5,choice:()=>o5,json:()=>s5,object:()=>r5,text:()=>Xs});function t5(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),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":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(n,l+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=e.slice(0,r+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 u=e.substring(n,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function Zo(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Qt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Qt({text:t5(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Xs=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),r5=({schema:e,name:t,description:r})=>{const n=Cn(e);return{name:"object",responseFormat:zt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await Qt({text:o});if(!a.success)throw new on({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=await Yt({value:a.value,schema:n});if(!i.success)throw new on({message:"No object generated: response did not match schema.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return i.value},async parsePartialOutput({text:o}){const s=await Zo(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},n5=({element:e,name:t,description:r})=>{const n=Cn(e);return{name:"array",responseFormat:zt(n.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const a=await Qt({text:o});if(!a.success)throw new on({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))throw new on({message:"No object generated: response did not match schema.",cause:new yn({value:i,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of i.elements){const c=await Yt({value:l,schema:n});if(!c.success)throw new on({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return i.elements},async parsePartialOutput({text:o}){const s=await Zo(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const i=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of i){const u=await Yt({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},o5=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const s=await Qt({text:n});if(!s.success)throw new on({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new on({message:"No object generated: response did not match schema.",cause:new yn({value:a,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:n}){const o=await Zo(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(i=>i.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),s5=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await Qt({text:r});if(!o.success)throw new on({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await Zo(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function H0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await J0(e);throw new Al({toolName:e.toolName})}try{return await G0({toolCall:e,tools:t})}catch(a){if(r==null||!(Al.isInstance(a)||Ml.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await Cn(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new fk({cause:l,originalError:a})}if(i==null)throw a;return await G0({toolCall:i,tools:t})}}catch(a){const i=await Qt({text:e.input}),l=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function J0(e){const t=e.input.trim()===""?{success:!0,value:{}}:await Qt({text:e.input});if(t.success===!1)throw new Ml({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function G0({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await J0(e);throw new Al({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Cn(n.inputSchema),s=e.input.trim()===""?await Yt({value:{},schema:o}):await Qt({text:e.input,schema:o});if(s.success===!1)throw new Ml({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}var W0=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:a,rawFinishReason:i,usage:l,warnings:c,request:u,response:m,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=s,this.finishReason=a,this.rawFinishReason=i,this.usage=l,this.warnings=c,this.request=u,this.response=m,this.providerMetadata=p}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!==!0)}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!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function zl(e){return({steps:t})=>t.length===e}async function K0({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Fl({content:e,tools:t}){const r=[],n=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":n.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":n.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await Uo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await Uo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await Uo({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function Y0(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var a5=No({prefix:"aitxt",size:24});async function Q0({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=zl(1),experimental_output:m,output:p=m,experimental_telemetry:f,providerOptions:g,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:w,prepareStep:_=w,experimental_repairToolCall:h,experimental_download:T,experimental_context:k,experimental_include:b,_internal:{generateId:S=a5}={},experimental_onStart:x,experimental_onStepStart:I,experimental_onToolCallStart:L,experimental_onToolCallFinish:$,onStepFinish:O,onFinish:A,...U}){const Z=Ws(e),Y=to(u),ye=Ll(l),X=w0(l),he=X!=null?new AbortController:void 0,B=Y0(i,ye!=null?AbortSignal.timeout(ye):void 0,he?.signal),{maxRetries:N,retry:H}=U0({maxRetries:a,abortSignal:B}),F=jl(U),E=rn(c??{},`ai/${b0}`),M=M0({model:Z,telemetry:f,headers:E,settings:{...F,maxRetries:N}}),D={provider:Z.provider,modelId:Z.modelId},G=await P0({system:n,prompt:o,messages:s});await cr({event:{model:D,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:F.maxOutputTokens,temperature:F.temperature,topP:F.topP,topK:F.topK,presencePenalty:F.presencePenalty,frequencyPenalty:F.frequencyPenalty,stopSequences:F.stopSequences,seed:F.seed,maxRetries:N,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:i,include:b,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k},callbacks:x});const te=O0(f);try{return await Vo({name:"ai.generateText",attributes:Ir({telemetry:f,attributes:{...Fo({operationId:"ai.generateText",telemetry:f}),...M,"ai.model.provider":Z.provider,"ai.model.id":Z.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:te,fn:async se=>{var Te,z,V,W,Q,ie,_e,Ye,ct,pt,rt,P,re;const Re=G.messages,Me=[],{approvedToolApprovals:nr,deniedToolApprovals:Qe}=z0({messages:Re}),Wt=nr.filter(ot=>!ot.toolCall.providerExecuted);if(Qe.length>0||Wt.length>0){const ot=await X0({toolCalls:Wt.map(Ce=>Ce.toolCall),tools:t,tracer:te,telemetry:f,messages:Re,abortSignal:B,experimental_context:k,stepNumber:0,model:D,onToolCallStart:L,onToolCallFinish:$}),Ct=[];for(const Ce of ot){const Mt=await Uo({toolCallId:Ce.toolCallId,input:Ce.input,tool:t?.[Ce.toolName],output:Ce.type==="tool-result"?Ce.output:Ce.error,errorMode:Ce.type==="tool-error"?"json":"none"});Ct.push({type:"tool-result",toolCallId:Ce.toolCallId,toolName:Ce.toolName,output:Mt})}for(const Ce of Qe)Ct.push({type:"tool-result",toolCallId:Ce.toolCall.toolCallId,toolName:Ce.toolCall.toolName,output:{type:"execution-denied",reason:Ce.approvalResponse.reason,...Ce.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ce.approvalResponse.approvalId}}}}});Me.push({role:"tool",content:Ct})}const Vr=[...nr,...Qe].filter(ot=>ot.toolCall.providerExecuted);Vr.length>0&&Me.push({role:"tool",content:Vr.map(ot=>({type:"tool-approval-response",approvalId:ot.approvalResponse.approvalId,approved:ot.approvalResponse.approved,reason:ot.approvalResponse.reason,providerExecuted:!0}))});const Xe=jl(U);let Se,nt=[],Ie=[];const He=[],_r=new Map;do{const ot=X!=null?setTimeout(()=>he.abort(),X):void 0;try{const Ct=[...Re,...Me],Ce=await _?.({model:Z,steps:He,stepNumber:He.length,messages:Ct,experimental_context:k}),Mt=Ws((Te=Ce?.model)!=null?Te:Z),ft={provider:Mt.provider,modelId:Mt.modelId},Tt=await T0({prompt:{system:(z=Ce?.system)!=null?z:G.system,messages:(V=Ce?.messages)!=null?V:Ct},supportedUrls:await Mt.supportedUrls,download:T});k=(W=Ce?.experimental_context)!=null?W:k;const ut=(Q=Ce?.activeTools)!=null?Q:y,{toolChoice:Zr,tools:_o}=await x0({tools:t,toolChoice:(ie=Ce?.toolChoice)!=null?ie:r,activeTools:ut}),Pi=(_e=Ce?.messages)!=null?_e:Ct,Ni=(Ye=Ce?.system)!=null?Ye:G.system,gs=Ys(g,Ce?.providerOptions);await cr({event:{stepNumber:He.length,model:ft,system:Ni,messages:Pi,tools:t,toolChoice:Zr,activeTools:ut,steps:[...He],providerOptions:gs,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:b,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k},callbacks:I}),Se=await H(()=>{var Oe;return Vo({name:"ai.generateText.doGenerate",attributes:Ir({telemetry:f,attributes:{...Fo({operationId:"ai.generateText.doGenerate",telemetry:f}),...M,"ai.model.provider":Mt.provider,"ai.model.id":Mt.modelId,"ai.prompt.messages":{input:()=>q0(Tt)},"ai.prompt.tools":{input:()=>_o?.map(Ot=>JSON.stringify(Ot))},"ai.prompt.toolChoice":{input:()=>Zr!=null?JSON.stringify(Zr):void 0},"gen_ai.system":Mt.provider,"gen_ai.request.model":Mt.modelId,"gen_ai.request.frequency_penalty":U.frequencyPenalty,"gen_ai.request.max_tokens":U.maxOutputTokens,"gen_ai.request.presence_penalty":U.presencePenalty,"gen_ai.request.stop_sequences":U.stopSequences,"gen_ai.request.temperature":(Oe=U.temperature)!=null?Oe:void 0,"gen_ai.request.top_k":U.topK,"gen_ai.request.top_p":U.topP}}),tracer:te,fn:async Ot=>{var hn,Br,Oi,Ai,ws,qi,bs,vo;const dt=await Mt.doGenerate({...Xe,tools:_o,toolChoice:Zr,responseFormat:await p?.responseFormat,prompt:Tt,providerOptions:gs,abortSignal:B,headers:E}),Hr={id:(Br=(hn=dt.response)==null?void 0:hn.id)!=null?Br:S(),timestamp:(Ai=(Oi=dt.response)==null?void 0:Oi.timestamp)!=null?Ai:new Date,modelId:(qi=(ws=dt.response)==null?void 0:ws.modelId)!=null?qi:Mt.modelId,headers:(bs=dt.response)==null?void 0:bs.headers,body:(vo=dt.response)==null?void 0:vo.body};return Ot.setAttributes(await Ir({telemetry:f,attributes:{"ai.response.finishReason":dt.finishReason.unified,"ai.response.text":{output:()=>V0(dt.content)},"ai.response.reasoning":{output:()=>F0(dt.content)},"ai.response.toolCalls":{output:()=>{const Li=em(dt.content);return Li==null?void 0:JSON.stringify(Li)}},"ai.response.id":Hr.id,"ai.response.model":Hr.modelId,"ai.response.timestamp":Hr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(dt.providerMetadata),"ai.usage.promptTokens":dt.usage.inputTokens.total,"ai.usage.completionTokens":dt.usage.outputTokens.total,"gen_ai.response.finish_reasons":[dt.finishReason.unified],"gen_ai.response.id":Hr.id,"gen_ai.response.model":Hr.modelId,"gen_ai.usage.input_tokens":dt.usage.inputTokens.total,"gen_ai.usage.output_tokens":dt.usage.outputTokens.total}})),{...dt,response:Hr}}})});const or=await Promise.all(Se.content.filter(Oe=>Oe.type==="tool-call").map(Oe=>H0({toolCall:Oe,tools:t,repairToolCall:h,system:n,messages:Ct}))),ys={};for(const Oe of or){if(Oe.invalid)continue;const Ot=t?.[Oe.toolName];Ot!=null&&(Ot?.onInputAvailable!=null&&await Ot.onInputAvailable({input:Oe.input,toolCallId:Oe.toolCallId,messages:Ct,abortSignal:B,experimental_context:k}),await B0({tool:Ot,toolCall:Oe,messages:Ct,experimental_context:k})&&(ys[Oe.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Oe}))}const Mi=or.filter(Oe=>Oe.invalid&&Oe.dynamic);Ie=[];for(const Oe of Mi)Ie.push({type:"tool-error",toolCallId:Oe.toolCallId,toolName:Oe.toolName,input:Oe.input,error:ul(Oe.error),dynamic:!0});nt=or.filter(Oe=>!Oe.providerExecuted),t!=null&&Ie.push(...await X0({toolCalls:nt.filter(Oe=>!Oe.invalid&&ys[Oe.toolCallId]==null),tools:t,tracer:te,telemetry:f,messages:Ct,abortSignal:B,experimental_context:k,stepNumber:He.length,model:ft,onToolCallStart:L,onToolCallFinish:$}));for(const Oe of or){if(!Oe.providerExecuted)continue;const Ot=t?.[Oe.toolName];Ot?.type==="provider"&&Ot.supportsDeferredResults&&(Se.content.some(Br=>Br.type==="tool-result"&&Br.toolCallId===Oe.toolCallId)||_r.set(Oe.toolCallId,{toolName:Oe.toolName}))}for(const Oe of Se.content)Oe.type==="tool-result"&&_r.delete(Oe.toolCallId);const _s=l5({content:Se.content,toolCalls:or,toolOutputs:Ie,toolApprovalRequests:Object.values(ys),tools:t});Me.push(...await Fl({content:_s,tools:t}));const fn=(ct=b?.requestBody)==null||ct?(pt=Se.request)!=null?pt:{}:{...Se.request,body:void 0},yt={...Se.response,messages:structuredClone(Me),body:(rt=b?.responseBody)==null||rt?(P=Se.response)==null?void 0:P.body:void 0},Er=He.length,vs=new W0({stepNumber:Er,model:ft,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k,content:_s,finishReason:Se.finishReason.unified,rawFinishReason:Se.finishReason.raw,usage:L0(Se.usage),warnings:Se.warnings,providerMetadata:Se.providerMetadata,request:fn,response:yt});ql({warnings:(re=Se.warnings)!=null?re:[],provider:ft.provider,model:ft.modelId}),He.push(vs),await cr({event:vs,callbacks:O})}finally{ot!=null&&clearTimeout(ot)}}while((nt.length>0&&Ie.length===nt.length||_r.size>0)&&!await K0({stopConditions:Y,steps:He}));se.setAttributes(await Ir({telemetry:f,attributes:{"ai.response.finishReason":Se.finishReason.unified,"ai.response.text":{output:()=>V0(Se.content)},"ai.response.reasoning":{output:()=>F0(Se.content)},"ai.response.toolCalls":{output:()=>{const ot=em(Se.content);return ot==null?void 0:JSON.stringify(ot)}},"ai.response.providerMetadata":JSON.stringify(Se.providerMetadata),"ai.usage.promptTokens":Se.usage.inputTokens.total,"ai.usage.completionTokens":Se.usage.outputTokens.total}}));const K=He[He.length-1],Je=He.reduce((ot,Ct)=>j0(ot,Ct.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await cr({event:{stepNumber:K.stepNumber,model:K.model,functionId:K.functionId,metadata:K.metadata,experimental_context:K.experimental_context,finishReason:K.finishReason,rawFinishReason:K.rawFinishReason,usage:K.usage,content:K.content,text:K.text,reasoningText:K.reasoningText,reasoning:K.reasoning,files:K.files,sources:K.sources,toolCalls:K.toolCalls,staticToolCalls:K.staticToolCalls,dynamicToolCalls:K.dynamicToolCalls,toolResults:K.toolResults,staticToolResults:K.staticToolResults,dynamicToolResults:K.dynamicToolResults,request:K.request,response:K.response,warnings:K.warnings,providerMetadata:K.providerMetadata,steps:He,totalUsage:Je},callbacks:A});let vr;return K.finishReason==="stop"&&(vr=await(p??Xs()).parseCompleteOutput({text:K.text},{response:K.response,usage:K.usage,finishReason:K.finishReason})),new i5({steps:He,totalUsage:Je,output:vr})}})}catch(se){throw N0(se)}}async function X0({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>Ul({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var i5=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new e0;return this._output}};function em(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function l5({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new Z0(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(i=>i.toolCallId===a.toolCallId));break}case"tool-result":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,error:a.result,providerExecuted:!0,dynamic:i.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,output:a.result,providerExecuted:!0,dynamic:i.dynamic});break}case"tool-approval-request":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null)throw new Ol({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function ea(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function c5({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:ea(r,{"content-type":"text/plain; charset=utf-8"})})}function tm({response:e,status:t,statusText:r,headers:n,stream:o}){const s=t??200;r!==void 0?e.writeHead(s,r,n):e.writeHead(s,n);const a=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await a.read();if(l)break;e.write(c)||await new Promise(m=>{e.once("drain",m)})}}catch(l){throw l}finally{e.end()}})()}function u5({response:e,status:t,statusText:r,headers:n,textStream:o}){tm({response:e,status:t,statusText:r,headers:Object.fromEntries(ea(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var rm=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
65
65
 
66
66
  `)},flush(e){e.enqueue(`data: [DONE]
67
67
 
68
- `)}})}},U0={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function J5({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new j0);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Ds(r,U0)})}function G5({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function W5(e){return e.type.startsWith("data-")}function Sl(e){return e.type.startsWith("tool-")}function K5(e){return e.type==="dynamic-tool"}function Y5(e){return Sl(e)||K5(e)}function D0(e){return e.type.split("-").slice(1).join("-")}function Q5({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function X5({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var g,p,h,y;function w(f){const k=c.message.parts.filter(Y5).find(v=>v.toolCallId===f);if(k==null)throw new Bn({chunkType:"tool-invocation",chunkId:f,message:`No tool invocation found for tool call ID "${f}".`});return k}function m(f){var C;const k=c.message.parts.find($=>Sl($)&&$.toolCallId===f.toolCallId),v=f,S=k;k!=null?(k.state=f.state,S.input=v.input,S.output=v.output,S.errorText=v.errorText,S.rawInput=v.rawInput,S.preliminary=v.preliminary,f.title!==void 0&&(S.title=f.title),S.providerExecuted=(C=v.providerExecuted)!=null?C:k.providerExecuted,v.providerMetadata!=null&&(k.callProviderMetadata=v.providerMetadata)):c.message.parts.push({type:`tool-${f.toolName}`,toolCallId:f.toolCallId,state:f.state,title:f.title,input:v.input,output:v.output,rawInput:v.rawInput,errorText:v.errorText,providerExecuted:v.providerExecuted,preliminary:v.preliminary,...v.providerMetadata!=null?{callProviderMetadata:v.providerMetadata}:{}})}function b(f){var C,k;const v=c.message.parts.find(E=>E.type==="dynamic-tool"&&E.toolCallId===f.toolCallId),S=f,$=v;v!=null?(v.state=f.state,$.toolName=f.toolName,$.input=S.input,$.output=S.output,$.errorText=S.errorText,$.rawInput=(C=S.rawInput)!=null?C:$.rawInput,$.preliminary=S.preliminary,f.title!==void 0&&($.title=f.title),$.providerExecuted=(k=S.providerExecuted)!=null?k:v.providerExecuted,S.providerMetadata!=null&&(v.callProviderMetadata=S.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:f.toolName,toolCallId:f.toolCallId,state:f.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,providerExecuted:S.providerExecuted,title:f.title,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function _(f){if(f!=null){const C=c.message.metadata!=null?js(c.message.metadata,f):f;t!=null&&await Rt({value:C,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=C}}switch(i.type){case"text-start":{const f={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=f,c.message.parts.push(f),u();break}case"text-delta":{const f=c.activeTextParts[i.id];if(f==null)throw new Bn({chunkType:"text-delta",chunkId:i.id,message:`Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});f.text+=i.delta,f.providerMetadata=(g=i.providerMetadata)!=null?g:f.providerMetadata,u();break}case"text-end":{const f=c.activeTextParts[i.id];if(f==null)throw new Bn({chunkType:"text-end",chunkId:i.id,message:`Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});f.state="done",f.providerMetadata=(p=i.providerMetadata)!=null?p:f.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const f={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=f,c.message.parts.push(f),u();break}case"reasoning-delta":{const f=c.activeReasoningParts[i.id];if(f==null)throw new Bn({chunkType:"reasoning-delta",chunkId:i.id,message:`Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});f.text+=i.delta,f.providerMetadata=(h=i.providerMetadata)!=null?h:f.providerMetadata,u();break}case"reasoning-end":{const f=c.activeReasoningParts[i.id];if(f==null)throw new Bn({chunkType:"reasoning-end",chunkId:i.id,message:`Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});f.providerMetadata=(y=i.providerMetadata)!=null?y:f.providerMetadata,f.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const f=c.message.parts.filter(Sl);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:f.length,dynamic:i.dynamic,title:i.title},i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}):m({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"tool-input-delta":{const f=c.partialToolCalls[i.toolCallId];if(f==null)throw new Bn({chunkType:"tool-input-delta",chunkId:i.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});f.text+=i.inputTextDelta;const{value:C}=await qo(f.text);f.dynamic?b({toolCallId:i.toolCallId,toolName:f.toolName,state:"input-streaming",input:C,title:f.title}):m({toolCallId:i.toolCallId,toolName:f.toolName,state:"input-streaming",input:C,title:f.title}),u();break}case"tool-input-available":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}):m({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}),u(),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,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):m({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-approval-request":{const f=w(i.toolCallId);f.state="approval-requested",f.approval={id:i.approvalId},u();break}case"tool-output-denied":{const f=w(i.toolCallId);f.state="output-denied",u();break}case"tool-output-available":{const f=w(i.toolCallId);f.type==="dynamic-tool"?b({toolCallId:i.toolCallId,toolName:f.toolName,state:"output-available",input:f.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:f.title}):m({toolCallId:i.toolCallId,toolName:D0(f),state:"output-available",input:f.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,title:f.title}),u();break}case"tool-output-error":{const f=w(i.toolCallId);f.type==="dynamic-tool"?b({toolCallId:i.toolCallId,toolName:f.toolName,state:"output-error",input:f.input,errorText:i.errorText,providerExecuted:i.providerExecuted,title:f.title}):m({toolCallId:i.toolCallId,toolName:D0(f),state:"output-error",input:f.input,rawInput:f.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,title:f.title}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(W5(i)){if(r?.[i.type]!=null){const k=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===i.id&&S.type===i.type),v=k>=0?k:c.message.parts.length;await Rt({value:i.data,schema:r[i.type],context:{field:`message.parts[${v}].data`,entityName:i.type,entityId:i.id}})}const f=i;if(f.transient){a?.(f);break}const C=f.id!=null?c.message.parts.find(k=>f.type===k.type&&f.id===k.id):void 0;C!=null?C.data=f.data:c.message.parts.push(f),a?.(f),u()}}l.enqueue(i)})}}))}function ek({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let a=t?.[t.length-1];a?.role!=="assistant"?a=void 0:e=a.id;let i=!1;const l=s.pipeThrough(new TransformStream({transform(y,w){if(y.type==="start"){const m=y;m.messageId==null&&e!=null&&(m.messageId=e)}y.type==="abort"&&(i=!0),w.enqueue(y)}}));if(n==null&&r==null)return l;const c=Q5({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async y=>{await y({state:c,write:()=>{}})};let g=!1;const p=async()=>{if(g||!n)return;g=!0;const y=c.message.id===a?.id;await n({isAborted:i,isContinuation:y,responseMessage:c.message,messages:[...y?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},h=async()=>{if(!r)return;const y=c.message.id===a?.id;try{await r({isContinuation:y,responseMessage:structuredClone(c.message),messages:[...y?t.slice(0,-1):t,structuredClone(c.message)]})}catch(w){o(w)}};return X5({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(y,w){y.type==="finish-step"&&await h(),w.enqueue(y)},async cancel(){await p()},async flush(){await p()}}))}function tk({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new j0);if(s){const[i,l]=a.tee();a=i,s({stream:l})}L0({response:e,status:t,statusText:r,headers:Object.fromEntries(Ds(n,U0).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Lo(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var a;if(!n){n=!0;try{s&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:a}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function rk({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function z0(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function nk(){let e=[],t=null,r=!1,n=z0();const o=()=>{r=!0,n.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=z0(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length===0&&r?t?.close():await s()):t?.enqueue(a)}catch(a){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=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function ok(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function sk({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l,generateId:c}){let u=null;const g=new ReadableStream({start(f){u=f}}),p=new Set,h=new Map,y=new Map;let w=!1,m;function b(){w&&p.size===0&&(m!=null&&u.enqueue(m),u.close())}const _=new TransformStream({async transform(f,C){const k=f.type;switch(k){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":{C.enqueue(f);break}case"file":{C.enqueue({type:"file",file:new A5({data:f.data,mediaType:f.mediaType})});break}case"finish":{m={type:"finish",finishReason:f.finishReason.unified,rawFinishReason:f.finishReason.raw,usage:v0(f.usage),providerMetadata:f.providerMetadata};break}case"tool-approval-request":{const v=y.get(f.toolCallId);if(v==null){u.enqueue({type:"error",error:new gl({toolCallId:f.toolCallId,approvalId:f.approvalId})});break}C.enqueue({type:"tool-approval-request",approvalId:f.approvalId,toolCall:v});break}case"tool-call":{try{const v=await E0({toolCall:f,tools:e,repairToolCall:i,system:o,messages:s});if(y.set(v.toolCallId,v),C.enqueue(v),v.invalid){u.enqueue({type:"tool-error",toolCallId:v.toolCallId,toolName:v.toolName,input:v.input,error:Hi(v.error),dynamic:!0,title:v.title});break}const S=e?.[v.toolName];if(S==null)break;if(S.onInputAvailable!=null&&await S.onInputAvailable({input:v.input,toolCallId:v.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await x0({tool:S,toolCall:v,messages:s,experimental_context:l})){u.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:v});break}if(h.set(v.toolCallId,v.input),S.execute!=null&&v.providerExecuted!==!0){const $=c();p.add($),kl({toolCall:v,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,onPreliminaryToolResult:E=>{u.enqueue(E)}}).then(E=>{u.enqueue(E)}).catch(E=>{u.enqueue({type:"error",error:E})}).finally(()=>{p.delete($),b()})}}catch(v){u.enqueue({type:"error",error:v})}break}case"tool-result":{const v=f.toolName;f.isError?u.enqueue({type:"tool-error",toolCallId:f.toolCallId,toolName:v,input:h.get(f.toolCallId),providerExecuted:!0,error:f.result,dynamic:f.dynamic}):C.enqueue({type:"tool-result",toolCallId:f.toolCallId,toolName:v,input:h.get(f.toolCallId),output:f.result,providerExecuted:!0,dynamic:f.dynamic});break}default:{const v=k;throw new Error(`Unhandled chunk type: ${v}`)}}},flush(){w=!0,b()}});return new ReadableStream({async start(f){return Promise.all([t.pipeThrough(_).pipeTo(new WritableStream({write(C){f.enqueue(C)},close(){}})),g.pipeTo(new WritableStream({write(C){f.enqueue(C)},close(){f.close()}}))])}})}var ak=ko({prefix:"aitxt",size:24});function Il({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Cl(1),experimental_output:g,output:p=g,experimental_telemetry:h,prepareStep:y,providerOptions:w,experimental_activeTools:m,activeTools:b=m,experimental_repairToolCall:_,experimental_transform:f,experimental_download:C,includeRawChunks:k=!1,onChunk:v,onError:S=({error:H})=>{console.error(H)},onFinish:$,onAbort:E,onStepFinish:D,experimental_context:M,experimental_include:N,_internal:{now:O=ok,generateId:L=ak}={},...K}){const H=vl(l),le=r0(l),W=i5(l),Ee=le!=null?new AbortController:void 0,F=W!=null?new AbortController:void 0;return new lk({model:qs(e),telemetry:h,headers:c,settings:K,maxRetries:a,abortSignal:N0(i,H!=null?AbortSignal.timeout(H):void 0,Ee?.signal,F?.signal),stepTimeoutMs:le,stepAbortController:Ee,chunkTimeoutMs:W,chunkAbortController:F,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Po(f),activeTools:b,repairToolCall:_,stopConditions:Po(u),output:p,providerOptions:w,prepareStep:y,includeRawChunks:k,onChunk:v,onError:S,onFinish:$,onAbort:E,onStepFinish:D,now:O,generateId:L,experimental_context:M,download:C,include:N})}function ik(e){let t,r="",n="",o,s="";function a({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&a({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&a({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const g=JSON.stringify(u.partial);g!==s&&(a({controller:l,partialOutput:u.partial}),s=g)}}})}var lk=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:a,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:g,messages:p,tools:h,toolChoice:y,transforms:w,activeTools:m,repairToolCall:b,stopConditions:_,output:f,providerOptions:C,prepareStep:k,includeRawChunks:v,now:S,generateId:$,onChunk:E,onError:D,onFinish:M,onAbort:N,onStepFinish:O,experimental_context:L,download:K,include:H}){this._totalUsage=new bo,this._finishReason=new bo,this._rawFinishReason=new bo,this._steps=new bo,this.outputSpecification=f,this.includeRawChunks=v,this.tools=h;let le,W=[];const Ee=[];let F,A,B,z={},I=[];const x=[],Z=new Map;let ee,Y={},ye={};const Ie=new TransformStream({async transform(we,Re){var Ge,ae,st,kt;Re.enqueue(we);const{part:ne}=we;if((ne.type==="text-delta"||ne.type==="reasoning-delta"||ne.type==="source"||ne.type==="tool-call"||ne.type==="tool-result"||ne.type==="tool-input-start"||ne.type==="tool-input-delta"||ne.type==="raw")&&await E?.({chunk:ne}),ne.type==="error"&&await D({error:h0(ne.error)}),ne.type==="text-start"&&(Y[ne.id]={type:"text",text:"",providerMetadata:ne.providerMetadata},W.push(Y[ne.id])),ne.type==="text-delta"){const Ue=Y[ne.id];if(Ue==null){Re.enqueue({part:{type:"error",error:`text part ${ne.id} not found`},partialOutput:void 0});return}Ue.text+=ne.text,Ue.providerMetadata=(Ge=ne.providerMetadata)!=null?Ge:Ue.providerMetadata}if(ne.type==="text-end"){const Ue=Y[ne.id];if(Ue==null){Re.enqueue({part:{type:"error",error:`text part ${ne.id} not found`},partialOutput:void 0});return}Ue.providerMetadata=(ae=ne.providerMetadata)!=null?ae:Ue.providerMetadata,delete Y[ne.id]}if(ne.type==="reasoning-start"&&(ye[ne.id]={type:"reasoning",text:"",providerMetadata:ne.providerMetadata},W.push(ye[ne.id])),ne.type==="reasoning-delta"){const Ue=ye[ne.id];if(Ue==null){Re.enqueue({part:{type:"error",error:`reasoning part ${ne.id} not found`},partialOutput:void 0});return}Ue.text+=ne.text,Ue.providerMetadata=(st=ne.providerMetadata)!=null?st:Ue.providerMetadata}if(ne.type==="reasoning-end"){const Ue=ye[ne.id];if(Ue==null){Re.enqueue({part:{type:"error",error:`reasoning part ${ne.id} not found`},partialOutput:void 0});return}Ue.providerMetadata=(kt=ne.providerMetadata)!=null?kt:Ue.providerMetadata,delete ye[ne.id]}if(ne.type==="file"&&W.push({type:"file",file:ne.file}),ne.type==="source"&&W.push(ne),ne.type==="tool-call"&&W.push(ne),ne.type==="tool-result"&&!ne.preliminary&&W.push(ne),ne.type==="tool-approval-request"&&W.push(ne),ne.type==="tool-error"&&W.push(ne),ne.type==="start-step"&&(W=[],ye={},Y={},z=ne.request,I=ne.warnings),ne.type==="finish-step"){const Ue=await Tl({content:W,tools:h}),Le=new P0({content:W,finishReason:ne.finishReason,rawFinishReason:ne.rawFinishReason,usage:ne.usage,warnings:I,request:z,response:{...ne.response,messages:[...Ee,...Ue]},providerMetadata:ne.providerMetadata});await O?.(Le),_l({warnings:I,provider:e.provider,model:e.modelId}),x.push(Le),Ee.push(...Ue),le.resolve()}ne.type==="finish"&&(B=ne.totalUsage,F=ne.finishReason,A=ne.rawFinishReason)},async flush(we){try{if(x.length===0){const st=s?.aborted?s.reason:new qh({message:"No output generated. Check the stream for errors."});ge._finishReason.reject(st),ge._rawFinishReason.reject(st),ge._totalUsage.reject(st),ge._steps.reject(st);return}const Re=F??"other",Ge=B??bl();ge._finishReason.resolve(Re),ge._rawFinishReason.resolve(A),ge._totalUsage.resolve(Ge),ge._steps.resolve(x);const ae=x[x.length-1];await M?.({finishReason:ae.finishReason,rawFinishReason:ae.rawFinishReason,totalUsage:Ge,usage:ae.usage,content:ae.content,text:ae.text,reasoningText:ae.reasoningText,reasoning:ae.reasoning,files:ae.files,sources:ae.sources,toolCalls:ae.toolCalls,staticToolCalls:ae.staticToolCalls,dynamicToolCalls:ae.dynamicToolCalls,toolResults:ae.toolResults,staticToolResults:ae.staticToolResults,dynamicToolResults:ae.dynamicToolResults,request:ae.request,response:ae.response,warnings:ae.warnings,providerMetadata:ae.providerMetadata,steps:x,experimental_context:L}),ee.setAttributes(await gr({telemetry:t,attributes:{"ai.response.finishReason":Re,"ai.response.text":{output:()=>ae.text},"ai.response.reasoning":{output:()=>ae.reasoningText},"ai.response.toolCalls":{output:()=>{var st;return(st=ae.toolCalls)!=null&&st.length?JSON.stringify(ae.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ae.providerMetadata),"ai.usage.inputTokens":Ge.inputTokens,"ai.usage.outputTokens":Ge.outputTokens,"ai.usage.totalTokens":Ge.totalTokens,"ai.usage.reasoningTokens":Ge.reasoningTokens,"ai.usage.cachedInputTokens":Ge.cachedInputTokens}}))}catch(Re){we.error(Re)}finally{ee.end()}}}),U=nk();this.addStream=U.addStream,this.closeStream=U.close;const V=U.stream.getReader();let G=new ReadableStream({async start(we){we.enqueue({type:"start"})},async pull(we){function Re(){N?.({steps:x}),we.enqueue({type:"abort",...s?.reason!==void 0?{reason:on(s.reason)}:{}}),we.close()}try{const{done:Ge,value:ae}=await V.read();if(Ge){we.close();return}if(s?.aborted){Re();return}we.enqueue(ae)}catch(Ge){dn(Ge)&&s?.aborted?Re():we.error(Ge)}},cancel(we){return U.stream.cancel(we)}});for(const we of w)G=G.pipeThrough(we({tools:h,stopStream(){U.terminate()}}));this.baseStream=G.pipeThrough(ik(f??Us())).pipeThrough(Ie);const{maxRetries:Q,retry:ce}=k0({maxRetries:o,abortSignal:s}),ve=g0(t),R=wl(n),re=m0({model:e,telemetry:t,headers:r,settings:{...R,maxRetries:Q}}),ge=this;Ao({name:"ai.streamText",attributes:gr({telemetry:t,attributes:{...Oo({operationId:"ai.streamText",telemetry:t}),...re,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:g,messages:p})}}}),tracer:ve,endWhenDone:!1,fn:async we=>{ee=we;const Re=await f0({system:u,prompt:g,messages:p}),Ge=Re.messages,ae=[],{approvedToolApprovals:st,deniedToolApprovals:kt}=C0({messages:Ge});if(kt.length>0||st.length>0){const Ue=[...st,...kt].filter(Ce=>Ce.toolCall.providerExecuted),Le=st.filter(Ce=>!Ce.toolCall.providerExecuted),cr=kt.filter(Ce=>!Ce.toolCall.providerExecuted),Nr=kt.filter(Ce=>Ce.toolCall.providerExecuted);let Ve;const Ct=new ReadableStream({start(Ce){Ve=Ce}});ge.addStream(Ct);try{for(const Ye of[...cr,...Nr])Ve?.enqueue({type:"tool-output-denied",toolCallId:Ye.toolCall.toolCallId,toolName:Ye.toolCall.toolName});const Ce=[];if(await Promise.all(Le.map(async Ye=>{const at=await kl({toolCall:Ye.toolCall,tools:h,tracer:ve,telemetry:t,messages:Ge,abortSignal:s,experimental_context:L,onPreliminaryToolResult:tn=>{Ve?.enqueue(tn)}});at!=null&&(Ve?.enqueue(at),Ce.push(at))})),Ue.length>0&&ae.push({role:"tool",content:Ue.map(Ye=>({type:"tool-approval-response",approvalId:Ye.approvalResponse.approvalId,approved:Ye.approvalResponse.approved,reason:Ye.approvalResponse.reason,providerExecuted:!0}))}),Ce.length>0||cr.length>0){const Ye=[];for(const at of Ce)Ye.push({type:"tool-result",toolCallId:at.toolCallId,toolName:at.toolName,output:await Mo({toolCallId:at.toolCallId,input:at.input,tool:h?.[at.toolName],output:at.type==="tool-result"?at.output:at.error,errorMode:at.type==="tool-error"?"json":"none"})});for(const at of cr)Ye.push({type:"tool-result",toolCallId:at.toolCall.toolCallId,toolName:at.toolCall.toolName,output:{type:"execution-denied",reason:at.approvalResponse.reason}});ae.push({role:"tool",content:Ye})}}finally{Ve?.close()}}Ee.push(...ae);async function ne({currentStep:Ue,responseMessages:Le,usage:cr}){var Nr,Ve,Ct,Ce,Ye,at,tn;const io=ge.includeRawChunks,rn=a!=null?setTimeout(()=>i.abort(),a):void 0;let _r;function Iu(){l!=null&&(_r!=null&&clearTimeout(_r),_r=setTimeout(()=>c.abort(),l))}function ls(){_r!=null&&(clearTimeout(_r),_r=void 0)}function yi(){rn!=null&&clearTimeout(rn)}try{le=new bo;const Rn=[...Ge,...Le],Tt=await k?.({model:e,steps:x,stepNumber:x.length,messages:Rn,experimental_context:L}),Pe=qs((Nr=Tt?.model)!=null?Nr:e),xt=await a0({prompt:{system:(Ve=Tt?.system)!=null?Ve:Re.system,messages:(Ct=Tt?.messages)!=null?Ct:Rn},supportedUrls:await Pe.supportedUrls,download:K}),{toolChoice:Pn,tools:Or}=await c0({tools:h,toolChoice:(Ce=Tt?.toolChoice)!=null?Ce:y,activeTools:(Ye=Tt?.activeTools)!=null?Ye:m});L=(at=Tt?.experimental_context)!=null?at:L;const _i=js(C,Tt?.providerOptions),{result:{stream:vi,response:cs,request:lo},doStreamSpan:Ar,startTimestampMs:us}=await ce(()=>Ao({name:"ai.streamText.doStream",attributes:gr({telemetry:t,attributes:{...Oo({operationId:"ai.streamText.doStream",telemetry:t}),...re,"ai.model.provider":Pe.provider,"ai.model.id":Pe.modelId,"ai.prompt.messages":{input:()=>_0(xt)},"ai.prompt.tools":{input:()=>Or?.map(_e=>JSON.stringify(_e))},"ai.prompt.toolChoice":{input:()=>Pn!=null?JSON.stringify(Pn):void 0},"gen_ai.system":Pe.provider,"gen_ai.request.model":Pe.modelId,"gen_ai.request.frequency_penalty":R.frequencyPenalty,"gen_ai.request.max_tokens":R.maxOutputTokens,"gen_ai.request.presence_penalty":R.presencePenalty,"gen_ai.request.stop_sequences":R.stopSequences,"gen_ai.request.temperature":R.temperature,"gen_ai.request.top_k":R.topK,"gen_ai.request.top_p":R.topP}}),tracer:ve,endWhenDone:!1,fn:async _e=>({startTimestampMs:S(),doStreamSpan:_e,result:await Pe.doStream({...R,tools:Or,toolChoice:Pn,responseFormat:await f?.responseFormat,prompt:xt,providerOptions:_i,abortSignal:s,headers:r,includeRawChunks:io})})})),xu=sk({tools:h,generatorStream:vi,tracer:ve,telemetry:t,system:u,messages:Rn,repairToolCall:b,abortSignal:s,experimental_context:L,generateId:$}),gt=(tn=H?.requestBody)==null||tn?lo??{}:{...lo,body:void 0},Kt=[],nn=[];let Eu;const $u={};let co="other",Ru,ur=bl(),Pu,E_=!0,vr={id:$(),timestamp:new Date,modelId:e.modelId},$_="";ge.addStream(xu.pipeThrough(new TransformStream({async transform(_e,St){var ds,ps,wi,it,wr;if(Iu(),_e.type==="stream-start"){Eu=_e.warnings;return}if(E_){const lt=S()-us;E_=!1,Ar.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":lt}),Ar.setAttributes({"ai.response.msToFirstChunk":lt}),St.enqueue({type:"start-step",request:gt,warnings:Eu??[]})}const Mu=_e.type;switch(Mu){case"tool-approval-request":case"text-start":case"text-end":{St.enqueue(_e);break}case"text-delta":{_e.delta.length>0&&(St.enqueue({type:"text-delta",id:_e.id,text:_e.delta,providerMetadata:_e.providerMetadata}),$_+=_e.delta);break}case"reasoning-start":case"reasoning-end":{St.enqueue(_e);break}case"reasoning-delta":{St.enqueue({type:"reasoning-delta",id:_e.id,text:_e.delta,providerMetadata:_e.providerMetadata});break}case"tool-call":{St.enqueue(_e),Kt.push(_e);break}case"tool-result":{St.enqueue(_e),_e.preliminary||nn.push(_e);break}case"tool-error":{St.enqueue(_e),nn.push(_e);break}case"response-metadata":{vr={id:(ds=_e.id)!=null?ds:vr.id,timestamp:(ps=_e.timestamp)!=null?ps:vr.timestamp,modelId:(wi=_e.modelId)!=null?wi:vr.modelId};break}case"finish":{ur=_e.usage,co=_e.finishReason,Ru=_e.rawFinishReason,Pu=_e.providerMetadata;const lt=S()-us;Ar.addEvent("ai.stream.finish"),Ar.setAttributes({"ai.response.msToFinish":lt,"ai.response.avgOutputTokensPerSecond":1e3*((it=ur.outputTokens)!=null?it:0)/lt});break}case"file":{St.enqueue(_e);break}case"source":{St.enqueue(_e);break}case"tool-input-start":{$u[_e.id]=_e.toolName;const lt=h?.[_e.toolName];lt?.onInputStart!=null&&await lt.onInputStart({toolCallId:_e.id,messages:Rn,abortSignal:s,experimental_context:L}),St.enqueue({..._e,dynamic:(wr=_e.dynamic)!=null?wr:lt?.type==="dynamic",title:lt?.title});break}case"tool-input-end":{delete $u[_e.id],St.enqueue(_e);break}case"tool-input-delta":{const lt=$u[_e.id],Nu=h?.[lt];Nu?.onInputDelta!=null&&await Nu.onInputDelta({inputTextDelta:_e.delta,toolCallId:_e.id,messages:Rn,abortSignal:s,experimental_context:L}),St.enqueue(_e);break}case"error":{St.enqueue(_e),co="error";break}case"raw":{io&&St.enqueue(_e);break}default:{const lt=Mu;throw new Error(`Unknown chunk type: ${lt}`)}}},async flush(_e){const St=Kt.length>0?JSON.stringify(Kt):void 0;try{Ar.setAttributes(await gr({telemetry:t,attributes:{"ai.response.finishReason":co,"ai.response.text":{output:()=>$_},"ai.response.reasoning":{output:()=>{const it=W.filter(wr=>wr.type==="reasoning");return it.length>0?it.map(wr=>wr.text).join(`
69
- `):void 0}},"ai.response.toolCalls":{output:()=>St},"ai.response.id":vr.id,"ai.response.model":vr.modelId,"ai.response.timestamp":vr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Pu),"ai.usage.inputTokens":ur.inputTokens,"ai.usage.outputTokens":ur.outputTokens,"ai.usage.totalTokens":ur.totalTokens,"ai.usage.reasoningTokens":ur.reasoningTokens,"ai.usage.cachedInputTokens":ur.cachedInputTokens,"gen_ai.response.finish_reasons":[co],"gen_ai.response.id":vr.id,"gen_ai.response.model":vr.modelId,"gen_ai.usage.input_tokens":ur.inputTokens,"gen_ai.usage.output_tokens":ur.outputTokens}}))}catch{}finally{Ar.end()}_e.enqueue({type:"finish-step",finishReason:co,rawFinishReason:Ru,usage:ur,providerMetadata:Pu,response:{...vr,headers:cs?.headers}});const ds=w0(cr,ur);await le.promise;const ps=Kt.filter(it=>it.providerExecuted!==!0),wi=nn.filter(it=>it.providerExecuted!==!0);for(const it of Kt){if(it.providerExecuted!==!0)continue;const wr=h?.[it.toolName];wr?.type==="provider"&&wr.supportsDeferredResults&&(nn.some(lt=>(lt.type==="tool-result"||lt.type==="tool-error")&&lt.toolCallId===it.toolCallId)||Z.set(it.toolCallId,{toolName:it.toolName}))}for(const it of nn)(it.type==="tool-result"||it.type==="tool-error")&&Z.delete(it.toolCallId);if(yi(),ls(),(ps.length>0&&wi.length===ps.length||Z.size>0)&&!await M0({stopConditions:_,steps:x})){Le.push(...await Tl({content:x[x.length-1].content,tools:h}));try{await ne({currentStep:Ue+1,responseMessages:Le,usage:ds})}catch(it){_e.enqueue({type:"error",error:it}),ge.closeStream()}}else _e.enqueue({type:"finish",finishReason:co,rawFinishReason:Ru,totalUsage:ds}),ge.closeStream()}})))}finally{yi(),ls()}}await ne({currentStep:0,responseMessages:ae,usage:bl()})}}).catch(we=>{ge.addStream(new ReadableStream({start(Re){Re.enqueue({type:"error",error:we}),Re.close()}})),ge.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}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Lo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Lo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await rk({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Lo(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new dr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Lo(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Us()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=on}={}){const c=t!=null?G5({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var h;const y=(h=this.tools)==null?void 0:h[p.toolName];return y==null?p.dynamic:y?.type==="dynamic"?!0:void 0},g=this.fullStream.pipeThrough(new TransformStream({transform:async(p,h)=>{const y=n?.({part:p}),w=p.type;switch(w){case"text-start":{h.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&h.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{s&&p.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const m=u(p);h.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...m!=null?{dynamic:m}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const m=u(p);p.invalid?h.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...m!=null?{dynamic:m}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...m!=null?{dynamic:m}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const m=u(p);h.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...m!=null?{dynamic:m}:{}});break}case"tool-error":{const m=u(p);h.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...m!=null?{dynamic:m}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{a&&h.enqueue({type:"start",...y!=null?{messageMetadata:y}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&h.enqueue({type:"finish",finishReason:p.finishReason,...y!=null?{messageMetadata:y}:{}});break}case"abort":{h.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const m=w;throw new Error(`Unknown chunk type: ${m}`)}}y!=null&&w!=="start"&&w!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:y})}}));return Lo(ek({stream:g,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){tk({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){H5({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...c}={}){return J5({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return B5({textStream:this.textStream,...e})}};ko({prefix:"aiobj",size:24}),ko({prefix:"aiobj",size:24});let xl;xl=globalThis.crypto;async function ck(e){return(await xl).getRandomValues(new Uint8Array(e))}async function uk(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await ck(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function dk(e){return await uk(e)}async function pk(e){const t=await(await xl).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function F0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await dk(e),r=await pk(t);return{code_verifier:t,code_challenge:r}}var fk="AI_MCPClientError",V0=`vercel.ai.error.${fk}`,hk=Symbol.for(V0),Z0,B0,ze=class extends(B0=he,Z0=hk,B0){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[Z0]=!0,this.data=n,this.code=o}static isInstance(e){return he.hasMarker(e,V0)}},Hn="2025-06-18",mk=[Hn,"2025-03-26","2024-11-05"],gk=ie(me(d(),Me())),yk=nt({name:d(),version:d()}),zs=nt({_meta:ie(T({}).loose())}),Sr=zs,H0=T({method:d(),params:ie(zs)}),J0=T({applyDefaults:ie(fe())}).loose(),_k=nt({experimental:ie(T({}).loose()),logging:ie(T({}).loose()),prompts:ie(nt({listChanged:ie(fe())})),resources:ie(nt({subscribe:ie(fe()),listChanged:ie(fe())})),tools:ie(nt({listChanged:ie(fe())})),elicitation:ie(J0)});T({elicitation:ie(J0)}).loose();var vk=Sr.extend({protocolVersion:d(),capabilities:_k,serverInfo:yk,instructions:ie(d())}),El=Sr.extend({nextCursor:ie(d())}),wk=T({name:d(),title:ie(d()),description:ie(d()),inputSchema:T({type:P("object"),properties:ie(T({}).loose())}).loose(),outputSchema:ie(T({}).loose()),annotations:ie(T({title:ie(d())}).loose()),_meta:gk}).loose(),bk=El.extend({tools:q(wk)}),G0=T({type:P("text"),text:d()}).loose(),W0=T({type:P("image"),data:gp(),mimeType:d()}).loose(),kk=T({uri:d(),name:d(),title:ie(d()),description:ie(d()),mimeType:ie(d()),size:ie(j())}).loose(),Ck=El.extend({resources:q(kk)}),K0=T({uri:d(),name:ie(d()),title:ie(d()),mimeType:ie(d())}).loose(),Y0=K0.extend({text:d()}),Q0=K0.extend({blob:gp()}),X0=T({type:P("resource"),resource:oe([Y0,Q0])}).loose(),Tk=Sr.extend({content:q(oe([G0,W0,X0])),structuredContent:ie(Me()),isError:fe().default(!1).optional()}).or(Sr.extend({toolResult:Me()})),Sk=T({uriTemplate:d(),name:d(),title:ie(d()),description:ie(d()),mimeType:ie(d())}).loose(),Ik=Sr.extend({resourceTemplates:q(Sk)}),xk=Sr.extend({contents:q(oe([Y0,Q0]))}),Ek=T({name:d(),description:ie(d()),required:ie(fe())}).loose(),$k=T({name:d(),title:ie(d()),description:ie(d()),arguments:ie(q(Ek))}).loose(),Rk=El.extend({prompts:q($k)}),Pk=T({role:oe([P("user"),P("assistant")]),content:oe([G0,W0,X0])}).loose(),Mk=Sr.extend({description:ie(d()),messages:q(Pk)}),Nk=zs.extend({message:d(),requestedSchema:Me()}),em=H0.extend({method:P("elicitation/create"),params:Nk}),Ok=Sr.extend({action:oe([P("accept"),P("decline"),P("cancel")]),content:ie(me(d(),Me()))}),Fs="2.0",Ak=T({jsonrpc:P(Fs),id:oe([d(),j().int()])}).merge(H0).strict(),qk=T({jsonrpc:P(Fs),id:oe([d(),j().int()]),result:Sr}).strict(),Lk=T({jsonrpc:P(Fs),id:oe([d(),j().int()]),error:T({code:j().int(),message:d(),data:ie(Me())})}).strict(),jk=T({jsonrpc:P(Fs)}).merge(T({method:d(),params:ie(zs)})).strict(),jo=oe([Ak,jk,qk,Lk]),tm=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",rm=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:j().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),qt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ip.custom,message:"URL must be parseable",fatal:!0}),Sd}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Uk=T({resource:d().url(),authorization_servers:q(qt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:fe().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:fe().optional()}).passthrough(),nm=T({issuer:d(),authorization_endpoint:qt,token_endpoint:qt,registration_endpoint:qt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),code_challenge_methods_supported:q(d()),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional()}).passthrough(),Dk=T({issuer:d(),authorization_endpoint:qt,token_endpoint:qt,userinfo_endpoint:qt.optional(),jwks_uri:qt,registration_endpoint:qt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),claims_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional()}).passthrough(),zk=Dk.merge(nm.pick({code_challenge_methods_supported:!0})),Fk=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),Vk=T({redirect_uris:q(qt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:qt.optional(),logo_uri:qt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:qt.optional(),policy_uri:d().optional(),jwks_uri:qt.optional(),jwks:ft().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),Zk=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),Bk=Vk.merge(Fk),Hk="AI_MCPClientOAuthError",om=`vercel.ai.error.${Hk}`,Jk=Symbol.for(om),sm,am,Uo=class extends(am=he,sm=Jk,am){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[sm]=!0}static isInstance(e){return he.hasMarker(e,om)}},Jn=class extends Uo{};Jn.errorCode="server_error";var Vs=class extends Uo{};Vs.errorCode="invalid_client";var Zs=class extends Uo{};Zs.errorCode="invalid_grant";var Bs=class extends Uo{};Bs.errorCode="unauthorized_client";var Gk={[Jn.errorCode]:Jn,[Vs.errorCode]:Vs,[Zs.errorCode]:Zs,[Bs.errorCode]:Bs};function Wk(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Kk({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var Hs=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Js(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const s=/resource_metadata="([^"]*)"/,a=r.match(s);if(a)try{return new URL(a[1])}catch{return}}function Yk(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function $l(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?$l(e,void 0,r):void 0;throw n}}async function im(e,t,r=fetch){return await $l(e,{"MCP-Protocol-Version":t},r)}function Qk(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Xk(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:Hn;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=Yk(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await im(l,i,r);if(!n?.metadataUrl&&Qk(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await im(u,i,r)}return c}async function eC(e,t,r=fetch){const n=await Xk(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Uk.parse(await n.json())}function tC(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function rC(e,{fetchFn:t=fetch,protocolVersion:r=Hn}={}){var n;const o={"MCP-Protocol-Version":r},s=tC(e);for(const{url:a,type:i}of s){const l=await $l(a,o,t);if(l){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 nm.parse(await l.json());{const c=zk.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function nC(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){const i="code",l="S256";let c;if(t){if(c=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 c=new URL("/authorize",e);const u=await F0(),g=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:g}}function lm(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function cm(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":oC(o,s,r);return;case"client_secret_post":sC(o,s,n);return;case"none":aC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function oC(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function sC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function aC(e,t){t.set("client_id",e)}async function Rl(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=Zk.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=Gk[o]||Jn;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Jn({message:o})}}async function iC(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",g=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(p,h,e,t);else{const w=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],m=lm(r,w);cm(m,r,p,h)}a&&h.set("resource",a.href);const y=await(l??fetch)(g,{method:"POST",headers:p,body:h});if(!y.ok)throw await Rl(y);return rm.parse(await y.json())}async function lC(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=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 c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),g=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,g,e,t);else{const h=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],y=lm(r,h);cm(y,r,u,g)}o&&g.set("resource",o.href);const p=await(a??fetch)(c,{method:"POST",headers:u,body:g});if(!p.ok)throw await Rl(p);return rm.parse({refresh_token:n,...await p.json()})}async function cC(e,{metadata:t,clientMetadata:r,fetchFn:n}){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(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Rl(s);return Bk.parse(await s.json())}async function Gs(e,t){var r,n;try{return await Pl(e,t)}catch(o){if(o instanceof Vs||o instanceof Bs)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Pl(e,t);if(o instanceof Zs)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Pl(e,t);throw o}}async function uC(e,t,r){const n=Wk(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Kk({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function Pl(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await eC(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await uC(t,e,a),c=await rC(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==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 w=await cC(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(w),u=w}if(r!==void 0){const w=await e.codeVerifier(),m=await iC(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:w,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}const g=await e.tokens();if(g?.refresh_token)try{const w=await lC(i,{metadata:c,clientInformation:u,refreshToken:g.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Uo)||w instanceof Jn))throw w}const p=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:y}=await nC(i,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(h),"REDIRECT"}var dC=class{constructor({url:e,headers:t,authProvider:r}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Hn};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return Br(t,`ai-sdk/${tm}`,Co())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Js(u);try{if(await Gs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new Hs;return(s=this.onerror)==null||s.call(this,w),t(w)}}catch(y){return(a=this.onerror)==null||a.call(this,y),t(y)}return r(!0)}if(!u.ok||!u.body){let y=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(y+=". This server does not support SSE transport. Try using `http` transport instead");const w=new ze({message:y});return(i=this.onerror)==null||i.call(this,w),t(w)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Un).getReader(),h=async()=>{var y,w,m;try{for(;;){const{done:b,value:_}=await p.read();if(b){if(this.connected)throw this.connected=!1,new ze({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:f,data:C}=_;if(f==="endpoint"){if(this.endpoint=new URL(C,this.url),this.endpoint.origin!==this.url.origin)throw new ze({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(f==="message")try{const k=jo.parse(JSON.parse(C));(y=this.onmessage)==null||y.call(this,k)}catch(k){const v=new ze({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(w=this.onerror)==null||w.call(this,v)}}}catch(b){if(b instanceof Error&&b.name==="AbortError")return;(m=this.onerror)==null||m.call(this,b),t(b)}};this.sseConnection={close:()=>p.cancel()},h()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new ze({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},g=await fetch(t,u);if(g.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Js(g);try{if(await Gs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Hs;(s=this.onerror)==null||s.call(this,h);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!g.ok){const p=await g.text().catch(()=>null),h=new ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${g.status}): ${p}`});(i=this.onerror)==null||i.call(this,h);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},pC=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":Hn};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return Br(t,`ai-sdk/${tm}`,Co())}async start(){if(this.abortController)throw new ze({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,a,i,l,c;try{const g={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},p=await fetch(this.url,g),h=p.headers.get("mcp-session-id");if(h&&(this.sessionId=h),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Js(p);try{if(await Gs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Hs}catch(b){throw(o=this.onerror)==null||o.call(this,b),b}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const b=await p.text().catch(()=>null);let _=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${b}`;p.status===404&&(_+=". This server does not support HTTP transport. Try using `sse` transport instead");const f=new ze({message:_});throw(s=this.onerror)==null||s.call(this,f),f}if(!("id"in e))return;const w=p.headers.get("content-type")||"";if(w.includes("application/json")){const b=await p.json(),_=Array.isArray(b)?b.map(f=>jo.parse(f)):[jo.parse(b)];for(const f of _)(a=this.onmessage)==null||a.call(this,f);return}if(w.includes("text/event-stream")){if(!p.body){const C=new ze({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,C),C}const _=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Un).getReader();(async()=>{var C,k,v;try{for(;;){const{done:S,value:$}=await _.read();if(S)return;const{event:E,data:D}=$;if(E==="message")try{const M=jo.parse(JSON.parse(D));(C=this.onmessage)==null||C.call(this,M)}catch(M){const N=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:M});(k=this.onerror)==null||k.call(this,N)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(v=this.onerror)==null||v.call(this,S)}})();return}const m=new ze({message:`MCP HTTP Transport Error: Unexpected content type: ${w}`});throw(l=this.onerror)==null||l.call(this,m),m}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new ze({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await fetch(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Js(c);try{if(await Gs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new Hs;(n=this.onerror)==null||n.call(this,w);return}}catch(y){(o=this.onerror)==null||o.call(this,y);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const y=new ze({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,y);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Un).getReader(),h=async()=>{var y,w,m,b;try{for(;;){const{done:_,value:f}=await p.read();if(_)return;const{event:C,data:k,id:v}=f;if(v&&(this.lastInboundEventId=v),C==="message")try{const S=jo.parse(JSON.parse(k));(y=this.onmessage)==null||y.call(this,S)}catch(S){const $=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(w=this.onerror)==null||w.call(this,$)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(m=this.onerror)==null||m.call(this,_),(b=this.abortController)!=null&&b.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,h()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function fC(e){switch(e.type){case"sse":return new dC(e);case"http":return new pC(e);default:throw new ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function hC(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var mC="1.0.0";function um({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function gC(e){const t=new yC(e);return await t.init(),t}var yC=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=mC,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},hC(e)?this.transport=e:this.transport=fC(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new ze({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:Hn,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:vk});if(e===void 0)throw new ze({message:"Server sent invalid initialize result"});if(!mk.includes(e.protocolVersion))throw new ze({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 ze({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new ze({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new ze({message:"Server does not support prompts"});break;default:throw new ze({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new ze({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s?.aborted)return o(new ze({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const g=new ze({message:"Failed to parse server response",cause:u});o(g)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:bk,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:Tk,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:Ck,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:xk,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:Ik,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:Rk,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:Mk,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:s,title:a,description:i,inputSchema:l,annotations:c,_meta:u}of e.tools){const g=a??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,h=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,y=async(m,b)=>{var _;(_=b?.abortSignal)==null||_.throwIfAborted();const f=await p.callTool({name:s,args:m,options:b});return h!=null?p.extractStructuredContent(f,h,s):f},w=t==="automatic"?gf({description:i,title:g,inputSchema:Zn({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:y,toModelOutput:um}):{description:i,title:g,inputSchema:t[s].inputSchema,...h!=null?{outputSchema:h}:{},execute:y,toModelOutput:um};o[s]={...w,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await Bt({value:e.structuredContent,schema:fn(t)});if(!n.success)throw new ze({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await Ht({text:n.text,schema:t});if(!o.success)throw new ze({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new ze({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==em)throw new ze({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=em.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=Ok.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new ze({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),r=this.responseHandlers.get(t);if(r===void 0)throw new ze({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new ze({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function Ws(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function dm(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Ws(t.headers),...Ws(n.headers)}:t.headers};return e(r,o)}:e}const Ks="2025-11-25",_C=[Ks,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],_n="io.modelcontextprotocol/related-task",Ys="2.0",yt=Tp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),pm=oe([d(),j().int()]),fm=d();nt({ttl:oe([j(),Ts()]).optional(),pollInterval:j().optional()});const vC=T({ttl:j().optional()}),wC=T({taskId:d()}),Ml=nt({progressToken:pm.optional(),[_n]:wC.optional()}),Ft=T({_meta:Ml.optional()}),Do=Ft.extend({task:vC.optional()}),bC=e=>Do.safeParse(e).success,_t=T({method:d(),params:Ft.loose().optional()}),Jt=T({_meta:Ml.optional()}),Gt=T({method:d(),params:Jt.loose().optional()}),vt=nt({_meta:Ml.optional()}),Qs=oe([d(),j().int()]),hm=T({jsonrpc:P(Ys),id:Qs,..._t.shape}).strict(),Nl=e=>hm.safeParse(e).success,mm=T({jsonrpc:P(Ys),...Gt.shape}).strict(),kC=e=>mm.safeParse(e).success,Ol=T({jsonrpc:P(Ys),id:Qs,result:vt}).strict(),zo=e=>Ol.safeParse(e).success;var $e;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})($e||($e={}));const Al=T({jsonrpc:P(Ys),id:Qs.optional(),error:T({code:j().int(),message:d(),data:Me().optional()})}).strict(),CC=e=>Al.safeParse(e).success,vn=oe([hm,mm,Ol,Al]);oe([Ol,Al]);const wn=vt.strict(),TC=Jt.extend({requestId:Qs.optional(),reason:d().optional()}),ql=Gt.extend({method:P("notifications/cancelled"),params:TC}),SC=T({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:Se(["light","dark"]).optional()}),Fo=T({icons:q(SC).optional()}),Gn=T({name:d(),title:d().optional()}),gm=Gn.extend({...Gn.shape,...Fo.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),IC=Pi(T({applyDefaults:fe().optional()}),me(d(),Me())),xC=Sp(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Pi(T({form:IC.optional(),url:yt.optional()}),me(d(),Me()).optional())),EC=nt({list:yt.optional(),cancel:yt.optional(),requests:nt({sampling:nt({createMessage:yt.optional()}).optional(),elicitation:nt({create:yt.optional()}).optional()}).optional()}),$C=nt({list:yt.optional(),cancel:yt.optional(),requests:nt({tools:nt({call:yt.optional()}).optional()}).optional()}),RC=T({experimental:me(d(),yt).optional(),sampling:T({context:yt.optional(),tools:yt.optional()}).optional(),elicitation:xC.optional(),roots:T({listChanged:fe().optional()}).optional(),tasks:EC.optional()}),PC=Ft.extend({protocolVersion:d(),capabilities:RC,clientInfo:gm}),MC=_t.extend({method:P("initialize"),params:PC}),NC=T({experimental:me(d(),yt).optional(),logging:yt.optional(),completions:yt.optional(),prompts:T({listChanged:fe().optional()}).optional(),resources:T({subscribe:fe().optional(),listChanged:fe().optional()}).optional(),tools:T({listChanged:fe().optional()}).optional(),tasks:$C.optional()}),ym=vt.extend({protocolVersion:d(),capabilities:NC,serverInfo:gm,instructions:d().optional()}),_m=Gt.extend({method:P("notifications/initialized"),params:Jt.optional()}),OC=e=>_m.safeParse(e).success,Ll=_t.extend({method:P("ping"),params:Ft.optional()}),AC=T({progress:j(),total:ie(j()),message:ie(d())}),qC=T({...Jt.shape,...AC.shape,progressToken:pm}),jl=Gt.extend({method:P("notifications/progress"),params:qC}),LC=Ft.extend({cursor:fm.optional()}),Vo=_t.extend({params:LC.optional()}),Zo=vt.extend({nextCursor:fm.optional()}),jC=Se(["working","input_required","completed","failed","cancelled"]),Bo=T({taskId:d(),status:jC,ttl:oe([j(),Ts()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ie(j()),statusMessage:ie(d())}),Ho=vt.extend({task:Bo}),UC=Jt.merge(Bo),Xs=Gt.extend({method:P("notifications/tasks/status"),params:UC}),Ul=_t.extend({method:P("tasks/get"),params:Ft.extend({taskId:d()})}),Dl=vt.merge(Bo),zl=_t.extend({method:P("tasks/result"),params:Ft.extend({taskId:d()})});vt.loose();const Fl=Vo.extend({method:P("tasks/list")}),Vl=Zo.extend({tasks:q(Bo)}),Zl=_t.extend({method:P("tasks/cancel"),params:Ft.extend({taskId:d()})}),DC=vt.merge(Bo),vm=T({uri:d(),mimeType:ie(d()),_meta:me(d(),Me()).optional()}),wm=vm.extend({text:d()}),Bl=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),bm=vm.extend({blob:Bl}),Jo=Se(["user","assistant"]),Wn=T({audience:q(Jo).optional(),priority:j().min(0).max(1).optional(),lastModified:up({offset:!0}).optional()}),km=T({...Gn.shape,...Fo.shape,uri:d(),description:ie(d()),mimeType:ie(d()),annotations:Wn.optional(),_meta:ie(nt({}))}),zC=T({...Gn.shape,...Fo.shape,uriTemplate:d(),description:ie(d()),mimeType:ie(d()),annotations:Wn.optional(),_meta:ie(nt({}))}),FC=Vo.extend({method:P("resources/list")}),Cm=Zo.extend({resources:q(km)}),VC=Vo.extend({method:P("resources/templates/list")}),Tm=Zo.extend({resourceTemplates:q(zC)}),Hl=Ft.extend({uri:d()}),ZC=Hl,BC=_t.extend({method:P("resources/read"),params:ZC}),Sm=vt.extend({contents:q(oe([wm,bm]))}),Jl=Gt.extend({method:P("notifications/resources/list_changed"),params:Jt.optional()}),HC=Hl,JC=_t.extend({method:P("resources/subscribe"),params:HC}),GC=Hl,WC=_t.extend({method:P("resources/unsubscribe"),params:GC}),KC=Jt.extend({uri:d()}),Im=Gt.extend({method:P("notifications/resources/updated"),params:KC}),YC=T({name:d(),description:ie(d()),required:ie(fe())}),QC=T({...Gn.shape,...Fo.shape,description:ie(d()),arguments:ie(q(YC)),_meta:ie(nt({}))}),XC=Vo.extend({method:P("prompts/list")}),xm=Zo.extend({prompts:q(QC)}),eT=Ft.extend({name:d(),arguments:me(d(),d()).optional()}),tT=_t.extend({method:P("prompts/get"),params:eT}),Gl=T({type:P("text"),text:d(),annotations:Wn.optional(),_meta:me(d(),Me()).optional()}),Wl=T({type:P("image"),data:Bl,mimeType:d(),annotations:Wn.optional(),_meta:me(d(),Me()).optional()}),Kl=T({type:P("audio"),data:Bl,mimeType:d(),annotations:Wn.optional(),_meta:me(d(),Me()).optional()}),rT=T({type:P("tool_use"),name:d(),id:d(),input:me(d(),Me()),_meta:me(d(),Me()).optional()}),nT=T({type:P("resource"),resource:oe([wm,bm]),annotations:Wn.optional(),_meta:me(d(),Me()).optional()}),oT=km.extend({type:P("resource_link")}),Yl=oe([Gl,Wl,Kl,oT,nT]),sT=T({role:Jo,content:Yl}),Em=vt.extend({description:d().optional(),messages:q(sT)}),Ql=Gt.extend({method:P("notifications/prompts/list_changed"),params:Jt.optional()}),aT=T({title:d().optional(),readOnlyHint:fe().optional(),destructiveHint:fe().optional(),idempotentHint:fe().optional(),openWorldHint:fe().optional()}),iT=T({taskSupport:Se(["required","optional","forbidden"]).optional()}),$m=T({...Gn.shape,...Fo.shape,description:d().optional(),inputSchema:T({type:P("object"),properties:me(d(),yt).optional(),required:q(d()).optional()}).catchall(Me()),outputSchema:T({type:P("object"),properties:me(d(),yt).optional(),required:q(d()).optional()}).catchall(Me()).optional(),annotations:aT.optional(),execution:iT.optional(),_meta:me(d(),Me()).optional()}),lT=Vo.extend({method:P("tools/list")}),Rm=Zo.extend({tools:q($m)}),Go=vt.extend({content:q(Yl).default([]),structuredContent:me(d(),Me()).optional(),isError:fe().optional()});Go.or(vt.extend({toolResult:Me()}));const cT=Do.extend({name:d(),arguments:me(d(),Me()).optional()}),uT=_t.extend({method:P("tools/call"),params:cT}),Xl=Gt.extend({method:P("notifications/tools/list_changed"),params:Jt.optional()}),dT=T({autoRefresh:fe().default(!0),debounceMs:j().int().nonnegative().default(300)}),Pm=Se(["debug","info","notice","warning","error","critical","alert","emergency"]),pT=Ft.extend({level:Pm}),fT=_t.extend({method:P("logging/setLevel"),params:pT}),hT=Jt.extend({level:Pm,logger:d().optional(),data:Me()}),Mm=Gt.extend({method:P("notifications/message"),params:hT}),mT=T({name:d().optional()}),gT=T({hints:q(mT).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),yT=T({mode:Se(["auto","required","none"]).optional()}),_T=T({type:P("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(Yl).default([]),structuredContent:T({}).loose().optional(),isError:fe().optional(),_meta:me(d(),Me()).optional()}),vT=Qe("type",[Gl,Wl,Kl]),ea=Qe("type",[Gl,Wl,Kl,rT,_T]),wT=T({role:Jo,content:oe([ea,q(ea)]),_meta:me(d(),Me()).optional()}),bT=Do.extend({messages:q(wT),modelPreferences:gT.optional(),systemPrompt:d().optional(),includeContext:Se(["none","thisServer","allServers"]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:q(d()).optional(),metadata:yt.optional(),tools:q($m).optional(),toolChoice:yT.optional()}),ec=_t.extend({method:P("sampling/createMessage"),params:bT}),tc=vt.extend({model:d(),stopReason:ie(Se(["endTurn","stopSequence","maxTokens"]).or(d())),role:Jo,content:vT}),Nm=vt.extend({model:d(),stopReason:ie(Se(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Jo,content:oe([ea,q(ea)])}),kT=T({type:P("boolean"),title:d().optional(),description:d().optional(),default:fe().optional()}),CT=T({type:P("string"),title:d().optional(),description:d().optional(),minLength:j().optional(),maxLength:j().optional(),format:Se(["email","uri","date","date-time"]).optional(),default:d().optional()}),TT=T({type:Se(["number","integer"]),title:d().optional(),description:d().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),ST=T({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),IT=T({type:P("string"),title:d().optional(),description:d().optional(),oneOf:q(T({const:d(),title:d()})),default:d().optional()}),xT=T({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),ET=oe([ST,IT]),$T=T({type:P("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:T({type:P("string"),enum:q(d())}),default:q(d()).optional()}),RT=T({type:P("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:T({anyOf:q(T({const:d(),title:d()}))}),default:q(d()).optional()}),PT=oe([$T,RT]),MT=oe([xT,ET,PT]),NT=oe([MT,kT,CT,TT]),OT=Do.extend({mode:P("form").optional(),message:d(),requestedSchema:T({type:P("object"),properties:me(d(),NT),required:q(d()).optional()})}),AT=Do.extend({mode:P("url"),message:d(),elicitationId:d(),url:d().url()}),qT=oe([OT,AT]),rc=_t.extend({method:P("elicitation/create"),params:qT}),LT=Jt.extend({elicitationId:d()}),jT=Gt.extend({method:P("notifications/elicitation/complete"),params:LT}),nc=vt.extend({action:Se(["accept","decline","cancel"]),content:Sp(e=>e===null?void 0:e,me(d(),oe([d(),j(),fe(),q(d())])).optional())}),UT=T({type:P("ref/resource"),uri:d()}),DT=T({type:P("ref/prompt"),name:d()}),zT=Ft.extend({ref:oe([DT,UT]),argument:T({name:d(),value:d()}),context:T({arguments:me(d(),d()).optional()}).optional()}),FT=_t.extend({method:P("completion/complete"),params:zT}),Om=vt.extend({completion:nt({values:q(d()).max(100),total:ie(j().int()),hasMore:ie(fe())})}),VT=T({uri:d().startsWith("file://"),name:d().optional(),_meta:me(d(),Me()).optional()}),Am=_t.extend({method:P("roots/list"),params:Ft.optional()}),qm=vt.extend({roots:q(VT)}),ZT=Gt.extend({method:P("notifications/roots/list_changed"),params:Jt.optional()});oe([Ll,MC,FT,fT,tT,XC,FC,VC,BC,JC,WC,uT,lT,Ul,zl,Fl,Zl]),oe([ql,jl,_m,ZT,Xs]),oe([wn,tc,Nm,nc,qm,Dl,Vl,Ho]),oe([Ll,ec,rc,Am,Ul,zl,Fl,Zl]),oe([ql,jl,Mm,Im,Jl,Xl,Ql,Xs,jT]),oe([wn,ym,Om,Em,xm,Cm,Tm,Sm,Go,Rm,Dl,Vl,Ho]);class ke extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===$e.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new BT(o.elicitations,r)}return new ke(t,r,n)}}class BT extends ke{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super($e.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const wt=Xw().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ip.custom,message:"URL must be parseable",fatal:!0}),Sd}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),HT=nt({resource:d().url(),authorization_servers:q(wt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:fe().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:fe().optional()}),Lm=nt({issuer:d(),authorization_endpoint:wt,token_endpoint:wt,registration_endpoint:wt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),service_documentation:wt.optional(),revocation_endpoint:wt.optional(),revocation_endpoint_auth_methods_supported:q(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:q(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(d()).optional(),code_challenge_methods_supported:q(d()).optional(),client_id_metadata_document_supported:fe().optional()}),JT=nt({issuer:d(),authorization_endpoint:wt,token_endpoint:wt,userinfo_endpoint:wt.optional(),jwks_uri:wt,registration_endpoint:wt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),acr_values_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),id_token_encryption_alg_values_supported:q(d()).optional(),id_token_encryption_enc_values_supported:q(d()).optional(),userinfo_signing_alg_values_supported:q(d()).optional(),userinfo_encryption_alg_values_supported:q(d()).optional(),userinfo_encryption_enc_values_supported:q(d()).optional(),request_object_signing_alg_values_supported:q(d()).optional(),request_object_encryption_alg_values_supported:q(d()).optional(),request_object_encryption_enc_values_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),display_values_supported:q(d()).optional(),claim_types_supported:q(d()).optional(),claims_supported:q(d()).optional(),service_documentation:d().optional(),claims_locales_supported:q(d()).optional(),ui_locales_supported:q(d()).optional(),claims_parameter_supported:fe().optional(),request_parameter_supported:fe().optional(),request_uri_parameter_supported:fe().optional(),require_request_uri_registration:fe().optional(),op_policy_uri:wt.optional(),op_tos_uri:wt.optional(),client_id_metadata_document_supported:fe().optional()}),GT=T({...JT.shape,...Lm.pick({code_challenge_methods_supported:!0}).shape}),WT=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:xp().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),KT=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),jm=wt.optional().or(P("").transform(()=>{})),YT=T({redirect_uris:q(wt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:wt.optional(),logo_uri:jm,scope:d().optional(),contacts:q(d()).optional(),tos_uri:jm,policy_uri:d().optional(),jwks_uri:wt.optional(),jwks:ft().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),QT=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),XT=YT.merge(QT);T({error:d(),error_description:d().optional()}).strip(),T({token:d(),token_type_hint:d().optional()}).strip();function e8(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function t8({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class ht extends Error{constructor(t,r){super(t),this.errorUri=r,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 oc extends ht{}oc.errorCode="invalid_request";class ta extends ht{}ta.errorCode="invalid_client";class ra extends ht{}ra.errorCode="invalid_grant";class na extends ht{}na.errorCode="unauthorized_client";class sc extends ht{}sc.errorCode="unsupported_grant_type";class ac extends ht{}ac.errorCode="invalid_scope";class ic extends ht{}ic.errorCode="access_denied";class Kn extends ht{}Kn.errorCode="server_error";class lc extends ht{}lc.errorCode="temporarily_unavailable";class cc extends ht{}cc.errorCode="unsupported_response_type";class uc extends ht{}uc.errorCode="unsupported_token_type";class dc extends ht{}dc.errorCode="invalid_token";class pc extends ht{}pc.errorCode="method_not_allowed";class fc extends ht{}fc.errorCode="too_many_requests";class oa extends ht{}oa.errorCode="invalid_client_metadata";class hc extends ht{}hc.errorCode="insufficient_scope";class mc extends ht{}mc.errorCode="invalid_target";const r8={[oc.errorCode]:oc,[ta.errorCode]:ta,[ra.errorCode]:ra,[na.errorCode]:na,[sc.errorCode]:sc,[ac.errorCode]:ac,[ic.errorCode]:ic,[Kn.errorCode]:Kn,[lc.errorCode]:lc,[cc.errorCode]:cc,[uc.errorCode]:uc,[dc.errorCode]:dc,[pc.errorCode]:pc,[fc.errorCode]:fc,[oa.errorCode]:oa,[hc.errorCode]:hc,[mc.errorCode]:mc};class Wt extends Error{constructor(t){super(t??"Unauthorized")}}function n8(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const gc="code",yc="S256";function o8(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&n8(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function s8(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":a8(o,s,r);return;case"client_secret_post":i8(o,s,n);return;case"none":l8(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function a8(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function i8(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function l8(e,t){t.set("client_id",e)}async function Um(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=KT.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=r8[o]||Kn;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Kn(o)}}async function bn(e,t){try{return await _c(e,t)}catch(r){if(r instanceof ta||r instanceof na)return await e.invalidateCredentials?.("all"),await _c(e,t);if(r instanceof ra)return await e.invalidateCredentials?.("tokens"),await _c(e,t);throw r}}async function _c(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await d8(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const l=await u8(t,e,a),c=await g8(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const m=c?.client_id_metadata_document_supported===!0,b=e.clientMetadataUrl;if(b&&!c8(b))throw new oa(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${b}`);if(m&&b)u={client_id:b},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const f=await b8(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(f),u=f}}const g=!e.redirectUrl;if(r!==void 0||g){const m=await w8(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const m=await v8(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}catch(m){if(!(!(m instanceof ht)||m instanceof Kn))throw m}const h=e.state?await e.state():void 0,{authorizationUrl:y,codeVerifier:w}=await y8(i,{metadata:c,clientInformation:u,state:h,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(w),await e.redirectToAuthorization(y),"REDIRECT"}function c8(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function u8(e,t,r){const n=e8(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!t8({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function sa(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=vc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=vc(e,"scope")||void 0,i=vc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function vc(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function d8(e,t,r=fetch){const n=await h8(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return HT.parse(await n.json())}async function wc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?wc(e,void 0,r):void 0;throw n}}function p8(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Dm(e,t,r=fetch){return await wc(e,{"MCP-Protocol-Version":t},r)}function f8(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function h8(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??Ks;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=p8(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await Dm(a,s,r);if(!n?.metadataUrl&&f8(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await Dm(l,s,r)}return i}function m8(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function g8(e,{fetchFn:t=fetch,protocolVersion:r=Ks}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=m8(e);for(const{url:s,type:a}of o){const i=await wc(s,n,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?Lm.parse(await i.json()):GT.parse(await i.json())}}}async function y8(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(gc))throw new Error(`Incompatible auth server: does not support response type ${gc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(yc))throw new Error(`Incompatible auth server: does not support code challenge method ${yc}`)}else i=new URL("/authorize",e);const l=await F0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",gc),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",yc),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function _8(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function zm(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,i,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],g=o8(n,u);s8(g,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await Um(c);return WT.parse(await c.json())}async function v8(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await zm(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function w8(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();i=_8(o,c,e.redirectUrl)}const l=await e.clientInformation();return zm(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function b8(e,{metadata:t,clientMetadata:r,fetchFn:n}){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(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Um(s);return XT.parse(await s.json())}const k8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Yn extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class aa{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=dm(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??k8}async _authThenStart(){if(!this._authProvider)throw new Wt("No auth provider");let t;try{t=await bn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Wt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=Ws(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){const{resumptionToken:r}=t;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Yn(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Un({onRetry:h=>{this._serverRetryMs=h}})).getReader();for(;;){const{value:h,done:y}=await u.read();if(y)break;if(h.id&&(a=h.id,i=!0,o?.(h.id)),!!h.data&&(!h.event||h.event==="message"))try{const w=vn.parse(JSON.parse(h.data));zo(w)&&(l=!0,s!==void 0&&(w.id=s)),this.onmessage?.(w)}catch(w){this.onerror?.(w)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(h){this.onerror?.(new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}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 Wt("No auth provider");if(await bn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Wt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Nl(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),l=i.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!i.ok){const p=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Yn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:h,scope:y}=sa(i);if(this._resourceMetadataUrl=h,this._scope=y,await bn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Wt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:h,scope:y,error:w}=sa(i);if(w==="insufficient_scope"){const m=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===m)throw new Yn(403,"Server returned 403 after trying upscoping");if(y&&(this._scope=y),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=m??void 0,await bn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Wt;return this.send(t)}}throw new Yn(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),OC(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,g=i.headers.get("content-type");if(u)if(g?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(g?.includes("application/json")){const p=await i.json(),h=Array.isArray(p)?p.map(y=>vn.parse(y)):[vn.parse(p)];for(const y of h)this.onmessage?.(y)}else throw await i.body?.cancel(),new Yn(-1,`Unexpected content type: ${g}`);else await i.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Yn(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class ia{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new ia,r=new ia;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}var bc=T({error:T({message:d(),type:d().nullish(),param:ft().nullish(),code:oe([d(),j()]).nullish()})}),rr=Hr({errorSchema:bc,errorToMessage:e=>e.error.message});function Fm(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=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"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function Vm(e){var t,r,n,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const i=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:i,noCache:i-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function C8({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map((i,l)=>{var c,u,g;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const p=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${p};base64,${Vn(i.data)}`,detail:(u=(c=i.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new dr({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Vn(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Vn(i.data),format:"mp3"}};default:throw new dr({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new dr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(g=i.filename)!=null?g:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Vn(i.data)}`}}}else throw new dr({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const l=[];for(const c of a)switch(c.type){case"text":{i+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}n.push({role:"assistant",content:i,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const i of a){if(i.type==="tool-approval-response")continue;const l=i.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:i.toolCallId,content:c})}break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:o}}function kc({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function Zm(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var T8=Te(()=>be(T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({message:T({role:P("assistant").nullish(),content:d().nullish(),tool_calls:q(T({id:d().nullish(),type:P("function"),function:T({name:d(),arguments:d()})})).nullish(),annotations:q(T({type:P("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}),index:j(),logprobs:T({content:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),S8=Te(()=>be(oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({delta:T({role:Se(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(T({index:j(),id:d().nullish(),type:P("function").nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(T({type:P("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:j()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),bc]))),I8=Te(()=>be(T({logitBias:me(xp(),j()).optional(),logprobs:oe([fe(),j()]).optional(),parallelToolCalls:fe().optional(),user:d().optional(),reasoningEffort:Se(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:fe().optional(),metadata:me(d().max(64),d().max(512)).optional(),prediction:me(d(),ft()).optional(),serviceTier:Se(["auto","flex","priority","default"]).optional(),strictJsonSchema:fe().optional(),textVerbosity:Se(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:Se(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:Se(["system","developer","remove"]).optional(),forceReasoning:fe().optional()})));function x8({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new dr({functionality:`tool choice type: ${s}`})}}}var E8=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:g,providerOptions:p}){var h,y,w,m,b;const _=[],f=(h=await Cr({provider:"openai",providerOptions:p,schema:I8}))!=null?h:{},C=Fm(this.modelId),k=(y=f.forceReasoning)!=null?y:C.isReasoningModel;o!=null&&_.push({type:"unsupported",feature:"topK"});const{messages:v,warnings:S}=C8({prompt:e,systemMessageMode:(w=f.systemMessageMode)!=null?w:k?"developer":C.systemMessageMode});_.push(...S);const $=(m=f.strictJsonSchema)!=null?m:!0,E={model:this.modelId,logit_bias:f.logitBias,logprobs:f.logprobs===!0||typeof f.logprobs=="number"?!0:void 0,top_logprobs:typeof f.logprobs=="number"?f.logprobs:typeof f.logprobs=="boolean"&&f.logprobs?0:void 0,user:f.user,parallel_tool_calls:f.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:$,name:(b=l.name)!=null?b:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:f.textVerbosity,max_completion_tokens:f.maxCompletionTokens,store:f.store,metadata:f.metadata,prediction:f.prediction,reasoning_effort:f.reasoningEffort,service_tier:f.serviceTier,prompt_cache_key:f.promptCacheKey,prompt_cache_retention:f.promptCacheRetention,safety_identifier:f.safetyIdentifier,messages:v};k?((f.reasoningEffort!=="none"||!C.supportsNonReasoningParameters)&&(E.temperature!=null&&(E.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),E.top_p!=null&&(E.top_p=void 0,_.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),E.logprobs!=null&&(E.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),E.frequency_penalty!=null&&(E.frequency_penalty=void 0,_.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),E.presence_penalty!=null&&(E.presence_penalty=void 0,_.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),E.logit_bias!=null&&(E.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),E.top_logprobs!=null&&(E.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),E.max_tokens!=null&&(E.max_completion_tokens==null&&(E.max_completion_tokens=E.max_tokens),E.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&E.temperature!=null&&(E.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),f.serviceTier==="flex"&&!C.supportsFlexProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),E.service_tier=void 0),f.serviceTier==="priority"&&!C.supportsPriorityProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),E.service_tier=void 0);const{tools:D,toolChoice:M,toolWarnings:N}=x8({tools:u,toolChoice:g});return{args:{...E,tools:D,tool_choice:M},warnings:[..._,...N]}}async doGenerate(e){var t,r,n,o,s,a,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:g,rawValue:p}=await Ot({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:l,failedResponseHandler:rr,successfulResponseHandler:Dt(T8),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=g.choices[0],y=[],w=h.message.content;w!=null&&w.length>0&&y.push({type:"text",text:w});for(const _ of(t=h.message.tool_calls)!=null?t:[])y.push({type:"tool-call",toolCallId:(r=_.id)!=null?r:Et(),toolName:_.function.name,input:_.function.arguments});for(const _ of(n=h.message.annotations)!=null?n:[])y.push({type:"source",sourceType:"url",id:Et(),url:_.url_citation.url,title:_.url_citation.title});const m=(o=g.usage)==null?void 0:o.completion_tokens_details;(s=g.usage)==null||s.prompt_tokens_details;const b={openai:{}};return m?.accepted_prediction_tokens!=null&&(b.openai.acceptedPredictionTokens=m?.accepted_prediction_tokens),m?.rejected_prediction_tokens!=null&&(b.openai.rejectedPredictionTokens=m?.rejected_prediction_tokens),((a=h.logprobs)==null?void 0:a.content)!=null&&(b.openai.logprobs=h.logprobs.content),{content:y,finishReason:{unified:Zm(h.finish_reason),raw:(i=h.finish_reason)!=null?i:void 0},usage:Vm(g.usage),request:{body:l},response:{...kc(g),headers:u,body:p},warnings:c,providerMetadata:b}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Ot({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:n,failedResponseHandler:rr,successfulResponseHandler:Ms(S8),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const g={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,h){var y,w,m,b,_,f,C,k,v,S,$,E,D,M,N,O,L;if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}const K=p.value;if("error"in K){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:K.error});return}if(!c){const W=kc(K);Object.values(W).some(Boolean)&&(c=!0,h.enqueue({type:"response-metadata",...kc(K)}))}K.usage!=null&&(l=K.usage,((y=K.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens)!=null&&(g.openai.acceptedPredictionTokens=(w=K.usage.completion_tokens_details)==null?void 0:w.accepted_prediction_tokens),((m=K.usage.completion_tokens_details)==null?void 0:m.rejected_prediction_tokens)!=null&&(g.openai.rejectedPredictionTokens=(b=K.usage.completion_tokens_details)==null?void 0:b.rejected_prediction_tokens));const H=K.choices[0];if(H?.finish_reason!=null&&(i={unified:Zm(H.finish_reason),raw:H.finish_reason}),((_=H?.logprobs)==null?void 0:_.content)!=null&&(g.openai.logprobs=H.logprobs.content),H?.delta==null)return;const le=H.delta;if(le.content!=null&&(u||(h.enqueue({type:"text-start",id:"0"}),u=!0),h.enqueue({type:"text-delta",id:"0",delta:le.content})),le.tool_calls!=null)for(const W of le.tool_calls){const Ee=W.index;if(a[Ee]==null){if(W.type!=="function")throw new bi({data:W,message:"Expected 'function' type."});if(W.id==null)throw new bi({data:W,message:"Expected 'id' to be a string."});if(((f=W.function)==null?void 0:f.name)==null)throw new bi({data:W,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:W.id,toolName:W.function.name}),a[Ee]={id:W.id,type:"function",function:{name:W.function.name,arguments:(C=W.function.arguments)!=null?C:""},hasFinished:!1};const A=a[Ee];((k=A.function)==null?void 0:k.name)!=null&&((v=A.function)==null?void 0:v.arguments)!=null&&(A.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:A.id,delta:A.function.arguments}),ff(A.function.arguments)&&(h.enqueue({type:"tool-input-end",id:A.id}),h.enqueue({type:"tool-call",toolCallId:(S=A.id)!=null?S:Et(),toolName:A.function.name,input:A.function.arguments}),A.hasFinished=!0));continue}const F=a[Ee];F.hasFinished||((($=W.function)==null?void 0:$.arguments)!=null&&(F.function.arguments+=(D=(E=W.function)==null?void 0:E.arguments)!=null?D:""),h.enqueue({type:"tool-input-delta",id:F.id,delta:(M=W.function.arguments)!=null?M:""}),((N=F.function)==null?void 0:N.name)!=null&&((O=F.function)==null?void 0:O.arguments)!=null&&ff(F.function.arguments)&&(h.enqueue({type:"tool-input-end",id:F.id}),h.enqueue({type:"tool-call",toolCallId:(L=F.id)!=null?L:Et(),toolName:F.function.name,input:F.function.arguments}),F.hasFinished=!0))}if(le.annotations!=null)for(const W of le.annotations)h.enqueue({type:"source",sourceType:"url",id:Et(),url:W.url_citation.url,title:W.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:Vm(l),...g!=null?{providerMetadata:g}:{}})}})),request:{body:n},response:{headers:o}}}};function Bm(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}function $8({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
68
+ `)}})}},nm={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function d5({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new rm);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:ea(r,nm)})}function p5({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function f5(e){return e.type.startsWith("data-")}function Vl(e){return e.type.startsWith("tool-")}function h5(e){return e.type==="dynamic-tool"}function om(e){return Vl(e)||h5(e)}function sm(e){return e.type.split("-").slice(1).join("-")}function m5({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function g5({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var m,p,f,g;function v(h){const k=c.message.parts.filter(om).find(b=>b.toolCallId===h);if(k==null)throw new eo({chunkType:"tool-invocation",chunkId:h,message:`No tool invocation found for tool call ID "${h}".`});return k}function y(h){var T;const k=c.message.parts.find(x=>Vl(x)&&x.toolCallId===h.toolCallId),b=h,S=k;k!=null?(k.state=h.state,S.input=b.input,S.output=b.output,S.errorText=b.errorText,S.rawInput=b.rawInput,S.preliminary=b.preliminary,h.title!==void 0&&(S.title=h.title),S.providerExecuted=(T=b.providerExecuted)!=null?T:k.providerExecuted,b.providerMetadata!=null&&(k.callProviderMetadata=b.providerMetadata)):c.message.parts.push({type:`tool-${h.toolName}`,toolCallId:h.toolCallId,state:h.state,title:h.title,input:b.input,output:b.output,rawInput:b.rawInput,errorText:b.errorText,providerExecuted:b.providerExecuted,preliminary:b.preliminary,...b.providerMetadata!=null?{callProviderMetadata:b.providerMetadata}:{}})}function w(h){var T,k;const b=c.message.parts.find(I=>I.type==="dynamic-tool"&&I.toolCallId===h.toolCallId),S=h,x=b;b!=null?(b.state=h.state,x.toolName=h.toolName,x.input=S.input,x.output=S.output,x.errorText=S.errorText,x.rawInput=(T=S.rawInput)!=null?T:x.rawInput,x.preliminary=S.preliminary,h.title!==void 0&&(x.title=h.title),x.providerExecuted=(k=S.providerExecuted)!=null?k:b.providerExecuted,S.providerMetadata!=null&&(b.callProviderMetadata=S.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:h.toolName,toolCallId:h.toolCallId,state:h.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,providerExecuted:S.providerExecuted,title:h.title,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function _(h){if(h!=null){const T=c.message.metadata!=null?Ys(c.message.metadata,h):h;t!=null&&await St({value:T,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=T}}switch(i.type){case"text-start":{const h={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=h,c.message.parts.push(h),u();break}case"text-delta":{const h=c.activeTextParts[i.id];if(h==null)throw new eo({chunkType:"text-delta",chunkId:i.id,message:`Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});h.text+=i.delta,h.providerMetadata=(m=i.providerMetadata)!=null?m:h.providerMetadata,u();break}case"text-end":{const h=c.activeTextParts[i.id];if(h==null)throw new eo({chunkType:"text-end",chunkId:i.id,message:`Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});h.state="done",h.providerMetadata=(p=i.providerMetadata)!=null?p:h.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const h={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=h,c.message.parts.push(h),u();break}case"reasoning-delta":{const h=c.activeReasoningParts[i.id];if(h==null)throw new eo({chunkType:"reasoning-delta",chunkId:i.id,message:`Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});h.text+=i.delta,h.providerMetadata=(f=i.providerMetadata)!=null?f:h.providerMetadata,u();break}case"reasoning-end":{const h=c.activeReasoningParts[i.id];if(h==null)throw new eo({chunkType:"reasoning-end",chunkId:i.id,message:`Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});h.providerMetadata=(g=i.providerMetadata)!=null?g:h.providerMetadata,h.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const h=c.message.parts.filter(Vl);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:h.length,dynamic:i.dynamic,title:i.title},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"tool-input-delta":{const h=c.partialToolCalls[i.toolCallId];if(h==null)throw new eo({chunkType:"tool-input-delta",chunkId:i.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});h.text+=i.inputTextDelta;const{value:T}=await Zo(h.text);h.dynamic?w({toolCallId:i.toolCallId,toolName:h.toolName,state:"input-streaming",input:T,title:h.title}):y({toolCallId:i.toolCallId,toolName:h.toolName,state:"input-streaming",input:T,title:h.title}),u();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{const h=c.message.parts.filter(om).find(k=>k.toolCallId===i.toolCallId);(h!=null?h.type==="dynamic-tool":!!i.dynamic)?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-approval-request":{const h=v(i.toolCallId);h.state="approval-requested",h.approval={id:i.approvalId},u();break}case"tool-output-denied":{const h=v(i.toolCallId);h.state="output-denied",u();break}case"tool-output-available":{const h=v(i.toolCallId);h.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:h.toolName,state:"output-available",input:h.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:h.title}):y({toolCallId:i.toolCallId,toolName:sm(h),state:"output-available",input:h.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,title:h.title}),u();break}case"tool-output-error":{const h=v(i.toolCallId);h.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:h.toolName,state:"output-error",input:h.input,errorText:i.errorText,providerExecuted:i.providerExecuted,title:h.title}):y({toolCallId:i.toolCallId,toolName:sm(h),state:"output-error",input:h.input,rawInput:h.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,title:h.title}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(f5(i)){if(r?.[i.type]!=null){const k=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===i.id&&S.type===i.type),b=k>=0?k:c.message.parts.length;await St({value:i.data,schema:r[i.type],context:{field:`message.parts[${b}].data`,entityName:i.type,entityId:i.id}})}const h=i;if(h.transient){a?.(h);break}const T=h.id!=null?c.message.parts.find(k=>h.type===k.type&&h.id===k.id):void 0;T!=null?T.data=h.data:c.message.parts.push(h),a?.(h),u()}}l.enqueue(i)})}}))}function y5({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let a=t?.[t.length-1];a?.role!=="assistant"?a=void 0:e=a.id;let i=!1;const l=s.pipeThrough(new TransformStream({transform(g,v){if(g.type==="start"){const y=g;y.messageId==null&&e!=null&&(y.messageId=e)}g.type==="abort"&&(i=!0),v.enqueue(g)}}));if(n==null&&r==null)return l;const c=m5({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async g=>{await g({state:c,write:()=>{}})};let m=!1;const p=async()=>{if(m||!n)return;m=!0;const g=c.message.id===a?.id;await n({isAborted:i,isContinuation:g,responseMessage:c.message,messages:[...g?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},f=async()=>{if(!r)return;const g=c.message.id===a?.id;try{await r({isContinuation:g,responseMessage:structuredClone(c.message),messages:[...g?t.slice(0,-1):t,structuredClone(c.message)]})}catch(v){o(v)}};return g5({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(g,v){g.type==="finish-step"&&await f(),v.enqueue(g)},async cancel(){await p()},async flush(){await p()}}))}function _5({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new rm);if(s){const[i,l]=a.tee();a=i,s({stream:l})}tm({response:e,status:t,statusText:r,headers:Object.fromEntries(ea(n,nm).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Bo(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var a;if(!n){n=!0;try{s&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:a}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function v5({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function am(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function w5(){let e=[],t=null,r=!1,n=am();const o=()=>{r=!0,n.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=am(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length===0&&r?t?.close():await s()):t?.enqueue(a)}catch(a){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=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function b5({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l,generateId:c,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f}){let g=null;const v=new ReadableStream({start(S){g=S}}),y=new Set,w=new Map,_=new Map;let h=!1,T;function k(){h&&y.size===0&&(T!=null&&g.enqueue(T),g.close())}const b=new TransformStream({async transform(S,x){const I=S.type;switch(I){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":{x.enqueue(S);break}case"file":{x.enqueue({type:"file",file:new Xk({data:S.data,mediaType:S.mediaType})});break}case"finish":{T={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:L0(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const L=_.get(S.toolCallId);if(L==null){g.enqueue({type:"error",error:new Ol({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}x.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:L});break}case"tool-call":{try{const L=await H0({toolCall:S,tools:e,repairToolCall:i,system:o,messages:s});if(_.set(L.toolCallId,L),x.enqueue(L),L.invalid){g.enqueue({type:"tool-error",toolCallId:L.toolCallId,toolName:L.toolName,input:L.input,error:ul(L.error),dynamic:!0,title:L.title});break}const $=e?.[L.toolName];if($==null)break;if($.onInputAvailable!=null&&await $.onInputAvailable({input:L.input,toolCallId:L.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await B0({tool:$,toolCall:L,messages:s,experimental_context:l})){g.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:L});break}if(w.set(L.toolCallId,L.input),$.execute!=null&&L.providerExecuted!==!0){const O=c();y.add(O),Ul({toolCall:L,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f,onPreliminaryToolResult:A=>{g.enqueue(A)}}).then(A=>{g.enqueue(A)}).catch(A=>{g.enqueue({type:"error",error:A})}).finally(()=>{y.delete(O),k()})}}catch(L){g.enqueue({type:"error",error:L})}break}case"tool-result":{const L=S.toolName;S.isError?g.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:L,input:w.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic}):x.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:L,input:w.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic});break}default:{const L=I;throw new Error(`Unhandled chunk type: ${L}`)}}},flush(){h=!0,k()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(b).pipeTo(new WritableStream({write(x){S.enqueue(x)},close(){}})),v.pipeTo(new WritableStream({write(x){S.enqueue(x)},close(){S.close()}}))])}})}var k5=No({prefix:"aitxt",size:24});function Zl({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=zl(1),experimental_output:m,output:p=m,experimental_telemetry:f,prepareStep:g,providerOptions:v,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:_,experimental_transform:h,experimental_download:T,includeRawChunks:k=!1,onChunk:b,onError:S=({error:B})=>{console.error(B)},onFinish:x,onAbort:I,onStepFinish:L,experimental_onStart:$,experimental_onStepStart:O,experimental_onToolCallStart:A,experimental_onToolCallFinish:U,experimental_context:Z,experimental_include:Y,_internal:{now:ye=Qs,generateId:X=k5}={},...he}){const B=Ll(l),N=w0(l),H=Sk(l),F=N!=null?new AbortController:void 0,E=H!=null?new AbortController:void 0;return new T5({model:Ws(e),telemetry:f,headers:c,settings:he,maxRetries:a,abortSignal:Y0(i,B!=null?AbortSignal.timeout(B):void 0,F?.signal,E?.signal),stepTimeoutMs:N,stepAbortController:F,chunkTimeoutMs:H,chunkAbortController:E,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:to(h),activeTools:w,repairToolCall:_,stopConditions:to(u),output:p,providerOptions:v,prepareStep:g,includeRawChunks:k,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:b,onError:S,onFinish:x,onAbort:I,onStepFinish:L,onStart:$,onStepStart:O,onToolCallStart:A,onToolCallFinish:U,now:ye,generateId:X,experimental_context:Z,download:T,include:Y})}function C5(e){let t,r="",n="",o,s="";function a({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&a({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&a({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const m=JSON.stringify(u.partial);m!==s&&(a({controller:l,partialOutput:u.partial}),s=m)}}})}var T5=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:a,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:m,messages:p,tools:f,toolChoice:g,transforms:v,activeTools:y,repairToolCall:w,stopConditions:_,output:h,providerOptions:T,prepareStep:k,includeRawChunks:b,now:S,generateId:x,timeout:I,stopWhen:L,originalAbortSignal:$,onChunk:O,onError:A,onFinish:U,onAbort:Z,onStepFinish:Y,onStart:ye,onStepStart:X,onToolCallStart:he,onToolCallFinish:B,experimental_context:N,download:H,include:F}){this._totalUsage=new Po,this._finishReason=new Po,this._rawFinishReason=new Po,this._steps=new Po,this.outputSpecification=h,this.includeRawChunks=b,this.tools=f;let E,M=[];const D=[];let G,te,se,Te={},z=[];const V=[],W=new Map;let Q,ie={},_e={};const Ye=new TransformStream({async transform(Xe,Se){var nt,Ie,He,_r;Se.enqueue(Xe);const{part:K}=Xe;if((K.type==="text-delta"||K.type==="reasoning-delta"||K.type==="source"||K.type==="tool-call"||K.type==="tool-result"||K.type==="tool-input-start"||K.type==="tool-input-delta"||K.type==="raw")&&await O?.({chunk:K}),K.type==="error"&&await A({error:N0(K.error)}),K.type==="text-start"&&(ie[K.id]={type:"text",text:"",providerMetadata:K.providerMetadata},M.push(ie[K.id])),K.type==="text-delta"){const Je=ie[K.id];if(Je==null){Se.enqueue({part:{type:"error",error:`text part ${K.id} not found`},partialOutput:void 0});return}Je.text+=K.text,Je.providerMetadata=(nt=K.providerMetadata)!=null?nt:Je.providerMetadata}if(K.type==="text-end"){const Je=ie[K.id];if(Je==null){Se.enqueue({part:{type:"error",error:`text part ${K.id} not found`},partialOutput:void 0});return}Je.providerMetadata=(Ie=K.providerMetadata)!=null?Ie:Je.providerMetadata,delete ie[K.id]}if(K.type==="reasoning-start"&&(_e[K.id]={type:"reasoning",text:"",providerMetadata:K.providerMetadata},M.push(_e[K.id])),K.type==="reasoning-delta"){const Je=_e[K.id];if(Je==null){Se.enqueue({part:{type:"error",error:`reasoning part ${K.id} not found`},partialOutput:void 0});return}Je.text+=K.text,Je.providerMetadata=(He=K.providerMetadata)!=null?He:Je.providerMetadata}if(K.type==="reasoning-end"){const Je=_e[K.id];if(Je==null){Se.enqueue({part:{type:"error",error:`reasoning part ${K.id} not found`},partialOutput:void 0});return}Je.providerMetadata=(_r=K.providerMetadata)!=null?_r:Je.providerMetadata,delete _e[K.id]}if(K.type==="file"&&M.push({type:"file",file:K.file}),K.type==="source"&&M.push(K),K.type==="tool-call"&&M.push(K),K.type==="tool-result"&&!K.preliminary&&M.push(K),K.type==="tool-approval-request"&&M.push(K),K.type==="tool-error"&&M.push(K),K.type==="start-step"&&(M=[],_e={},ie={},Te=K.request,z=K.warnings),K.type==="finish-step"){const Je=await Fl({content:M,tools:f}),vr=new W0({stepNumber:V.length,model:Wt,...Vr,experimental_context:N,content:M,finishReason:K.finishReason,rawFinishReason:K.rawFinishReason,usage:K.usage,warnings:z,request:Te,response:{...K.response,messages:[...D,...Je]},providerMetadata:K.providerMetadata});await cr({event:vr,callbacks:Y}),ql({warnings:z,provider:Wt.provider,model:Wt.modelId}),V.push(vr),D.push(...Je),E.resolve()}K.type==="finish"&&(se=K.totalUsage,G=K.finishReason,te=K.rawFinishReason)},async flush(Xe){try{if(V.length===0){const He=s?.aborted?s.reason:new e0({message:"No output generated. Check the stream for errors."});Qe._finishReason.reject(He),Qe._rawFinishReason.reject(He),Qe._totalUsage.reject(He),Qe._steps.reject(He);return}const Se=G??"other",nt=se??Dl();Qe._finishReason.resolve(Se),Qe._rawFinishReason.resolve(te),Qe._totalUsage.resolve(nt),Qe._steps.resolve(V);const Ie=V[V.length-1];await cr({event:{stepNumber:Ie.stepNumber,model:Ie.model,functionId:Ie.functionId,metadata:Ie.metadata,experimental_context:Ie.experimental_context,finishReason:Ie.finishReason,rawFinishReason:Ie.rawFinishReason,totalUsage:nt,usage:Ie.usage,content:Ie.content,text:Ie.text,reasoningText:Ie.reasoningText,reasoning:Ie.reasoning,files:Ie.files,sources:Ie.sources,toolCalls:Ie.toolCalls,staticToolCalls:Ie.staticToolCalls,dynamicToolCalls:Ie.dynamicToolCalls,toolResults:Ie.toolResults,staticToolResults:Ie.staticToolResults,dynamicToolResults:Ie.dynamicToolResults,request:Ie.request,response:Ie.response,warnings:Ie.warnings,providerMetadata:Ie.providerMetadata,steps:V},callbacks:U}),Q.setAttributes(await Ir({telemetry:t,attributes:{"ai.response.finishReason":Se,"ai.response.text":{output:()=>Ie.text},"ai.response.reasoning":{output:()=>Ie.reasoningText},"ai.response.toolCalls":{output:()=>{var He;return(He=Ie.toolCalls)!=null&&He.length?JSON.stringify(Ie.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Ie.providerMetadata),"ai.usage.inputTokens":nt.inputTokens,"ai.usage.outputTokens":nt.outputTokens,"ai.usage.totalTokens":nt.totalTokens,"ai.usage.reasoningTokens":nt.reasoningTokens,"ai.usage.cachedInputTokens":nt.cachedInputTokens}}))}catch(Se){Xe.error(Se)}finally{Q.end()}}}),ct=w5();this.addStream=ct.addStream,this.closeStream=ct.close;const pt=ct.stream.getReader();let rt=new ReadableStream({async start(Xe){Xe.enqueue({type:"start"})},async pull(Xe){function Se(){Z?.({steps:V}),Xe.enqueue({type:"abort",...s?.reason!==void 0?{reason:mn(s.reason)}:{}}),Xe.close()}try{const{done:nt,value:Ie}=await pt.read();if(nt){Xe.close();return}if(s?.aborted){Se();return}Xe.enqueue(Ie)}catch(nt){bn(nt)&&s?.aborted?Se():Xe.error(nt)}},cancel(Xe){return ct.stream.cancel(Xe)}});for(const Xe of v)rt=rt.pipeThrough(Xe({tools:f,stopStream(){ct.terminate()}}));this.baseStream=rt.pipeThrough(C5(h??Xs())).pipeThrough(Ye);const{maxRetries:P,retry:re}=U0({maxRetries:o,abortSignal:s}),Re=O0(t),Me=jl(n),nr=M0({model:e,telemetry:t,headers:r,settings:{...Me,maxRetries:P}}),Qe=this,Wt={provider:e.provider,modelId:e.modelId},Vr={functionId:t?.functionId,metadata:t?.metadata};Vo({name:"ai.streamText",attributes:Ir({telemetry:t,attributes:{...Fo({operationId:"ai.streamText",telemetry:t}),...nr,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:m,messages:p})}}}),tracer:Re,endWhenDone:!1,fn:async Xe=>{Q=Xe;const Se=await P0({system:u,prompt:m,messages:p});await cr({event:{model:Wt,system:u,prompt:m,messages:p,tools:f,toolChoice:g,activeTools:y,maxOutputTokens:Me.maxOutputTokens,temperature:Me.temperature,topP:Me.topP,topK:Me.topK,presencePenalty:Me.presencePenalty,frequencyPenalty:Me.frequencyPenalty,stopSequences:Me.stopSequences,seed:Me.seed,maxRetries:P,timeout:I,headers:r,providerOptions:T,stopWhen:L,output:h,abortSignal:$,include:F,...Vr,experimental_context:N},callbacks:ye});const nt=Se.messages,Ie=[],{approvedToolApprovals:He,deniedToolApprovals:_r}=z0({messages:nt});if(_r.length>0||He.length>0){const Je=[...He,..._r].filter(ft=>ft.toolCall.providerExecuted),vr=He.filter(ft=>!ft.toolCall.providerExecuted),ot=_r.filter(ft=>!ft.toolCall.providerExecuted),Ct=_r.filter(ft=>ft.toolCall.providerExecuted);let Ce;const Mt=new ReadableStream({start(ft){Ce=ft}});Qe.addStream(Mt);try{for(const Tt of[...ot,...Ct])Ce?.enqueue({type:"tool-output-denied",toolCallId:Tt.toolCall.toolCallId,toolName:Tt.toolCall.toolName});const ft=[];if(await Promise.all(vr.map(async Tt=>{const ut=await Ul({toolCall:Tt.toolCall,tools:f,tracer:Re,telemetry:t,messages:nt,abortSignal:s,experimental_context:N,stepNumber:V.length,model:Wt,onToolCallStart:he,onToolCallFinish:B,onPreliminaryToolResult:Zr=>{Ce?.enqueue(Zr)}});ut!=null&&(Ce?.enqueue(ut),ft.push(ut))})),Je.length>0&&Ie.push({role:"tool",content:Je.map(Tt=>({type:"tool-approval-response",approvalId:Tt.approvalResponse.approvalId,approved:Tt.approvalResponse.approved,reason:Tt.approvalResponse.reason,providerExecuted:!0}))}),ft.length>0||ot.length>0){const Tt=[];for(const ut of ft)Tt.push({type:"tool-result",toolCallId:ut.toolCallId,toolName:ut.toolName,output:await Uo({toolCallId:ut.toolCallId,input:ut.input,tool:f?.[ut.toolName],output:ut.type==="tool-result"?ut.output:ut.error,errorMode:ut.type==="tool-error"?"json":"none"})});for(const ut of ot)Tt.push({type:"tool-result",toolCallId:ut.toolCall.toolCallId,toolName:ut.toolCall.toolName,output:{type:"execution-denied",reason:ut.approvalResponse.reason}});Ie.push({role:"tool",content:Tt})}}finally{Ce?.close()}}D.push(...Ie);async function K({currentStep:Je,responseMessages:vr,usage:ot}){var Ct,Ce,Mt,ft,Tt,ut,Zr,_o,Pi;const Ni=Qe.includeRawChunks,gs=a!=null?setTimeout(()=>i.abort(),a):void 0;let or;function ys(){l!=null&&(or!=null&&clearTimeout(or),or=setTimeout(()=>c.abort(),l))}function Mi(){or!=null&&(clearTimeout(or),or=void 0)}function _s(){gs!=null&&clearTimeout(gs)}try{E=new Po;const fn=[...nt,...vr],yt=await k?.({model:e,steps:V,stepNumber:V.length,messages:fn,experimental_context:N}),Er=Ws((Ct=yt?.model)!=null?Ct:e),vs={provider:Er.provider,modelId:Er.modelId},Oe=await T0({prompt:{system:(Ce=yt?.system)!=null?Ce:Se.system,messages:(Mt=yt?.messages)!=null?Mt:fn},supportedUrls:await Er.supportedUrls,download:H}),Ot=(ft=yt?.activeTools)!=null?ft:y,{toolChoice:hn,tools:Br}=await x0({tools:f,toolChoice:(Tt=yt?.toolChoice)!=null?Tt:g,activeTools:Ot});N=(ut=yt?.experimental_context)!=null?ut:N;const Oi=(Zr=yt?.messages)!=null?Zr:fn,Ai=(_o=yt?.system)!=null?_o:Se.system,ws=Ys(T,yt?.providerOptions);await cr({event:{stepNumber:V.length,model:vs,system:Ai,messages:Oi,tools:f,toolChoice:hn,activeTools:Ot,steps:[...V],providerOptions:ws,timeout:I,headers:r,stopWhen:L,output:h,abortSignal:$,include:F,...Vr,experimental_context:N},callbacks:X});const{result:{stream:qi,response:bs,request:vo},doStreamSpan:dt,startTimestampMs:Hr}=await re(()=>Vo({name:"ai.streamText.doStream",attributes:Ir({telemetry:t,attributes:{...Fo({operationId:"ai.streamText.doStream",telemetry:t}),...nr,"ai.model.provider":Er.provider,"ai.model.id":Er.modelId,"ai.prompt.messages":{input:()=>q0(Oe)},"ai.prompt.tools":{input:()=>Br?.map(ve=>JSON.stringify(ve))},"ai.prompt.toolChoice":{input:()=>hn!=null?JSON.stringify(hn):void 0},"gen_ai.system":Er.provider,"gen_ai.request.model":Er.modelId,"gen_ai.request.frequency_penalty":Me.frequencyPenalty,"gen_ai.request.max_tokens":Me.maxOutputTokens,"gen_ai.request.presence_penalty":Me.presencePenalty,"gen_ai.request.stop_sequences":Me.stopSequences,"gen_ai.request.temperature":Me.temperature,"gen_ai.request.top_k":Me.topK,"gen_ai.request.top_p":Me.topP}}),tracer:Re,endWhenDone:!1,fn:async ve=>({startTimestampMs:S(),doStreamSpan:ve,result:await Er.doStream({...Me,tools:Br,toolChoice:hn,responseFormat:await h?.responseFormat,prompt:Oe,providerOptions:ws,abortSignal:s,headers:r,includeRawChunks:Ni})})})),Li=b5({tools:f,generatorStream:qi,tracer:Re,telemetry:t,system:u,messages:fn,repairToolCall:w,abortSignal:s,experimental_context:N,generateId:x,stepNumber:V.length,model:vs,onToolCallStart:he,onToolCallFinish:B}),xE=(Pi=F?.requestBody)==null||Pi?vo??{}:{...vo,body:void 0},ks=[],Cs=[];let Bu;const Hu={};let wo="other",Ju,wr=Dl(),Gu,J_=!0,$r={id:x(),timestamp:new Date,modelId:Wt.modelId},G_="";Qe.addStream(Li.pipeThrough(new TransformStream({async transform(ve,Pt){var Ts,Ss,ji,ht,Rr;if(ys(),ve.type==="stream-start"){Bu=ve.warnings;return}if(J_){const mt=S()-Hr;J_=!1,dt.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":mt}),dt.setAttributes({"ai.response.msToFirstChunk":mt}),Pt.enqueue({type:"start-step",request:xE,warnings:Bu??[]})}const Wu=ve.type;switch(Wu){case"tool-approval-request":case"text-start":case"text-end":{Pt.enqueue(ve);break}case"text-delta":{ve.delta.length>0&&(Pt.enqueue({type:"text-delta",id:ve.id,text:ve.delta,providerMetadata:ve.providerMetadata}),G_+=ve.delta);break}case"reasoning-start":case"reasoning-end":{Pt.enqueue(ve);break}case"reasoning-delta":{Pt.enqueue({type:"reasoning-delta",id:ve.id,text:ve.delta,providerMetadata:ve.providerMetadata});break}case"tool-call":{Pt.enqueue(ve),ks.push(ve);break}case"tool-result":{Pt.enqueue(ve),ve.preliminary||Cs.push(ve);break}case"tool-error":{Pt.enqueue(ve),Cs.push(ve);break}case"response-metadata":{$r={id:(Ts=ve.id)!=null?Ts:$r.id,timestamp:(Ss=ve.timestamp)!=null?Ss:$r.timestamp,modelId:(ji=ve.modelId)!=null?ji:$r.modelId};break}case"finish":{wr=ve.usage,wo=ve.finishReason,Ju=ve.rawFinishReason,Gu=ve.providerMetadata;const mt=S()-Hr;dt.addEvent("ai.stream.finish"),dt.setAttributes({"ai.response.msToFinish":mt,"ai.response.avgOutputTokensPerSecond":1e3*((ht=wr.outputTokens)!=null?ht:0)/mt});break}case"file":{Pt.enqueue(ve);break}case"source":{Pt.enqueue(ve);break}case"tool-input-start":{Hu[ve.id]=ve.toolName;const mt=f?.[ve.toolName];mt?.onInputStart!=null&&await mt.onInputStart({toolCallId:ve.id,messages:fn,abortSignal:s,experimental_context:N}),Pt.enqueue({...ve,dynamic:(Rr=ve.dynamic)!=null?Rr:mt?.type==="dynamic",title:mt?.title});break}case"tool-input-end":{delete Hu[ve.id],Pt.enqueue(ve);break}case"tool-input-delta":{const mt=Hu[ve.id],Ku=f?.[mt];Ku?.onInputDelta!=null&&await Ku.onInputDelta({inputTextDelta:ve.delta,toolCallId:ve.id,messages:fn,abortSignal:s,experimental_context:N}),Pt.enqueue(ve);break}case"error":{Pt.enqueue(ve),wo="error";break}case"raw":{Ni&&Pt.enqueue(ve);break}default:{const mt=Wu;throw new Error(`Unknown chunk type: ${mt}`)}}},async flush(ve){const Pt=ks.length>0?JSON.stringify(ks):void 0;try{dt.setAttributes(await Ir({telemetry:t,attributes:{"ai.response.finishReason":wo,"ai.response.text":{output:()=>G_},"ai.response.reasoning":{output:()=>{const ht=M.filter(Rr=>Rr.type==="reasoning");return ht.length>0?ht.map(Rr=>Rr.text).join(`
69
+ `):void 0}},"ai.response.toolCalls":{output:()=>Pt},"ai.response.id":$r.id,"ai.response.model":$r.modelId,"ai.response.timestamp":$r.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Gu),"ai.usage.inputTokens":wr.inputTokens,"ai.usage.outputTokens":wr.outputTokens,"ai.usage.totalTokens":wr.totalTokens,"ai.usage.reasoningTokens":wr.reasoningTokens,"ai.usage.cachedInputTokens":wr.cachedInputTokens,"gen_ai.response.finish_reasons":[wo],"gen_ai.response.id":$r.id,"gen_ai.response.model":$r.modelId,"gen_ai.usage.input_tokens":wr.inputTokens,"gen_ai.usage.output_tokens":wr.outputTokens}}))}catch{}finally{dt.end()}ve.enqueue({type:"finish-step",finishReason:wo,rawFinishReason:Ju,usage:wr,providerMetadata:Gu,response:{...$r,headers:bs?.headers}});const Ts=j0(ot,wr);await E.promise;const Ss=ks.filter(ht=>ht.providerExecuted!==!0),ji=Cs.filter(ht=>ht.providerExecuted!==!0);for(const ht of ks){if(ht.providerExecuted!==!0)continue;const Rr=f?.[ht.toolName];Rr?.type==="provider"&&Rr.supportsDeferredResults&&(Cs.some(mt=>(mt.type==="tool-result"||mt.type==="tool-error")&&mt.toolCallId===ht.toolCallId)||W.set(ht.toolCallId,{toolName:ht.toolName}))}for(const ht of Cs)(ht.type==="tool-result"||ht.type==="tool-error")&&W.delete(ht.toolCallId);if(_s(),Mi(),(Ss.length>0&&ji.length===Ss.length||W.size>0)&&!await K0({stopConditions:_,steps:V})){vr.push(...await Fl({content:V[V.length-1].content,tools:f}));try{await K({currentStep:Je+1,responseMessages:vr,usage:Ts})}catch(ht){ve.enqueue({type:"error",error:ht}),Qe.closeStream()}}else ve.enqueue({type:"finish",finishReason:wo,rawFinishReason:Ju,totalUsage:Ts}),Qe.closeStream()}})))}finally{_s(),Mi()}}await K({currentStep:0,responseMessages:Ie,usage:Dl()})}}).catch(Xe=>{Qe.addStream(new ReadableStream({start(Se){Se.enqueue({type:"error",error:Xe}),Se.close()}})),Qe.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}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Bo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Bo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await v5({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Bo(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new br({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Bo(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Xs()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=mn}={}){const c=t!=null?p5({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var f;const g=(f=this.tools)==null?void 0:f[p.toolName];return g==null?p.dynamic:g?.type==="dynamic"?!0:void 0},m=this.fullStream.pipeThrough(new TransformStream({transform:async(p,f)=>{const g=n?.({part:p}),v=p.type;switch(v){case"text-start":{f.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&f.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{s&&p.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const y=u(p);f.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const y=u(p);p.invalid?f.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):f.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{f.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const y=u(p);f.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=u(p);f.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-output-denied":{f.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{f.enqueue({type:"error",errorText:l(p.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",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:p.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{f.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=v;throw new Error(`Unknown chunk type: ${y}`)}}g!=null&&v!=="start"&&v!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:g})}}));return Bo(y5({stream:m,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){_5({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){u5({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...c}={}){return d5({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return c5({textStream:this.textStream,...e})}};No({prefix:"aiobj",size:24}),No({prefix:"aiobj",size:24});let Bl;Bl=globalThis.crypto;async function S5(e){return(await Bl).getRandomValues(new Uint8Array(e))}async function I5(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await S5(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function x5(e){return await I5(e)}async function E5(e){const t=await(await Bl).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function im(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await x5(e),r=await E5(t);return{code_verifier:t,code_challenge:r}}var $5="AI_MCPClientError",lm=`vercel.ai.error.${$5}`,R5=Symbol.for(lm),cm,um,ze=class extends(um=me,cm=R5,um){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[cm]=!0,this.data=n,this.code=o}static isInstance(e){return me.hasMarker(e,lm)}},ro="2025-06-18",P5=[ro,"2025-03-26","2024-11-05"],N5=le(ge(d(),$e())),M5=it({name:d(),version:d()}),ta=it({_meta:le(C({}).loose())}),Ar=ta,dm=C({method:d(),params:le(ta)}),pm=C({applyDefaults:le(pe())}).loose(),O5=it({experimental:le(C({}).loose()),logging:le(C({}).loose()),prompts:le(it({listChanged:le(pe())})),resources:le(it({subscribe:le(pe()),listChanged:le(pe())})),tools:le(it({listChanged:le(pe())})),elicitation:le(pm)});C({elicitation:le(pm)}).loose();var A5=Ar.extend({protocolVersion:d(),capabilities:O5,serverInfo:M5,instructions:le(d())}),Hl=Ar.extend({nextCursor:le(d())}),q5=C({name:d(),title:le(d()),description:le(d()),inputSchema:C({type:R("object"),properties:le(C({}).loose())}).loose(),outputSchema:le(C({}).loose()),annotations:le(C({title:le(d())}).loose()),_meta:N5}).loose(),L5=Hl.extend({tools:q(q5)}),fm=C({type:R("text"),text:d()}).loose(),hm=C({type:R("image"),data:Mp(),mimeType:d()}).loose(),j5=C({uri:d(),name:d(),title:le(d()),description:le(d()),mimeType:le(d()),size:le(j())}).loose(),D5=Hl.extend({resources:q(j5)}),mm=C({uri:d(),name:le(d()),title:le(d()),mimeType:le(d())}).loose(),gm=mm.extend({text:d()}),ym=mm.extend({blob:Mp()}),_m=C({type:R("resource"),resource:oe([gm,ym])}).loose(),U5=Ar.extend({content:q(oe([fm,hm,_m])),structuredContent:le($e()),isError:pe().default(!1).optional()}).or(Ar.extend({toolResult:$e()})),z5=C({uriTemplate:d(),name:d(),title:le(d()),description:le(d()),mimeType:le(d())}).loose(),F5=Ar.extend({resourceTemplates:q(z5)}),V5=Ar.extend({contents:q(oe([gm,ym]))}),Z5=C({name:d(),description:le(d()),required:le(pe())}).loose(),B5=C({name:d(),title:le(d()),description:le(d()),arguments:le(q(Z5))}).loose(),H5=Hl.extend({prompts:q(B5)}),J5=C({role:oe([R("user"),R("assistant")]),content:oe([fm,hm,_m])}).loose(),G5=Ar.extend({description:le(d()),messages:q(J5)}),W5=ta.extend({message:d(),requestedSchema:$e()}),vm=dm.extend({method:R("elicitation/create"),params:W5}),K5=Ar.extend({action:oe([R("accept"),R("decline"),R("cancel")]),content:le(ge(d(),$e()))}),ra="2.0",Y5=C({jsonrpc:R(ra),id:oe([d(),j().int()])}).merge(dm).strict(),Q5=C({jsonrpc:R(ra),id:oe([d(),j().int()]),result:Ar}).strict(),X5=C({jsonrpc:R(ra),id:oe([d(),j().int()]),error:C({code:j().int(),message:d(),data:le($e())})}).strict(),eC=C({jsonrpc:R(ra)}).merge(C({method:d(),params:le(ta)})).strict(),Ho=oe([Y5,eC,Q5,X5]),wm=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",bm=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:j().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Ft=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vp.custom,message:"URL must be parseable",fatal:!0}),Fd}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),tC=C({resource:d().url(),authorization_servers:q(Ft).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:pe().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:pe().optional()}).passthrough(),km=C({issuer:d(),authorization_endpoint:Ft,token_endpoint:Ft,registration_endpoint:Ft.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),code_challenge_methods_supported:q(d()),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional()}).passthrough(),rC=C({issuer:d(),authorization_endpoint:Ft,token_endpoint:Ft,userinfo_endpoint:Ft.optional(),jwks_uri:Ft,registration_endpoint:Ft.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),claims_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional()}).passthrough(),nC=rC.merge(km.pick({code_challenge_methods_supported:!0})),oC=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),sC=C({redirect_uris:q(Ft),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Ft.optional(),logo_uri:Ft.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Ft.optional(),policy_uri:d().optional(),jwks_uri:Ft.optional(),jwks:wt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),aC=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),iC=sC.merge(oC),lC="AI_MCPClientOAuthError",Cm=`vercel.ai.error.${lC}`,cC=Symbol.for(Cm),Tm,Sm,Jo=class extends(Sm=me,Tm=cC,Sm){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[Tm]=!0}static isInstance(e){return me.hasMarker(e,Cm)}},no=class extends Jo{};no.errorCode="server_error";var na=class extends Jo{};na.errorCode="invalid_client";var oa=class extends Jo{};oa.errorCode="invalid_grant";var sa=class extends Jo{};sa.errorCode="unauthorized_client";var uC={[no.errorCode]:no,[na.errorCode]:na,[oa.errorCode]:oa,[sa.errorCode]:sa};function dC(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function pC({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var aa=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function ia(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const s=/resource_metadata="([^"]*)"/,a=r.match(s);if(a)try{return new URL(a[1])}catch{return}}function fC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Jl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Jl(e,void 0,r):void 0;throw n}}async function Im(e,t,r=fetch){return await Jl(e,{"MCP-Protocol-Version":t},r)}function hC(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function mC(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:ro;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=fC(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await Im(l,i,r);if(!n?.metadataUrl&&hC(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await Im(u,i,r)}return c}async function gC(e,t,r=fetch){const n=await mC(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return tC.parse(await n.json())}function yC(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function _C(e,{fetchFn:t=fetch,protocolVersion:r=ro}={}){var n;const o={"MCP-Protocol-Version":r},s=yC(e);for(const{url:a,type:i}of s){const l=await Jl(a,o,t);if(l){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 km.parse(await l.json());{const c=nC.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function vC(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){const i="code",l="S256";let c;if(t){if(c=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 c=new URL("/authorize",e);const u=await im(),m=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:m}}function xm(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Em(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":wC(o,s,r);return;case"client_secret_post":bC(o,s,n);return;case"none":kC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function wC(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function bC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function kC(e,t){t.set("client_id",e)}async function Gl(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=aC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=uC[o]||no;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new no({message:o})}}async function CC(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",m=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(p,f,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=xm(r,v);Em(y,r,p,f)}a&&f.set("resource",a.href);const g=await(l??fetch)(m,{method:"POST",headers:p,body:f});if(!g.ok)throw await Gl(g);return bm.parse(await g.json())}async function TC(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=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 c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,m,e,t);else{const f=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],g=xm(r,f);Em(g,r,u,m)}o&&m.set("resource",o.href);const p=await(a??fetch)(c,{method:"POST",headers:u,body:m});if(!p.ok)throw await Gl(p);return bm.parse({refresh_token:n,...await p.json()})}async function SC(e,{metadata:t,clientMetadata:r,fetchFn:n}){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(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Gl(s);return iC.parse(await s.json())}async function la(e,t){var r,n;try{return await Wl(e,t)}catch(o){if(o instanceof na||o instanceof sa)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Wl(e,t);if(o instanceof oa)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Wl(e,t);throw o}}async function IC(e,t,r){const n=dC(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!pC({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}async function Wl(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await gC(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await IC(t,e,a),c=await _C(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==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 v=await SC(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),y=await CC(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const m=await e.tokens();if(m?.refresh_token)try{const v=await TC(i,{metadata:c,clientInformation:u,refreshToken:m.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Jo)||v instanceof no))throw v}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await vC(i,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(f),"REDIRECT"}var xC=class{constructor({url:e,headers:t,authProvider:r}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":ro};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return rn(t,`ai-sdk/${wm}`,Mo())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ia(u);try{if(await la(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new aa;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return r(!0)}if(!u.ok||!u.body){let g=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const v=new ze({message:g});return(i=this.onerror)==null||i.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader(),f=async()=>{var g,v,y;try{for(;;){const{done:w,value:_}=await p.read();if(w){if(this.connected)throw this.connected=!1,new ze({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:h,data:T}=_;if(h==="endpoint"){if(this.endpoint=new URL(T,this.url),this.endpoint.origin!==this.url.origin)throw new ze({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(h==="message")try{const k=Ho.parse(JSON.parse(T));(g=this.onmessage)==null||g.call(this,k)}catch(k){const b=new ze({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(v=this.onerror)==null||v.call(this,b)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(y=this.onerror)==null||y.call(this,w),t(w)}};this.sseConnection={close:()=>p.cancel()},f()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new ze({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},m=await fetch(t,u);if(m.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ia(m);try{if(await la(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new aa;(s=this.onerror)==null||s.call(this,f);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!m.ok){const p=await m.text().catch(()=>null),f=new ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${p}`});(i=this.onerror)==null||i.call(this,f);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},EC=class{constructor({url:e,headers:t,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":ro};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return rn(t,`ai-sdk/${wm}`,Mo())}async start(){if(this.abortController)throw new ze({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,a,i,l,c;try{const m={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},p=await fetch(this.url,m),f=p.headers.get("mcp-session-id");if(f&&(this.sessionId=f),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=ia(p);try{if(await la(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new aa}catch(w){throw(o=this.onerror)==null||o.call(this,w),w}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const w=await p.text().catch(()=>null);let _=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(_+=". This server does not support HTTP transport. Try using `sse` transport instead");const h=new ze({message:_});throw(s=this.onerror)==null||s.call(this,h),h}if(!("id"in e))return;const v=p.headers.get("content-type")||"";if(v.includes("application/json")){const w=await p.json(),_=Array.isArray(w)?w.map(h=>Ho.parse(h)):[Ho.parse(w)];for(const h of _)(a=this.onmessage)==null||a.call(this,h);return}if(v.includes("text/event-stream")){if(!p.body){const T=new ze({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,T),T}const _=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader();(async()=>{var T,k,b;try{for(;;){const{done:S,value:x}=await _.read();if(S)return;const{event:I,data:L}=x;if(I==="message")try{const $=Ho.parse(JSON.parse(L));(T=this.onmessage)==null||T.call(this,$)}catch($){const O=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:$});(k=this.onerror)==null||k.call(this,O)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(b=this.onerror)==null||b.call(this,S)}})();return}const y=new ze({message:`MCP HTTP Transport Error: Unexpected content type: ${v}`});throw(l=this.onerror)==null||l.call(this,y),y}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new ze({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await fetch(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=ia(c);try{if(await la(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new aa;(n=this.onerror)==null||n.call(this,v);return}}catch(g){(o=this.onerror)==null||o.call(this,g);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const g=new ze({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,g);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).getReader(),f=async()=>{var g,v,y,w;try{for(;;){const{done:_,value:h}=await p.read();if(_)return;const{event:T,data:k,id:b}=h;if(b&&(this.lastInboundEventId=b),T==="message")try{const S=Ho.parse(JSON.parse(k));(g=this.onmessage)==null||g.call(this,S)}catch(S){const x=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,x)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(y=this.onerror)==null||y.call(this,_),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,f()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function $C(e){switch(e.type){case"sse":return new xC(e);case"http":return new EC(e);default:throw new ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function RC(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var PC="1.0.0";function $m({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function NC(e){const t=new MC(e);return await t.init(),t}var MC=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=PC,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},RC(e)?this.transport=e:this.transport=$C(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new ze({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:ro,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:A5});if(e===void 0)throw new ze({message:"Server sent invalid initialize result"});if(!P5.includes(e.protocolVersion))throw new ze({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 ze({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new ze({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new ze({message:"Server does not support prompts"});break;default:throw new ze({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new ze({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s?.aborted)return o(new ze({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const m=new ze({message:"Failed to parse server response",cause:u});o(m)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:L5,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:U5,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:D5,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:V5,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:F5,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:H5,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:G5,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:s,title:a,description:i,inputSchema:l,annotations:c,_meta:u}of e.tools){const m=a??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,f=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,g=async(y,w)=>{var _;(_=w?.abortSignal)==null||_.throwIfAborted();const h=await p.callTool({name:s,args:y,options:w});return f!=null?p.extractStructuredContent(h,f,s):h},v=t==="automatic"?Of({description:i,title:m,inputSchema:Xn({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:$m}):{description:i,title:m,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:g,toModelOutput:$m};o[s]={...v,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await Yt({value:e.structuredContent,schema:Cn(t)});if(!n.success)throw new ze({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await Qt({text:n.text,schema:t});if(!o.success)throw new ze({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new ze({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==vm)throw new ze({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=vm.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=K5.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new ze({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),r=this.responseHandlers.get(t);if(r===void 0)throw new ze({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new ze({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function ca(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Rm(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...ca(t.headers),...ca(n.headers)}:t.headers};return e(r,o)}:e}const ua="2025-11-25",OC=[ua,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],En="io.modelcontextprotocol/related-task",da="2.0",It=zp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Pm=oe([d(),j().int()]),Nm=d();it({ttl:oe([j(),Ls()]).optional(),pollInterval:j().optional()});const AC=C({ttl:j().optional()}),qC=C({taskId:d()}),Kl=it({progressToken:Pm.optional(),[En]:qC.optional()}),Jt=C({_meta:Kl.optional()}),Go=Jt.extend({task:AC.optional()}),LC=e=>Go.safeParse(e).success,xt=C({method:d(),params:Jt.loose().optional()}),er=C({_meta:Kl.optional()}),tr=C({method:d(),params:er.loose().optional()}),Et=it({_meta:Kl.optional()}),pa=oe([d(),j().int()]),Mm=C({jsonrpc:R(da),id:pa,...xt.shape}).strict(),Yl=e=>Mm.safeParse(e).success,Om=C({jsonrpc:R(da),...tr.shape}).strict(),jC=e=>Om.safeParse(e).success,Ql=C({jsonrpc:R(da),id:pa,result:Et}).strict(),Wo=e=>Ql.safeParse(e).success;var Ee;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ee||(Ee={}));const Xl=C({jsonrpc:R(da),id:pa.optional(),error:C({code:j().int(),message:d(),data:$e().optional()})}).strict(),DC=e=>Xl.safeParse(e).success,$n=oe([Mm,Om,Ql,Xl]);oe([Ql,Xl]);const Rn=Et.strict(),UC=er.extend({requestId:pa.optional(),reason:d().optional()}),ec=tr.extend({method:R("notifications/cancelled"),params:UC}),zC=C({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:fe(["light","dark"]).optional()}),Ko=C({icons:q(zC).optional()}),oo=C({name:d(),title:d().optional()}),Am=oo.extend({...oo.shape,...Ko.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),FC=Wi(C({applyDefaults:pe().optional()}),ge(d(),$e())),VC=Fp(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Wi(C({form:FC.optional(),url:It.optional()}),ge(d(),$e()).optional())),ZC=it({list:It.optional(),cancel:It.optional(),requests:it({sampling:it({createMessage:It.optional()}).optional(),elicitation:it({create:It.optional()}).optional()}).optional()}),BC=it({list:It.optional(),cancel:It.optional(),requests:it({tools:it({call:It.optional()}).optional()}).optional()}),HC=C({experimental:ge(d(),It).optional(),sampling:C({context:It.optional(),tools:It.optional()}).optional(),elicitation:VC.optional(),roots:C({listChanged:pe().optional()}).optional(),tasks:ZC.optional()}),JC=Jt.extend({protocolVersion:d(),capabilities:HC,clientInfo:Am}),GC=xt.extend({method:R("initialize"),params:JC}),WC=C({experimental:ge(d(),It).optional(),logging:It.optional(),completions:It.optional(),prompts:C({listChanged:pe().optional()}).optional(),resources:C({subscribe:pe().optional(),listChanged:pe().optional()}).optional(),tools:C({listChanged:pe().optional()}).optional(),tasks:BC.optional()}),qm=Et.extend({protocolVersion:d(),capabilities:WC,serverInfo:Am,instructions:d().optional()}),Lm=tr.extend({method:R("notifications/initialized"),params:er.optional()}),KC=e=>Lm.safeParse(e).success,tc=xt.extend({method:R("ping"),params:Jt.optional()}),YC=C({progress:j(),total:le(j()),message:le(d())}),QC=C({...er.shape,...YC.shape,progressToken:Pm}),rc=tr.extend({method:R("notifications/progress"),params:QC}),XC=Jt.extend({cursor:Nm.optional()}),Yo=xt.extend({params:XC.optional()}),Qo=Et.extend({nextCursor:Nm.optional()}),eT=fe(["working","input_required","completed","failed","cancelled"]),Xo=C({taskId:d(),status:eT,ttl:oe([j(),Ls()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:le(j()),statusMessage:le(d())}),es=Et.extend({task:Xo}),tT=er.merge(Xo),fa=tr.extend({method:R("notifications/tasks/status"),params:tT}),nc=xt.extend({method:R("tasks/get"),params:Jt.extend({taskId:d()})}),oc=Et.merge(Xo),sc=xt.extend({method:R("tasks/result"),params:Jt.extend({taskId:d()})});Et.loose();const ac=Yo.extend({method:R("tasks/list")}),ic=Qo.extend({tasks:q(Xo)}),lc=xt.extend({method:R("tasks/cancel"),params:Jt.extend({taskId:d()})}),rT=Et.merge(Xo),jm=C({uri:d(),mimeType:le(d()),_meta:ge(d(),$e()).optional()}),Dm=jm.extend({text:d()}),cc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Um=jm.extend({blob:cc}),ts=fe(["user","assistant"]),so=C({audience:q(ts).optional(),priority:j().min(0).max(1).optional(),lastModified:xp({offset:!0}).optional()}),zm=C({...oo.shape,...Ko.shape,uri:d(),description:le(d()),mimeType:le(d()),annotations:so.optional(),_meta:le(it({}))}),nT=C({...oo.shape,...Ko.shape,uriTemplate:d(),description:le(d()),mimeType:le(d()),annotations:so.optional(),_meta:le(it({}))}),oT=Yo.extend({method:R("resources/list")}),Fm=Qo.extend({resources:q(zm)}),sT=Yo.extend({method:R("resources/templates/list")}),Vm=Qo.extend({resourceTemplates:q(nT)}),uc=Jt.extend({uri:d()}),aT=uc,iT=xt.extend({method:R("resources/read"),params:aT}),Zm=Et.extend({contents:q(oe([Dm,Um]))}),dc=tr.extend({method:R("notifications/resources/list_changed"),params:er.optional()}),lT=uc,cT=xt.extend({method:R("resources/subscribe"),params:lT}),uT=uc,dT=xt.extend({method:R("resources/unsubscribe"),params:uT}),pT=er.extend({uri:d()}),Bm=tr.extend({method:R("notifications/resources/updated"),params:pT}),fT=C({name:d(),description:le(d()),required:le(pe())}),hT=C({...oo.shape,...Ko.shape,description:le(d()),arguments:le(q(fT)),_meta:le(it({}))}),mT=Yo.extend({method:R("prompts/list")}),Hm=Qo.extend({prompts:q(hT)}),gT=Jt.extend({name:d(),arguments:ge(d(),d()).optional()}),yT=xt.extend({method:R("prompts/get"),params:gT}),pc=C({type:R("text"),text:d(),annotations:so.optional(),_meta:ge(d(),$e()).optional()}),fc=C({type:R("image"),data:cc,mimeType:d(),annotations:so.optional(),_meta:ge(d(),$e()).optional()}),hc=C({type:R("audio"),data:cc,mimeType:d(),annotations:so.optional(),_meta:ge(d(),$e()).optional()}),_T=C({type:R("tool_use"),name:d(),id:d(),input:ge(d(),$e()),_meta:ge(d(),$e()).optional()}),vT=C({type:R("resource"),resource:oe([Dm,Um]),annotations:so.optional(),_meta:ge(d(),$e()).optional()}),wT=zm.extend({type:R("resource_link")}),mc=oe([pc,fc,hc,wT,vT]),bT=C({role:ts,content:mc}),Jm=Et.extend({description:d().optional(),messages:q(bT)}),gc=tr.extend({method:R("notifications/prompts/list_changed"),params:er.optional()}),kT=C({title:d().optional(),readOnlyHint:pe().optional(),destructiveHint:pe().optional(),idempotentHint:pe().optional(),openWorldHint:pe().optional()}),CT=C({taskSupport:fe(["required","optional","forbidden"]).optional()}),Gm=C({...oo.shape,...Ko.shape,description:d().optional(),inputSchema:C({type:R("object"),properties:ge(d(),It).optional(),required:q(d()).optional()}).catchall($e()),outputSchema:C({type:R("object"),properties:ge(d(),It).optional(),required:q(d()).optional()}).catchall($e()).optional(),annotations:kT.optional(),execution:CT.optional(),_meta:ge(d(),$e()).optional()}),TT=Yo.extend({method:R("tools/list")}),Wm=Qo.extend({tools:q(Gm)}),rs=Et.extend({content:q(mc).default([]),structuredContent:ge(d(),$e()).optional(),isError:pe().optional()});rs.or(Et.extend({toolResult:$e()}));const ST=Go.extend({name:d(),arguments:ge(d(),$e()).optional()}),IT=xt.extend({method:R("tools/call"),params:ST}),yc=tr.extend({method:R("notifications/tools/list_changed"),params:er.optional()}),xT=C({autoRefresh:pe().default(!0),debounceMs:j().int().nonnegative().default(300)}),Km=fe(["debug","info","notice","warning","error","critical","alert","emergency"]),ET=Jt.extend({level:Km}),$T=xt.extend({method:R("logging/setLevel"),params:ET}),RT=er.extend({level:Km,logger:d().optional(),data:$e()}),Ym=tr.extend({method:R("notifications/message"),params:RT}),PT=C({name:d().optional()}),NT=C({hints:q(PT).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),MT=C({mode:fe(["auto","required","none"]).optional()}),OT=C({type:R("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(mc).default([]),structuredContent:C({}).loose().optional(),isError:pe().optional(),_meta:ge(d(),$e()).optional()}),AT=De("type",[pc,fc,hc]),ha=De("type",[pc,fc,hc,_T,OT]),qT=C({role:ts,content:oe([ha,q(ha)]),_meta:ge(d(),$e()).optional()}),LT=Go.extend({messages:q(qT),modelPreferences:NT.optional(),systemPrompt:d().optional(),includeContext:fe(["none","thisServer","allServers"]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:q(d()).optional(),metadata:It.optional(),tools:q(Gm).optional(),toolChoice:MT.optional()}),_c=xt.extend({method:R("sampling/createMessage"),params:LT}),vc=Et.extend({model:d(),stopReason:le(fe(["endTurn","stopSequence","maxTokens"]).or(d())),role:ts,content:AT}),Qm=Et.extend({model:d(),stopReason:le(fe(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:ts,content:oe([ha,q(ha)])}),jT=C({type:R("boolean"),title:d().optional(),description:d().optional(),default:pe().optional()}),DT=C({type:R("string"),title:d().optional(),description:d().optional(),minLength:j().optional(),maxLength:j().optional(),format:fe(["email","uri","date","date-time"]).optional(),default:d().optional()}),UT=C({type:fe(["number","integer"]),title:d().optional(),description:d().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),zT=C({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),FT=C({type:R("string"),title:d().optional(),description:d().optional(),oneOf:q(C({const:d(),title:d()})),default:d().optional()}),VT=C({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),ZT=oe([zT,FT]),BT=C({type:R("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:C({type:R("string"),enum:q(d())}),default:q(d()).optional()}),HT=C({type:R("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:C({anyOf:q(C({const:d(),title:d()}))}),default:q(d()).optional()}),JT=oe([BT,HT]),GT=oe([VT,ZT,JT]),WT=oe([GT,jT,DT,UT]),KT=Go.extend({mode:R("form").optional(),message:d(),requestedSchema:C({type:R("object"),properties:ge(d(),WT),required:q(d()).optional()})}),YT=Go.extend({mode:R("url"),message:d(),elicitationId:d(),url:d().url()}),QT=oe([KT,YT]),wc=xt.extend({method:R("elicitation/create"),params:QT}),XT=er.extend({elicitationId:d()}),eS=tr.extend({method:R("notifications/elicitation/complete"),params:XT}),bc=Et.extend({action:fe(["accept","decline","cancel"]),content:Fp(e=>e===null?void 0:e,ge(d(),oe([d(),j(),pe(),q(d())])).optional())}),tS=C({type:R("ref/resource"),uri:d()}),rS=C({type:R("ref/prompt"),name:d()}),nS=Jt.extend({ref:oe([rS,tS]),argument:C({name:d(),value:d()}),context:C({arguments:ge(d(),d()).optional()}).optional()}),oS=xt.extend({method:R("completion/complete"),params:nS}),Xm=Et.extend({completion:it({values:q(d()).max(100),total:le(j().int()),hasMore:le(pe())})}),sS=C({uri:d().startsWith("file://"),name:d().optional(),_meta:ge(d(),$e()).optional()}),e2=xt.extend({method:R("roots/list"),params:Jt.optional()}),t2=Et.extend({roots:q(sS)}),aS=tr.extend({method:R("notifications/roots/list_changed"),params:er.optional()});oe([tc,GC,oS,$T,yT,mT,oT,sT,iT,cT,dT,IT,TT,nc,sc,ac,lc]),oe([ec,rc,Lm,aS,fa]),oe([Rn,vc,Qm,bc,t2,oc,ic,es]),oe([tc,_c,wc,e2,nc,sc,ac,lc]),oe([ec,rc,Ym,Bm,dc,yc,gc,fa,eS]),oe([Rn,qm,Xm,Jm,Hm,Fm,Vm,Zm,rs,Wm,oc,ic,es]);class ke extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===Ee.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new iS(o.elicitations,r)}return new ke(t,r,n)}}class iS extends ke{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(Ee.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const $t=_b().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vp.custom,message:"URL must be parseable",fatal:!0}),Fd}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),lS=it({resource:d().url(),authorization_servers:q($t).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:pe().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:pe().optional()}),r2=it({issuer:d(),authorization_endpoint:$t,token_endpoint:$t,registration_endpoint:$t.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),service_documentation:$t.optional(),revocation_endpoint:$t.optional(),revocation_endpoint_auth_methods_supported:q(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:q(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(d()).optional(),code_challenge_methods_supported:q(d()).optional(),client_id_metadata_document_supported:pe().optional()}),cS=it({issuer:d(),authorization_endpoint:$t,token_endpoint:$t,userinfo_endpoint:$t.optional(),jwks_uri:$t,registration_endpoint:$t.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),acr_values_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),id_token_encryption_alg_values_supported:q(d()).optional(),id_token_encryption_enc_values_supported:q(d()).optional(),userinfo_signing_alg_values_supported:q(d()).optional(),userinfo_encryption_alg_values_supported:q(d()).optional(),userinfo_encryption_enc_values_supported:q(d()).optional(),request_object_signing_alg_values_supported:q(d()).optional(),request_object_encryption_alg_values_supported:q(d()).optional(),request_object_encryption_enc_values_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),display_values_supported:q(d()).optional(),claim_types_supported:q(d()).optional(),claims_supported:q(d()).optional(),service_documentation:d().optional(),claims_locales_supported:q(d()).optional(),ui_locales_supported:q(d()).optional(),claims_parameter_supported:pe().optional(),request_parameter_supported:pe().optional(),request_uri_parameter_supported:pe().optional(),require_request_uri_registration:pe().optional(),op_policy_uri:$t.optional(),op_tos_uri:$t.optional(),client_id_metadata_document_supported:pe().optional()}),uS=C({...cS.shape,...r2.pick({code_challenge_methods_supported:!0}).shape}),dS=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Zp().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),pS=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),n2=$t.optional().or(R("").transform(()=>{})),fS=C({redirect_uris:q($t),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:$t.optional(),logo_uri:n2,scope:d().optional(),contacts:q(d()).optional(),tos_uri:n2,policy_uri:d().optional(),jwks_uri:$t.optional(),jwks:wt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),hS=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),mS=fS.merge(hS);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function gS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function yS({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class bt extends Error{constructor(t,r){super(t),this.errorUri=r,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 kc extends bt{}kc.errorCode="invalid_request";class ma extends bt{}ma.errorCode="invalid_client";class ga extends bt{}ga.errorCode="invalid_grant";class ya extends bt{}ya.errorCode="unauthorized_client";class Cc extends bt{}Cc.errorCode="unsupported_grant_type";class Tc extends bt{}Tc.errorCode="invalid_scope";class Sc extends bt{}Sc.errorCode="access_denied";class ao extends bt{}ao.errorCode="server_error";class Ic extends bt{}Ic.errorCode="temporarily_unavailable";class xc extends bt{}xc.errorCode="unsupported_response_type";class Ec extends bt{}Ec.errorCode="unsupported_token_type";class $c extends bt{}$c.errorCode="invalid_token";class Rc extends bt{}Rc.errorCode="method_not_allowed";class Pc extends bt{}Pc.errorCode="too_many_requests";class _a extends bt{}_a.errorCode="invalid_client_metadata";class Nc extends bt{}Nc.errorCode="insufficient_scope";class Mc extends bt{}Mc.errorCode="invalid_target";const _S={[kc.errorCode]:kc,[ma.errorCode]:ma,[ga.errorCode]:ga,[ya.errorCode]:ya,[Cc.errorCode]:Cc,[Tc.errorCode]:Tc,[Sc.errorCode]:Sc,[ao.errorCode]:ao,[Ic.errorCode]:Ic,[xc.errorCode]:xc,[Ec.errorCode]:Ec,[$c.errorCode]:$c,[Rc.errorCode]:Rc,[Pc.errorCode]:Pc,[_a.errorCode]:_a,[Nc.errorCode]:Nc,[Mc.errorCode]:Mc};class rr extends Error{constructor(t){super(t??"Unauthorized")}}function vS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Oc="code",Ac="S256";function wS(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&vS(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function bS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":kS(o,s,r);return;case"client_secret_post":CS(o,s,n);return;case"none":TS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function kS(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function CS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function TS(e,t){t.set("client_id",e)}async function o2(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=pS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=_S[o]||ao;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ao(o)}}async function Pn(e,t){try{return await qc(e,t)}catch(r){if(r instanceof ma||r instanceof ya)return await e.invalidateCredentials?.("all"),await qc(e,t);if(r instanceof ga)return await e.invalidateCredentials?.("tokens"),await qc(e,t);throw r}}async function qc(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await xS(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const l=await IS(t,e,a),c=await NS(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const y=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!SS(w))throw new _a(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(y&&w)u={client_id:w},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const h=await LS(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(h),u=h}}const m=!e.redirectUrl;if(r!==void 0||m){const y=await qS(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const y=await AS(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof bt)||y instanceof ao))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:v}=await MS(i,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(g),"REDIRECT"}function SS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function IS(e,t,r){const n=gS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!yS({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function va(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Lc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=Lc(e,"scope")||void 0,i=Lc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function Lc(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function xS(e,t,r=fetch){const n=await RS(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return lS.parse(await n.json())}async function jc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?jc(e,void 0,r):void 0;throw n}}function ES(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function s2(e,t,r=fetch){return await jc(e,{"MCP-Protocol-Version":t},r)}function $S(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function RS(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??ua;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=ES(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await s2(a,s,r);if(!n?.metadataUrl&&$S(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await s2(l,s,r)}return i}function PS(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function NS(e,{fetchFn:t=fetch,protocolVersion:r=ua}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=PS(e);for(const{url:s,type:a}of o){const i=await jc(s,n,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?r2.parse(await i.json()):uS.parse(await i.json())}}}async function MS(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Oc))throw new Error(`Incompatible auth server: does not support response type ${Oc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ac))throw new Error(`Incompatible auth server: does not support code challenge method ${Ac}`)}else i=new URL("/authorize",e);const l=await im(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Oc),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Ac),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function OS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function a2(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,i,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],m=wS(n,u);bS(m,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await o2(c);return dS.parse(await c.json())}async function AS(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await a2(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function qS(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();i=OS(o,c,e.redirectUrl)}const l=await e.clientInformation();return a2(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function LS(e,{metadata:t,clientMetadata:r,fetchFn:n}){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(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await o2(s);return mS.parse(await s.json())}const jS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class io extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class wa{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Rm(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??jS}async _authThenStart(){if(!this._authProvider)throw new rr("No auth provider");let t;try{t=await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new rr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=ca(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){const{resumptionToken:r}=t;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new io(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Jn({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:g}=await u.read();if(g)break;if(f.id&&(a=f.id,i=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const v=$n.parse(JSON.parse(f.data));Wo(v)&&(l=!0,s!==void 0&&(v.id=s)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}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 rr("No auth provider");if(await Pn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Yl(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),l=i.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!i.ok){const p=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new io(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:g}=va(i);if(this._resourceMetadataUrl=f,this._scope=g,await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:g,error:v}=va(i);if(v==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new io(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new rr;return this.send(t)}}throw new io(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),KC(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,m=i.headers.get("content-type");if(u)if(m?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(m?.includes("application/json")){const p=await i.json(),f=Array.isArray(p)?p.map(g=>$n.parse(g)):[$n.parse(p)];for(const g of f)this.onmessage?.(g)}else throw await i.body?.cancel(),new io(-1,`Unexpected content type: ${m}`);else await i.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new io(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class ba{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new ba,r=new ba;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}var Dc=C({error:C({message:d(),type:d().nullish(),param:wt().nullish(),code:oe([d(),j()]).nullish()})}),dr=nn({errorSchema:Dc,errorToMessage:e=>e.error.message});function i2(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=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"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function l2(e){var t,r,n,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const i=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:i,noCache:i-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function DS({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map((i,l)=>{var c,u,m;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const p=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${p};base64,${Yn(i.data)}`,detail:(u=(c=i.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new br({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Yn(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Yn(i.data),format:"mp3"}};default:throw new br({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new br({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(m=i.filename)!=null?m:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Yn(i.data)}`}}}else throw new br({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const l=[];for(const c of a)switch(c.type){case"text":{i+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}n.push({role:"assistant",content:i,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const i of a){if(i.type==="tool-approval-response")continue;const l=i.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:i.toolCallId,content:c})}break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:o}}function Uc({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function c2(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var US=be(()=>we(C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({message:C({role:R("assistant").nullish(),content:d().nullish(),tool_calls:q(C({id:d().nullish(),type:R("function"),function:C({name:d(),arguments:d()})})).nullish(),annotations:q(C({type:R("url_citation"),url_citation:C({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}),index:j(),logprobs:C({content:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:C({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:C({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),zS=be(()=>we(oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({delta:C({role:fe(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(C({index:j(),id:d().nullish(),type:R("function").nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(C({type:R("url_citation"),url_citation:C({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:C({content:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:j()})),usage:C({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:C({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Dc]))),FS=be(()=>we(C({logitBias:ge(Zp(),j()).optional(),logprobs:oe([pe(),j()]).optional(),parallelToolCalls:pe().optional(),user:d().optional(),reasoningEffort:fe(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:pe().optional(),metadata:ge(d().max(64),d().max(512)).optional(),prediction:ge(d(),wt()).optional(),serviceTier:fe(["auto","flex","priority","default"]).optional(),strictJsonSchema:pe().optional(),textVerbosity:fe(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:fe(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:fe(["system","developer","remove"]).optional(),forceReasoning:pe().optional()})));function VS({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new br({functionality:`tool choice type: ${s}`})}}}var ZS=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:m,providerOptions:p}){var f,g,v,y,w;const _=[],h=(f=await Mr({provider:"openai",providerOptions:p,schema:FS}))!=null?f:{},T=i2(this.modelId),k=(g=h.forceReasoning)!=null?g:T.isReasoningModel;o!=null&&_.push({type:"unsupported",feature:"topK"});const{messages:b,warnings:S}=DS({prompt:e,systemMessageMode:(v=h.systemMessageMode)!=null?v:k?"developer":T.systemMessageMode});_.push(...S);const x=(y=h.strictJsonSchema)!=null?y:!0,I={model:this.modelId,logit_bias:h.logitBias,logprobs:h.logprobs===!0||typeof h.logprobs=="number"?!0:void 0,top_logprobs:typeof h.logprobs=="number"?h.logprobs:typeof h.logprobs=="boolean"&&h.logprobs?0:void 0,user:h.user,parallel_tool_calls:h.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:x,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:h.textVerbosity,max_completion_tokens:h.maxCompletionTokens,store:h.store,metadata:h.metadata,prediction:h.prediction,reasoning_effort:h.reasoningEffort,service_tier:h.serviceTier,prompt_cache_key:h.promptCacheKey,prompt_cache_retention:h.promptCacheRetention,safety_identifier:h.safetyIdentifier,messages:b};k?((h.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(I.temperature!=null&&(I.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,_.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,_.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,_.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&I.temperature!=null&&(I.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),h.serviceTier==="flex"&&!T.supportsFlexProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),h.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),I.service_tier=void 0);const{tools:L,toolChoice:$,toolWarnings:O}=VS({tools:u,toolChoice:m});return{args:{...I,tools:L,tool_choice:$},warnings:[..._,...O]}}async doGenerate(e){var t,r,n,o,s,a,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:m,rawValue:p}=await Ut({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:l,failedResponseHandler:dr,successfulResponseHandler:Xt(US),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=m.choices[0],g=[],v=f.message.content;v!=null&&v.length>0&&g.push({type:"text",text:v});for(const _ of(t=f.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(r=_.id)!=null?r:At(),toolName:_.function.name,input:_.function.arguments});for(const _ of(n=f.message.annotations)!=null?n:[])g.push({type:"source",sourceType:"url",id:At(),url:_.url_citation.url,title:_.url_citation.title});const y=(o=m.usage)==null?void 0:o.completion_tokens_details;(s=m.usage)==null||s.prompt_tokens_details;const w={openai:{}};return y?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=y?.accepted_prediction_tokens),y?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=y?.rejected_prediction_tokens),((a=f.logprobs)==null?void 0:a.content)!=null&&(w.openai.logprobs=f.logprobs.content),{content:g,finishReason:{unified:c2(f.finish_reason),raw:(i=f.finish_reason)!=null?i:void 0},usage:l2(m.usage),request:{body:l},response:{...Uc(m),headers:u,body:p},warnings:c,providerMetadata:w}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Ut({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:n,failedResponseHandler:dr,successfulResponseHandler:Bs(zS),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const m={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,f){var g,v,y,w,_,h,T,k,b,S,x,I,L,$,O,A,U;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const Z=p.value;if("error"in Z){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:Z.error});return}if(!c){const X=Uc(Z);Object.values(X).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Uc(Z)}))}Z.usage!=null&&(l=Z.usage,((g=Z.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(m.openai.acceptedPredictionTokens=(v=Z.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens),((y=Z.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(m.openai.rejectedPredictionTokens=(w=Z.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const Y=Z.choices[0];if(Y?.finish_reason!=null&&(i={unified:c2(Y.finish_reason),raw:Y.finish_reason}),((_=Y?.logprobs)==null?void 0:_.content)!=null&&(m.openai.logprobs=Y.logprobs.content),Y?.delta==null)return;const ye=Y.delta;if(ye.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:ye.content})),ye.tool_calls!=null)for(const X of ye.tool_calls){const he=X.index;if(a[he]==null){if(X.type!=null&&X.type!=="function")throw new Di({data:X,message:"Expected 'function' type."});if(X.id==null)throw new Di({data:X,message:"Expected 'id' to be a string."});if(((h=X.function)==null?void 0:h.name)==null)throw new Di({data:X,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),a[he]={id:X.id,type:"function",function:{name:X.function.name,arguments:(T=X.function.arguments)!=null?T:""},hasFinished:!1};const N=a[he];((k=N.function)==null?void 0:k.name)!=null&&((b=N.function)==null?void 0:b.arguments)!=null&&(N.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:N.id,delta:N.function.arguments}),Rf(N.function.arguments)&&(f.enqueue({type:"tool-input-end",id:N.id}),f.enqueue({type:"tool-call",toolCallId:(S=N.id)!=null?S:At(),toolName:N.function.name,input:N.function.arguments}),N.hasFinished=!0));continue}const B=a[he];B.hasFinished||(((x=X.function)==null?void 0:x.arguments)!=null&&(B.function.arguments+=(L=(I=X.function)==null?void 0:I.arguments)!=null?L:""),f.enqueue({type:"tool-input-delta",id:B.id,delta:($=X.function.arguments)!=null?$:""}),((O=B.function)==null?void 0:O.name)!=null&&((A=B.function)==null?void 0:A.arguments)!=null&&Rf(B.function.arguments)&&(f.enqueue({type:"tool-input-end",id:B.id}),f.enqueue({type:"tool-call",toolCallId:(U=B.id)!=null?U:At(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}if(ye.annotations!=null)for(const X of ye.annotations)f.enqueue({type:"source",sourceType:"url",id:At(),url:X.url_citation.url,title:X.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:l2(l),...m!=null?{providerMetadata:m}:{}})}})),request:{body:n},response:{headers:o}}}};function u2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}function BS({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
70
70
 
71
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new sn({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("");n+=`${t}:
71
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new gn({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("");n+=`${t}:
72
72
  ${a}
73
73
 
74
- `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new dr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
74
+ `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new br({functionality:"tool-call messages"})}}).join("");n+=`${r}:
75
75
  ${a}
76
76
 
77
- `;break}case"tool":throw new dr({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
77
+ `;break}case"tool":throw new br({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
78
78
  `,{prompt:n,stopSequences:[`
79
- ${t}:`]}}function Hm({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Jm(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var R8=Te(()=>be(T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d(),logprobs:T({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(me(d(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),P8=Te(()=>be(oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d().nullish(),index:j(),logprobs:T({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(me(d(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),bc]))),Gm=Te(()=>be(T({echo:fe().optional(),logitBias:me(d(),j()).optional(),suffix:d().optional(),user:d().optional(),logprobs:oe([fe(),j()]).optional()}))),M8=class{constructor(e,t){this.specificationVersion="v3",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:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:g,providerOptions:p}){const h=[],y={...await Cr({provider:"openai",providerOptions:p,schema:Gm}),...await Cr({provider:this.providerOptionsName,providerOptions:p,schema:Gm})};o!=null&&h.push({type:"unsupported",feature:"topK"}),c?.length&&h.push({type:"unsupported",feature:"tools"}),u!=null&&h.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&h.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:w,stopSequences:m}=$8({prompt:e}),b=[...m??[],...i??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,logprobs:y?.logprobs===!0?0:y?.logprobs===!1?void 0:y?.logprobs,suffix:y.suffix,user:y.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:g,prompt:w,stop:b.length>0?b:void 0},warnings:h}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:a}=await Ot({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:r,failedResponseHandler:rr,successfulResponseHandler:Dt(R8),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=s.choices[0],l={openai:{}};return i.logprobs!=null&&(l.openai.logprobs=i.logprobs),{content:[{type:"text",text:i.text}],usage:Bm(s.usage),finishReason:{unified:Jm(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...Hm(s),headers:o,body:a},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Ot({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:n,failedResponseHandler:rr,successfulResponseHandler:Ms(P8),abortSignal:e.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,g){if(e.includeRawChunks&&g.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},g.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},g.enqueue({type:"error",error:p.error});return}c&&(c=!1,g.enqueue({type:"response-metadata",...Hm(p)}),g.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const h=p.choices[0];h?.finish_reason!=null&&(a={unified:Jm(h.finish_reason),raw:h.finish_reason}),h?.logprobs!=null&&(i.openai.logprobs=h.logprobs),h?.text!=null&&h.text.length>0&&g.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:Bm(l)})}})),request:{body:n},response:{headers:o}}}},N8=Te(()=>be(T({dimensions:j().optional(),user:d().optional()}))),O8=Te(()=>be(T({data:q(T({embedding:q(j())})),usage:T({prompt_tokens:j()}).nullish()}))),A8=class{constructor(e,t){this.specificationVersion="v3",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:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new B_({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Cr({provider:"openai",providerOptions:n,schema:N8}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Ot({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:It(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:rr,successfulResponseHandler:Dt(O8),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},Wm=Te(()=>be(T({created:j().nullish(),data:q(T({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:T({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:T({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),q8={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},L8=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function j8(e){return L8.some(t=>e.startsWith(t))}var U8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=q8[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:s,seed:a,providerOptions:i,headers:l,abortSignal:c}){var u,g,p,h,y,w,m,b,_,f,C;const k=[];s!=null&&k.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&k.push({type:"unsupported",feature:"seed"});const v=(p=(g=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:g.call(u))!=null?p:new Date;if(t!=null){const{value:E,responseHeaders:D}=await hf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:It(this.config.headers(),l),formData:v3({model:this.modelId,prompt:e,image:await Promise.all(t.map(M=>M.type==="file"?new Blob([M.data instanceof Uint8Array?new Blob([M.data],{type:M.mediaType}):new Blob([zn(M.data)],{type:M.mediaType})],{type:M.mediaType}):tf(M.url))),mask:r!=null?await D8(r):void 0,n,size:o,...(h=i.openai)!=null?h:{}}),failedResponseHandler:rr,successfulResponseHandler:Dt(Wm),abortSignal:c,fetch:this.config.fetch});return{images:E.data.map(M=>M.b64_json),warnings:k,usage:E.usage!=null?{inputTokens:(y=E.usage.input_tokens)!=null?y:void 0,outputTokens:(w=E.usage.output_tokens)!=null?w:void 0,totalTokens:(m=E.usage.total_tokens)!=null?m:void 0}:void 0,response:{timestamp:v,modelId:this.modelId,headers:D},providerMetadata:{openai:{images:E.data.map(M=>{var N,O,L,K,H;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(N=E.created)!=null?N:void 0,size:(O=E.size)!=null?O:void 0,quality:(L=E.quality)!=null?L:void 0,background:(K=E.background)!=null?K:void 0,outputFormat:(H=E.output_format)!=null?H:void 0}})}}}}const{value:S,responseHeaders:$}=await Ot({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:It(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(b=i.openai)!=null?b:{},...j8(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:rr,successfulResponseHandler:Dt(Wm),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(E=>E.b64_json),warnings:k,usage:S.usage!=null?{inputTokens:(_=S.usage.input_tokens)!=null?_:void 0,outputTokens:(f=S.usage.output_tokens)!=null?f:void 0,totalTokens:(C=S.usage.total_tokens)!=null?C:void 0}:void 0,response:{timestamp:v,modelId:this.modelId,headers:$},providerMetadata:{openai:{images:S.data.map(E=>{var D,M,N,O,L;return{...E.revised_prompt?{revisedPrompt:E.revised_prompt}:{},created:(D=S.created)!=null?D:void 0,size:(M=S.size)!=null?M:void 0,quality:(N=S.quality)!=null?N:void 0,background:(O=S.background)!=null?O:void 0,outputFormat:(L=S.output_format)!=null?L:void 0}})}}}}};async function D8(e){if(!e)return;if(e.type==="url")return tf(e.url);const t=e.data instanceof Uint8Array?e.data:zn(e.data);return new Blob([t],{type:e.mediaType})}var Km=Te(()=>be(T({callId:d(),operation:Qe("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}))),Ym=Te(()=>be(T({status:Se(["completed","failed"]),output:d().optional()}))),z8=er({id:"openai.apply_patch",inputSchema:Km,outputSchema:Ym}),F8=z8,V8=Te(()=>be(T({code:d().nullish(),containerId:d()}))),Z8=Te(()=>be(T({outputs:q(Qe("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullish()}))),B8=Te(()=>be(T({container:oe([d(),T({fileIds:q(d()).optional()})]).optional()}))),H8=er({id:"openai.code_interpreter",inputSchema:V8,outputSchema:Z8}),J8=(e={})=>H8(e),Qm=T({key:d(),type:Se(["eq","ne","gt","gte","lt","lte","in","nin"]),value:oe([d(),j(),fe(),q(d())])}),Xm=T({type:Se(["and","or"]),filters:q(oe([Qm,Oi(()=>Xm)]))}),G8=Te(()=>be(T({vectorStoreIds:q(d()),maxNumResults:j().optional(),ranking:T({ranker:d().optional(),scoreThreshold:j().optional()}).optional(),filters:oe([Qm,Xm]).optional()}))),W8=Te(()=>be(T({queries:q(d()),results:q(T({attributes:me(d(),Me()),fileId:d(),filename:d(),score:j(),text:d()})).nullable()}))),K8=er({id:"openai.file_search",inputSchema:T({}),outputSchema:W8}),Y8=Te(()=>be(T({background:Se(["auto","opaque","transparent"]).optional(),inputFidelity:Se(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:Se(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Se(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Se(["auto","low","medium","high"]).optional(),size:Se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),Q8=Te(()=>be(T({}))),X8=Te(()=>be(T({result:d()}))),eS=er({id:"openai.image_generation",inputSchema:Q8,outputSchema:X8}),tS=(e={})=>eS(e),e2=Te(()=>be(T({action:T({type:P("exec"),command:q(d()),timeoutMs:j().optional(),user:d().optional(),workingDirectory:d().optional(),env:me(d(),d()).optional()})}))),t2=Te(()=>be(T({output:d()}))),rS=er({id:"openai.local_shell",inputSchema:e2,outputSchema:t2}),r2=Te(()=>be(T({action:T({commands:q(d()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),n2=Te(()=>be(T({output:q(T({stdout:d(),stderr:d(),outcome:Qe("type",[T({type:P("timeout")}),T({type:P("exit"),exitCode:j()})])}))}))),nS=er({id:"openai.shell",inputSchema:r2,outputSchema:n2}),oS=Te(()=>be(T({externalWebAccess:fe().optional(),filters:T({allowedDomains:q(d()).optional()}).optional(),searchContextSize:Se(["low","medium","high"]).optional(),userLocation:T({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),sS=Te(()=>be(T({}))),aS=Te(()=>be(T({action:Qe("type",[T({type:P("search"),query:d().optional()}),T({type:P("openPage"),url:d().nullish()}),T({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]),sources:q(Qe("type",[T({type:P("url"),url:d()}),T({type:P("api"),name:d()})])).optional()}))),iS=er({id:"openai.web_search",inputSchema:sS,outputSchema:aS}),lS=(e={})=>iS(e),cS=Te(()=>be(T({searchContextSize:Se(["low","medium","high"]).optional(),userLocation:T({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),uS=Te(()=>be(T({}))),dS=Te(()=>be(T({action:Qe("type",[T({type:P("search"),query:d().optional()}),T({type:P("openPage"),url:d().nullish()}),T({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})])}))),pS=er({id:"openai.web_search_preview",inputSchema:uS,outputSchema:dS}),Cc=Oi(()=>oe([d(),j(),fe(),Ts(),q(Cc),me(d(),Cc)])),fS=Te(()=>be(T({serverLabel:d(),allowedTools:oe([q(d()),T({readOnly:fe().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:me(d(),d()).optional(),requireApproval:oe([Se(["always","never"]),T({never:T({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),hS=Te(()=>be(T({}))),mS=Te(()=>be(T({type:P("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:oe([d(),Cc]).optional()}))),gS=er({id:"openai.mcp",inputSchema:hS,outputSchema:mS}),yS=e=>gS(e),_S={applyPatch:F8,codeInterpreter:J8,fileSearch:K8,imageGeneration:tS,localShell:rS,shell:nS,webSearchPreview:pS,webSearch:lS,mcp:yS};function o2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,i=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-i,cacheRead:i,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}function s2(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function vS({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var u,g,p,h,y,w,m,b,_,f,C,k,v;const S=[],$=[],E=new Set;for(const{role:D,content:M}of e)switch(D){case"system":{switch(r){case"system":{S.push({role:"system",content:M});break}case"developer":{S.push({role:"developer",content:M});break}case"remove":{$.push({type:"other",message:"system messages are removed for this model"});break}default:{const N=r;throw new Error(`Unsupported system message mode: ${N}`)}}break}case"user":{S.push({role:"user",content:M.map((N,O)=>{var L,K,H;switch(N.type){case"text":return{type:"input_text",text:N.text};case"file":if(N.mediaType.startsWith("image/")){const le=N.mediaType==="image/*"?"image/jpeg":N.mediaType;return{type:"input_image",...N.data instanceof URL?{image_url:N.data.toString()}:typeof N.data=="string"&&s2(N.data,o)?{file_id:N.data}:{image_url:`data:${le};base64,${Vn(N.data)}`},detail:(K=(L=N.providerOptions)==null?void 0:L[n])==null?void 0:K.imageDetail}}else{if(N.mediaType==="application/pdf")return N.data instanceof URL?{type:"input_file",file_url:N.data.toString()}:{type:"input_file",...typeof N.data=="string"&&s2(N.data,o)?{file_id:N.data}:{filename:(H=N.filename)!=null?H:`part-${O}.pdf`,file_data:`data:application/pdf;base64,${Vn(N.data)}`}};throw new dr({functionality:`file part media type ${N.mediaType}`})}}})});break}case"assistant":{const N={};for(const O of M)switch(O.type){case"text":{const L=(g=(u=O.providerOptions)==null?void 0:u[n])==null?void 0:g.itemId;if(a&&L!=null)break;if(s&&L!=null){S.push({type:"item_reference",id:L});break}S.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:L});break}case"tool-call":{const L=(m=(h=(p=O.providerOptions)==null?void 0:p[n])==null?void 0:h.itemId)!=null?m:(w=(y=O.providerMetadata)==null?void 0:y[n])==null?void 0:w.itemId;if(a&&L!=null)break;if(O.providerExecuted){s&&L!=null&&S.push({type:"item_reference",id:L});break}if(s&&L!=null){S.push({type:"item_reference",id:L});break}const K=t.toProviderToolName(O.toolName);if(i&&K==="local_shell"){const H=await Rt({value:O.input,schema:e2});S.push({type:"local_shell_call",call_id:O.toolCallId,id:L,action:{type:"exec",command:H.action.command,timeout_ms:H.action.timeoutMs,user:H.action.user,working_directory:H.action.workingDirectory,env:H.action.env}});break}if(l&&K==="shell"){const H=await Rt({value:O.input,schema:r2});S.push({type:"shell_call",call_id:O.toolCallId,id:L,status:"completed",action:{commands:H.action.commands,timeout_ms:H.action.timeoutMs,max_output_length:H.action.maxOutputLength}});break}if(c&&K==="apply_patch"){const H=await Rt({value:O.input,schema:Km});S.push({type:"apply_patch_call",call_id:H.callId,id:L,status:"completed",operation:H.operation});break}S.push({type:"function_call",call_id:O.toolCallId,name:K,arguments:JSON.stringify(O.input),id:L});break}case"tool-result":{if(O.output.type==="execution-denied"||O.output.type==="json"&&typeof O.output.value=="object"&&O.output.value!=null&&"type"in O.output.value&&O.output.value.type==="execution-denied"||a)break;if(s){const L=(f=(_=(b=O.providerMetadata)==null?void 0:b[n])==null?void 0:_.itemId)!=null?f:O.toolCallId;S.push({type:"item_reference",id:L})}else $.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const L=await Cr({provider:n,providerOptions:O.providerOptions,schema:wS}),K=L?.itemId;if(a&&K!=null)break;if(K!=null){const H=N[K];if(s)H===void 0&&(S.push({type:"item_reference",id:K}),N[K]={type:"reasoning",id:K,summary:[]});else{const le=[];O.text.length>0?le.push({type:"summary_text",text:O.text}):H!==void 0&&$.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),H===void 0?(N[K]={type:"reasoning",id:K,encrypted_content:L?.reasoningEncryptedContent,summary:le},S.push(N[K])):(H.summary.push(...le),L?.reasoningEncryptedContent!=null&&(H.encrypted_content=L.reasoningEncryptedContent))}}else $.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(O)}.`});break}}break}case"tool":{for(const N of M){if(N.type==="tool-approval-response"){const H=N;if(E.has(H.approvalId))continue;E.add(H.approvalId),s&&S.push({type:"item_reference",id:H.approvalId}),S.push({type:"mcp_approval_response",approval_request_id:H.approvalId,approve:H.approved});continue}const O=N.output;if(O.type==="execution-denied"&&((k=(C=O.providerOptions)==null?void 0:C.openai)==null?void 0:k.approvalId))continue;const L=t.toProviderToolName(N.toolName);if(i&&L==="local_shell"&&O.type==="json"){const H=await Rt({value:O.value,schema:t2});S.push({type:"local_shell_call_output",call_id:N.toolCallId,output:H.output});continue}if(l&&L==="shell"&&O.type==="json"){const H=await Rt({value:O.value,schema:n2});S.push({type:"shell_call_output",call_id:N.toolCallId,output:H.output.map(le=>({stdout:le.stdout,stderr:le.stderr,outcome:le.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:le.outcome.exitCode}}))});continue}if(c&&N.toolName==="apply_patch"&&O.type==="json"){const H=await Rt({value:O.value,schema:Ym});S.push({type:"apply_patch_call_output",call_id:N.toolCallId,status:H.status,output:H.output});continue}let K;switch(O.type){case"text":case"error-text":K=O.value;break;case"execution-denied":K=(v=O.reason)!=null?v:"Tool execution denied.";break;case"json":case"error-json":K=JSON.stringify(O.value);break;case"content":K=O.value.map(H=>{var le;switch(H.type){case"text":return{type:"input_text",text:H.text};case"image-data":return{type:"input_image",image_url:`data:${H.mediaType};base64,${H.data}`};case"image-url":return{type:"input_image",image_url:H.url};case"file-data":return{type:"input_file",filename:(le=H.filename)!=null?le:"data",file_data:`data:${H.mediaType};base64,${H.data}`};default:{$.push({type:"other",message:`unsupported tool content part type: ${H.type}`});return}}}).filter(I3);break}S.push({type:"function_call_output",call_id:N.toolCallId,output:K})}break}default:{const N=D;throw new Error(`Unsupported role: ${N}`)}}return{input:S,warnings:$}}var wS=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function a2({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var bS=Te(()=>be(oe([T({type:P("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}),T({type:Se(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:P("response.created"),response:T({id:d(),created_at:j(),model:d(),service_tier:d().nullish()})}),T({type:P("response.output_item.added"),output_index:j(),item:Qe("type",[T({type:P("message"),id:d()}),T({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),T({type:P("web_search_call"),id:d(),status:d()}),T({type:P("computer_call"),id:d(),status:d()}),T({type:P("file_search_call"),id:d()}),T({type:P("image_generation_call"),id:d()}),T({type:P("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(Qe("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullable(),status:d()}),T({type:P("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),T({type:P("mcp_list_tools"),id:d()}),T({type:P("mcp_approval_request"),id:d()}),T({type:P("apply_patch_call"),id:d(),call_id:d(),status:Se(["in_progress","completed"]),operation:Qe("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}),T({type:P("shell_call"),id:d(),call_id:d(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:q(d())})})])}),T({type:P("response.output_item.done"),output_index:j(),item:Qe("type",[T({type:P("message"),id:d()}),T({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:P("completed")}),T({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Qe("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullable()}),T({type:P("image_generation_call"),id:d(),result:d()}),T({type:P("web_search_call"),id:d(),status:d(),action:Qe("type",[T({type:P("search"),query:d().nullish(),sources:q(Qe("type",[T({type:P("url"),url:d()}),T({type:P("api"),name:d()})])).nullish()}),T({type:P("open_page"),url:d().nullish()}),T({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),T({type:P("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:me(d(),oe([d(),j(),fe()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),T({type:P("local_shell_call"),id:d(),call_id:d(),action:T({type:P("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:me(d(),d()).optional()})}),T({type:P("computer_call"),id:d(),status:P("completed")}),T({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:ft(),annotations:me(d(),Me()).optional()})),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:P("apply_patch_call"),id:d(),call_id:d(),status:Se(["in_progress","completed"]),operation:Qe("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}),T({type:P("shell_call"),id:d(),call_id:d(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:q(d())})})])}),T({type:P("response.function_call_arguments.delta"),item_id:d(),output_index:j(),delta:d()}),T({type:P("response.image_generation_call.partial_image"),item_id:d(),output_index:j(),partial_image_b64:d()}),T({type:P("response.code_interpreter_call_code.delta"),item_id:d(),output_index:j(),delta:d()}),T({type:P("response.code_interpreter_call_code.done"),item_id:d(),output_index:j(),code:d()}),T({type:P("response.output_text.annotation.added"),annotation:Qe("type",[T({type:P("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),T({type:P("file_citation"),file_id:d(),filename:d(),index:j()}),T({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),T({type:P("file_path"),file_id:d(),index:j()})])}),T({type:P("response.reasoning_summary_part.added"),item_id:d(),summary_index:j()}),T({type:P("response.reasoning_summary_text.delta"),item_id:d(),summary_index:j(),delta:d()}),T({type:P("response.reasoning_summary_part.done"),item_id:d(),summary_index:j()}),T({type:P("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:j(),delta:d(),obfuscation:d().nullish()}),T({type:P("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:j(),diff:d()}),T({type:P("error"),sequence_number:j(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),kS=Te(()=>be(T({id:d().optional(),created_at:j().optional(),error:T({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(Qe("type",[T({type:P("message"),role:P("assistant"),id:d(),content:q(T({type:P("output_text"),text:d(),logprobs:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish(),annotations:q(Qe("type",[T({type:P("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),T({type:P("file_citation"),file_id:d(),filename:d(),index:j()}),T({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),T({type:P("file_path"),file_id:d(),index:j()})]))}))}),T({type:P("web_search_call"),id:d(),status:d(),action:Qe("type",[T({type:P("search"),query:d().nullish(),sources:q(Qe("type",[T({type:P("url"),url:d()}),T({type:P("api"),name:d()})])).nullish()}),T({type:P("open_page"),url:d().nullish()}),T({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),T({type:P("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:me(d(),oe([d(),j(),fe()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),T({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Qe("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullable()}),T({type:P("image_generation_call"),id:d(),result:d()}),T({type:P("local_shell_call"),id:d(),call_id:d(),action:T({type:P("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:me(d(),d()).optional()})}),T({type:P("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),T({type:P("computer_call"),id:d(),status:d().optional()}),T({type:P("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(T({type:P("summary_text"),text:d()}))}),T({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:ft(),annotations:me(d(),Me()).optional()})),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:P("apply_patch_call"),id:d(),call_id:d(),status:Se(["in_progress","completed"]),operation:Qe("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}),T({type:P("shell_call"),id:d(),call_id:d(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:q(d())})})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}).optional()}))),i2=20,l2=Te(()=>be(T({conversation:d().nullish(),include:q(Se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:oe([fe(),j().min(1).max(i2)]).optional(),maxToolCalls:j().nullish(),metadata:ft().nullish(),parallelToolCalls:fe().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:Se(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:Se(["auto","flex","priority","default"]).nullish(),store:fe().nullish(),strictJsonSchema:fe().nullish(),textVerbosity:Se(["low","medium","high"]).nullish(),truncation:Se(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:Se(["system","developer","remove"]).optional(),forceReasoning:fe().optional()})));async function CS({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await Rt({value:s.args,schema:G8});n.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{n.push({type:"local_shell"});break}case"openai.shell":{n.push({type:"shell"});break}case"openai.apply_patch":{n.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await Rt({value:s.args,schema:cS});n.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await Rt({value:s.args,schema:oS});n.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await Rt({value:s.args,schema:B8});n.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await Rt({value:s.args,schema:Y8});n.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await Rt({value:s.args,schema:fS}),i=u=>({tool_names:u.toolNames}),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:i(l.never)}:void 0;n.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:r.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const s=o;throw new dr({functionality:`tool choice type: ${s}`})}}}function c2(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;a!=null&&(n[a]=s.toolCallId)}return n}var TS=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:g,responseFormat:p}){var h,y,w,m,b,_;const f=[],C=Fm(this.modelId);o!=null&&f.push({type:"unsupported",feature:"topK"}),i!=null&&f.push({type:"unsupported",feature:"seed"}),s!=null&&f.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&f.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&f.push({type:"unsupported",feature:"stopSequences"});const k=this.config.provider.includes("azure")?"azure":"openai";let v=await Cr({provider:k,providerOptions:c,schema:l2});v==null&&k!=="openai"&&(v=await Cr({provider:"openai",providerOptions:c,schema:l2}));const S=(h=v?.forceReasoning)!=null?h:C.isReasoningModel;v?.conversation&&v?.previousResponseId&&f.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const $=m3({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:E,warnings:D}=await vS({prompt:l,toolNameMapping:$,systemMessageMode:(y=v?.systemMessageMode)!=null?y:S?"developer":C.systemMessageMode,providerOptionsName:k,fileIdPrefixes:this.config.fileIdPrefixes,store:(w=v?.store)!=null?w:!0,hasConversation:v?.conversation!=null,hasLocalShellTool:L("openai.local_shell"),hasShellTool:L("openai.shell"),hasApplyPatchTool:L("openai.apply_patch")});f.push(...D);const M=(m=v?.strictJsonSchema)!=null?m:!0;let N=v?.include;function O(B){N==null?N=[B]:N.includes(B)||(N=[...N,B])}function L(B){return u?.find(z=>z.type==="provider"&&z.id===B)!=null}const K=typeof v?.logprobs=="number"?v?.logprobs:v?.logprobs===!0?i2:void 0;K&&O("message.output_text.logprobs");const H=(b=u?.find(B=>B.type==="provider"&&(B.id==="openai.web_search"||B.id==="openai.web_search_preview")))==null?void 0:b.name;H&&O("web_search_call.action.sources"),L("openai.code_interpreter")&&O("code_interpreter_call.outputs");const le=v?.store;le===!1&&S&&O("reasoning.encrypted_content");const W={model:this.modelId,input:E,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||v?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:M,name:(_=p.name)!=null?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...v?.textVerbosity&&{verbosity:v.textVerbosity}}},conversation:v?.conversation,max_tool_calls:v?.maxToolCalls,metadata:v?.metadata,parallel_tool_calls:v?.parallelToolCalls,previous_response_id:v?.previousResponseId,store:le,user:v?.user,instructions:v?.instructions,service_tier:v?.serviceTier,include:N,prompt_cache_key:v?.promptCacheKey,prompt_cache_retention:v?.promptCacheRetention,safety_identifier:v?.safetyIdentifier,top_logprobs:K,truncation:v?.truncation,...S&&(v?.reasoningEffort!=null||v?.reasoningSummary!=null)&&{reasoning:{...v?.reasoningEffort!=null&&{effort:v.reasoningEffort},...v?.reasoningSummary!=null&&{summary:v.reasoningSummary}}}};S?v?.reasoningEffort==="none"&&C.supportsNonReasoningParameters||(W.temperature!=null&&(W.temperature=void 0,f.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),W.top_p!=null&&(W.top_p=void 0,f.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(v?.reasoningEffort!=null&&f.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),v?.reasoningSummary!=null&&f.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),v?.serviceTier==="flex"&&!C.supportsFlexProcessing&&(f.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete W.service_tier),v?.serviceTier==="priority"&&!C.supportsPriorityProcessing&&(f.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete W.service_tier);const{tools:Ee,toolChoice:F,toolWarnings:A}=await CS({tools:u,toolChoice:g});return{webSearchToolName:H,args:{...W,tools:Ee,tool_choice:F},warnings:[...f,...A],store:le,toolNameMapping:$,providerOptionsName:k}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,p,h,y,w,m,b,_,f,C,k,v,S,$,E;const{args:D,warnings:M,webSearchToolName:N,toolNameMapping:O,providerOptionsName:L}=await this.getArgs(e),K=this.config.url({path:"/responses",modelId:this.modelId}),H=c2(e.prompt),{responseHeaders:le,value:W,rawValue:Ee}=await Ot({url:K,headers:It(this.config.headers(),e.headers),body:D,failedResponseHandler:rr,successfulResponseHandler:Dt(kS),abortSignal:e.abortSignal,fetch:this.config.fetch});if(W.error)throw new ut({message:W.error.message,url:K,requestBodyValues:D,statusCode:400,responseHeaders:le,responseBody:Ee,isRetryable:!1});const F=[],A=[];let B=!1;for(const x of W.output)switch(x.type){case"reasoning":{x.summary.length===0&&x.summary.push({type:"summary_text",text:""});for(const Z of x.summary)F.push({type:"reasoning",text:Z.text,providerMetadata:{[L]:{itemId:x.id,reasoningEncryptedContent:(t=x.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{F.push({type:"tool-call",toolCallId:x.id,toolName:O.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),F.push({type:"tool-result",toolCallId:x.id,toolName:O.toCustomToolName("image_generation"),result:{result:x.result}});break}case"local_shell_call":{F.push({type:"tool-call",toolCallId:x.call_id,toolName:O.toCustomToolName("local_shell"),input:JSON.stringify({action:x.action}),providerMetadata:{[L]:{itemId:x.id}}});break}case"shell_call":{F.push({type:"tool-call",toolCallId:x.call_id,toolName:O.toCustomToolName("shell"),input:JSON.stringify({action:{commands:x.action.commands}}),providerMetadata:{[L]:{itemId:x.id}}});break}case"message":{for(const Z of x.content){(n=(r=e.providerOptions)==null?void 0:r[L])!=null&&n.logprobs&&Z.logprobs&&A.push(Z.logprobs);const ee={itemId:x.id,...Z.annotations.length>0&&{annotations:Z.annotations}};F.push({type:"text",text:Z.text,providerMetadata:{[L]:ee}});for(const Y of Z.annotations)Y.type==="url_citation"?F.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:Et(),url:Y.url,title:Y.title}):Y.type==="file_citation"?F.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:Et(),mediaType:"text/plain",title:Y.filename,filename:Y.filename,providerMetadata:{[L]:{type:Y.type,fileId:Y.file_id,index:Y.index}}}):Y.type==="container_file_citation"?F.push({type:"source",sourceType:"document",id:(p=(g=(u=this.config).generateId)==null?void 0:g.call(u))!=null?p:Et(),mediaType:"text/plain",title:Y.filename,filename:Y.filename,providerMetadata:{[L]:{type:Y.type,fileId:Y.file_id,containerId:Y.container_id}}}):Y.type==="file_path"&&F.push({type:"source",sourceType:"document",id:(w=(y=(h=this.config).generateId)==null?void 0:y.call(h))!=null?w:Et(),mediaType:"application/octet-stream",title:Y.file_id,filename:Y.file_id,providerMetadata:{[L]:{type:Y.type,fileId:Y.file_id,index:Y.index}}})}break}case"function_call":{B=!0,F.push({type:"tool-call",toolCallId:x.call_id,toolName:x.name,input:x.arguments,providerMetadata:{[L]:{itemId:x.id}}});break}case"web_search_call":{F.push({type:"tool-call",toolCallId:x.id,toolName:O.toCustomToolName(N??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),F.push({type:"tool-result",toolCallId:x.id,toolName:O.toCustomToolName(N??"web_search"),result:d2(x.action)});break}case"mcp_call":{const Z=x.approval_request_id!=null&&(m=H[x.approval_request_id])!=null?m:x.id,ee=`mcp.${x.name}`;F.push({type:"tool-call",toolCallId:Z,toolName:ee,input:x.arguments,providerExecuted:!0,dynamic:!0}),F.push({type:"tool-result",toolCallId:Z,toolName:ee,result:{type:"call",serverLabel:x.server_label,name:x.name,arguments:x.arguments,...x.output!=null?{output:x.output}:{},...x.error!=null?{error:x.error}:{}},providerMetadata:{[L]:{itemId:x.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const Z=(b=x.approval_request_id)!=null?b:x.id,ee=(C=(f=(_=this.config).generateId)==null?void 0:f.call(_))!=null?C:Et(),Y=`mcp.${x.name}`;F.push({type:"tool-call",toolCallId:ee,toolName:Y,input:x.arguments,providerExecuted:!0,dynamic:!0}),F.push({type:"tool-approval-request",approvalId:Z,toolCallId:ee});break}case"computer_call":{F.push({type:"tool-call",toolCallId:x.id,toolName:O.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),F.push({type:"tool-result",toolCallId:x.id,toolName:O.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:x.status||"completed"}});break}case"file_search_call":{F.push({type:"tool-call",toolCallId:x.id,toolName:O.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),F.push({type:"tool-result",toolCallId:x.id,toolName:O.toCustomToolName("file_search"),result:{queries:x.queries,results:(v=(k=x.results)==null?void 0:k.map(Z=>({attributes:Z.attributes,fileId:Z.file_id,filename:Z.filename,score:Z.score,text:Z.text})))!=null?v:null}});break}case"code_interpreter_call":{F.push({type:"tool-call",toolCallId:x.id,toolName:O.toCustomToolName("code_interpreter"),input:JSON.stringify({code:x.code,containerId:x.container_id}),providerExecuted:!0}),F.push({type:"tool-result",toolCallId:x.id,toolName:O.toCustomToolName("code_interpreter"),result:{outputs:x.outputs}});break}case"apply_patch_call":{F.push({type:"tool-call",toolCallId:x.call_id,toolName:O.toCustomToolName("apply_patch"),input:JSON.stringify({callId:x.call_id,operation:x.operation}),providerMetadata:{[L]:{itemId:x.id}}});break}}const z={[L]:{responseId:W.id,...A.length>0?{logprobs:A}:{},...typeof W.service_tier=="string"?{serviceTier:W.service_tier}:{}}},I=W.usage;return{content:F,finishReason:{unified:a2({finishReason:(S=W.incomplete_details)==null?void 0:S.reason,hasFunctionCall:B}),raw:(E=($=W.incomplete_details)==null?void 0:$.reason)!=null?E:void 0},usage:o2(I),request:{body:D},response:{id:W.id,timestamp:new Date(W.created_at*1e3),modelId:W.model,headers:le,body:Ee},providerMetadata:z,warnings:M}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a}=await this.getArgs(e),{responseHeaders:i,value:l}=await Ot({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:rr,successfulResponseHandler:Ms(bS),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=this,u=c2(e.prompt),g=new Map;let p={unified:"other",raw:void 0},h;const y=[];let w=null;const m={},b=[];let _=!1;const f={};let C;return{stream:l.pipeThrough(new TransformStream({start(k){k.enqueue({type:"stream-start",warnings:r})},transform(k,v){var S,$,E,D,M,N,O,L,K,H,le,W,Ee,F,A,B,z,I,x,Z,ee,Y,ye,Ie,U,V,G,Q,ce,ve;if(e.includeRawChunks&&v.enqueue({type:"raw",rawValue:k.rawValue}),!k.success){p={unified:"error",raw:void 0},v.enqueue({type:"error",error:k.error});return}const R=k.value;if(u2(R)){if(R.item.type==="function_call")m[R.output_index]={toolName:R.item.name,toolCallId:R.item.call_id},v.enqueue({type:"tool-input-start",id:R.item.call_id,toolName:R.item.name});else if(R.item.type==="web_search_call")m[R.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:R.item.id},v.enqueue({type:"tool-input-start",id:R.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),v.enqueue({type:"tool-input-end",id:R.item.id}),v.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(R.item.type==="computer_call")m[R.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:R.item.id},v.enqueue({type:"tool-input-start",id:R.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(R.item.type==="code_interpreter_call")m[R.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:R.item.id,codeInterpreter:{containerId:R.item.container_id}},v.enqueue({type:"tool-input-start",id:R.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),v.enqueue({type:"tool-input-delta",id:R.item.id,delta:`{"containerId":"${R.item.container_id}","code":"`});else if(R.item.type==="file_search_call")v.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(R.item.type==="image_generation_call")v.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(R.item.type==="mcp_call"||R.item.type==="mcp_list_tools"||R.item.type==="mcp_approval_request"))if(R.item.type==="apply_patch_call"){const{call_id:re,operation:ge}=R.item;if(m[R.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:re,applyPatch:{hasDiff:ge.type==="delete_file",endEmitted:ge.type==="delete_file"}},v.enqueue({type:"tool-input-start",id:re,toolName:o.toCustomToolName("apply_patch")}),ge.type==="delete_file"){const we=JSON.stringify({callId:re,operation:ge});v.enqueue({type:"tool-input-delta",id:re,delta:we}),v.enqueue({type:"tool-input-end",id:re})}else v.enqueue({type:"tool-input-delta",id:re,delta:`{"callId":"${kn(re)}","operation":{"type":"${kn(ge.type)}","path":"${kn(ge.path)}","diff":"`})}else R.item.type==="shell_call"?m[R.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:R.item.call_id}:R.item.type==="message"?(b.splice(0,b.length),v.enqueue({type:"text-start",id:R.item.id,providerMetadata:{[a]:{itemId:R.item.id}}})):u2(R)&&R.item.type==="reasoning"&&(f[R.item.id]={encryptedContent:R.item.encrypted_content,summaryParts:{0:"active"}},v.enqueue({type:"reasoning-start",id:`${R.item.id}:0`,providerMetadata:{[a]:{itemId:R.item.id,reasoningEncryptedContent:(S=R.item.encrypted_content)!=null?S:null}}}))}else if(IS(R)){if(R.item.type==="message")v.enqueue({type:"text-end",id:R.item.id,providerMetadata:{[a]:{itemId:R.item.id,...b.length>0&&{annotations:b}}}});else if(R.item.type==="function_call")m[R.output_index]=void 0,_=!0,v.enqueue({type:"tool-input-end",id:R.item.call_id}),v.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:R.item.name,input:R.item.arguments,providerMetadata:{[a]:{itemId:R.item.id}}});else if(R.item.type==="web_search_call")m[R.output_index]=void 0,v.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName(n??"web_search"),result:d2(R.item.action)});else if(R.item.type==="computer_call")m[R.output_index]=void 0,v.enqueue({type:"tool-input-end",id:R.item.id}),v.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),v.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:R.item.status||"completed"}});else if(R.item.type==="file_search_call")m[R.output_index]=void 0,v.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:R.item.queries,results:(E=($=R.item.results)==null?void 0:$.map(re=>({attributes:re.attributes,fileId:re.file_id,filename:re.filename,score:re.score,text:re.text})))!=null?E:null}});else if(R.item.type==="code_interpreter_call")m[R.output_index]=void 0,v.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:R.item.outputs}});else if(R.item.type==="image_generation_call")v.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:R.item.result}});else if(R.item.type==="mcp_call"){m[R.output_index]=void 0;const re=(D=R.item.approval_request_id)!=null?D:void 0,ge=re!=null&&(N=(M=g.get(re))!=null?M:u[re])!=null?N:R.item.id,we=`mcp.${R.item.name}`;v.enqueue({type:"tool-call",toolCallId:ge,toolName:we,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),v.enqueue({type:"tool-result",toolCallId:ge,toolName:we,result:{type:"call",serverLabel:R.item.server_label,name:R.item.name,arguments:R.item.arguments,...R.item.output!=null?{output:R.item.output}:{},...R.item.error!=null?{error:R.item.error}:{}},providerMetadata:{[a]:{itemId:R.item.id}}})}else if(R.item.type==="mcp_list_tools")m[R.output_index]=void 0;else if(R.item.type==="apply_patch_call"){const re=m[R.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&R.item.operation.type!=="delete_file"&&(re.applyPatch.hasDiff||v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:kn(R.item.operation.diff)}),v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),v.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0),re&&R.item.status==="completed"&&v.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:R.item.call_id,operation:R.item.operation}),providerMetadata:{[a]:{itemId:R.item.id}}}),m[R.output_index]=void 0}else if(R.item.type==="mcp_approval_request"){m[R.output_index]=void 0;const re=(K=(L=(O=c.config).generateId)==null?void 0:L.call(O))!=null?K:Et(),ge=(H=R.item.approval_request_id)!=null?H:R.item.id;g.set(ge,re);const we=`mcp.${R.item.name}`;v.enqueue({type:"tool-call",toolCallId:re,toolName:we,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),v.enqueue({type:"tool-approval-request",approvalId:ge,toolCallId:re})}else if(R.item.type==="local_shell_call")m[R.output_index]=void 0,v.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:R.item.action.command,timeoutMs:R.item.action.timeout_ms,user:R.item.action.user,workingDirectory:R.item.action.working_directory,env:R.item.action.env}}),providerMetadata:{[a]:{itemId:R.item.id}}});else if(R.item.type==="shell_call")m[R.output_index]=void 0,v.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:R.item.action.commands}}),providerMetadata:{[a]:{itemId:R.item.id}}});else if(R.item.type==="reasoning"){const re=f[R.item.id],ge=Object.entries(re.summaryParts).filter(([we,Re])=>Re==="active"||Re==="can-conclude").map(([we])=>we);for(const we of ge)v.enqueue({type:"reasoning-end",id:`${R.item.id}:${we}`,providerMetadata:{[a]:{itemId:R.item.id,reasoningEncryptedContent:(le=R.item.encrypted_content)!=null?le:null}}});delete f[R.item.id]}}else if($S(R)){const re=m[R.output_index];re!=null&&v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:R.delta})}else if(NS(R)){const re=m[R.output_index];re?.applyPatch&&(v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:kn(R.delta)}),re.applyPatch.hasDiff=!0)}else if(OS(R)){const re=m[R.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&(re.applyPatch.hasDiff||(v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:kn(R.diff)}),re.applyPatch.hasDiff=!0),v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),v.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0)}else if(RS(R))v.enqueue({type:"tool-result",toolCallId:R.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:R.partial_image_b64},preliminary:!0});else if(PS(R)){const re=m[R.output_index];re!=null&&v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:kn(R.delta)})}else if(MS(R)){const re=m[R.output_index];re!=null&&(v.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}'}),v.enqueue({type:"tool-input-end",id:re.toolCallId}),v.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:R.code,containerId:re.codeInterpreter.containerId}),providerExecuted:!0}))}else if(ES(R))w=R.response.id,v.enqueue({type:"response-metadata",id:R.response.id,timestamp:new Date(R.response.created_at*1e3),modelId:R.response.model});else if(SS(R))v.enqueue({type:"text-delta",id:R.item_id,delta:R.delta}),(Ee=(W=e.providerOptions)==null?void 0:W[a])!=null&&Ee.logprobs&&R.logprobs&&y.push(R.logprobs);else if(R.type==="response.reasoning_summary_part.added"){if(R.summary_index>0){const re=f[R.item_id];re.summaryParts[R.summary_index]="active";for(const ge of Object.keys(re.summaryParts))re.summaryParts[ge]==="can-conclude"&&(v.enqueue({type:"reasoning-end",id:`${R.item_id}:${ge}`,providerMetadata:{[a]:{itemId:R.item_id}}}),re.summaryParts[ge]="concluded");v.enqueue({type:"reasoning-start",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[a]:{itemId:R.item_id,reasoningEncryptedContent:(A=(F=f[R.item_id])==null?void 0:F.encryptedContent)!=null?A:null}}})}}else R.type==="response.reasoning_summary_text.delta"?v.enqueue({type:"reasoning-delta",id:`${R.item_id}:${R.summary_index}`,delta:R.delta,providerMetadata:{[a]:{itemId:R.item_id}}}):R.type==="response.reasoning_summary_part.done"?s?(v.enqueue({type:"reasoning-end",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[a]:{itemId:R.item_id}}}),f[R.item_id].summaryParts[R.summary_index]="concluded"):f[R.item_id].summaryParts[R.summary_index]="can-conclude":xS(R)?(p={unified:a2({finishReason:(B=R.response.incomplete_details)==null?void 0:B.reason,hasFunctionCall:_}),raw:(I=(z=R.response.incomplete_details)==null?void 0:z.reason)!=null?I:void 0},h=R.response.usage,typeof R.response.service_tier=="string"&&(C=R.response.service_tier)):AS(R)?(b.push(R.annotation),R.annotation.type==="url_citation"?v.enqueue({type:"source",sourceType:"url",id:(ee=(Z=(x=c.config).generateId)==null?void 0:Z.call(x))!=null?ee:Et(),url:R.annotation.url,title:R.annotation.title}):R.annotation.type==="file_citation"?v.enqueue({type:"source",sourceType:"document",id:(Ie=(ye=(Y=c.config).generateId)==null?void 0:ye.call(Y))!=null?Ie:Et(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[a]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}}):R.annotation.type==="container_file_citation"?v.enqueue({type:"source",sourceType:"document",id:(G=(V=(U=c.config).generateId)==null?void 0:V.call(U))!=null?G:Et(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[a]:{type:R.annotation.type,fileId:R.annotation.file_id,containerId:R.annotation.container_id}}}):R.annotation.type==="file_path"&&v.enqueue({type:"source",sourceType:"document",id:(ve=(ce=(Q=c.config).generateId)==null?void 0:ce.call(Q))!=null?ve:Et(),mediaType:"application/octet-stream",title:R.annotation.file_id,filename:R.annotation.file_id,providerMetadata:{[a]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}})):qS(R)&&v.enqueue({type:"error",error:R})},flush(k){const v={[a]:{responseId:w,...y.length>0?{logprobs:y}:{},...C!==void 0?{serviceTier:C}:{}}};k.enqueue({type:"finish",finishReason:p,usage:o2(h),providerMetadata:v})}})),request:{body:t},response:{headers:i}}}};function SS(e){return e.type==="response.output_text.delta"}function IS(e){return e.type==="response.output_item.done"}function xS(e){return e.type==="response.completed"||e.type==="response.incomplete"}function ES(e){return e.type==="response.created"}function $S(e){return e.type==="response.function_call_arguments.delta"}function RS(e){return e.type==="response.image_generation_call.partial_image"}function PS(e){return e.type==="response.code_interpreter_call_code.delta"}function MS(e){return e.type==="response.code_interpreter_call_code.done"}function NS(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function OS(e){return e.type==="response.apply_patch_call_operation_diff.done"}function u2(e){return e.type==="response.output_item.added"}function AS(e){return e.type==="response.output_text.annotation.added"}function qS(e){return e.type==="error"}function d2(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function kn(e){return JSON.stringify(e).slice(1,-1)}var LS=Te(()=>be(T({instructions:d().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),jS=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await Cr({provider:"openai",providerOptions:a,schema:LS}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const g in u){const p=u[g];p!==void 0&&(c[g]=p)}}return s&&i.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await Ot({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),body:s,failedResponseHandler:rr,successfulResponseHandler:x9(),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:c}}}},US=Te(()=>be(T({text:d(),language:d().nullish(),duration:j().nullish(),words:q(T({word:d(),start:j(),end:j()})).nullish(),segments:q(T({id:j(),seek:j(),start:j(),end:j(),text:d(),tokens:q(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),DS=Te(()=>be(T({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:q(Se(["word","segment"])).default(["segment"]).optional()}))),p2={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"},zS=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await Cr({provider:"openai",providerOptions:r,schema:DS}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([zn(e)]);s.append("model",this.modelId);const i=$3(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const g of u)s.append(`${c}[]`,String(g));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,a,i,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:g}=await this.getArgs(e),{value:p,responseHeaders:h,rawValue:y}=await hf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:It(this.config.headers(),e.headers),formData:u,failedResponseHandler:rr,successfulResponseHandler:Dt(US),abortSignal:e.abortSignal,fetch:this.config.fetch}),w=p.language!=null&&p.language in p2?p2[p.language]:void 0;return{text:p.text,segments:(i=(a=(o=p.segments)==null?void 0:o.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?a:(s=p.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:w,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:g,response:{timestamp:c,modelId:this.modelId,headers:h,body:y}}}},FS="3.0.28";function f2(e={}){var t,r;const n=(t=yf(To({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>Br({Authorization:`Bearer ${E3({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${FS}`),a=w=>new E8(w,{provider:`${o}.chat`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),i=w=>new M8(w,{provider:`${o}.completion`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),l=w=>new A8(w,{provider:`${o}.embedding`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),c=w=>new U8(w,{provider:`${o}.image`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),u=w=>new zS(w,{provider:`${o}.transcription`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),g=w=>new jS(w,{provider:`${o}.speech`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),p=w=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return h(w)},h=w=>new TS(w,{provider:`${o}.responses`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),y=function(w){return p(w)};return y.specificationVersion="v3",y.languageModel=p,y.chat=a,y.completion=i,y.responses=h,y.embedding=l,y.embeddingModel=l,y.textEmbedding=l,y.textEmbeddingModel=l,y.image=c,y.imageModel=c,y.transcription=u,y.transcriptionModel=u,y.speech=g,y.speechModel=g,y.tools=_S,y}f2();var h2="vercel.ai.error",VS=Symbol.for(h2),m2,ZS=class O_ extends Error{constructor({name:t,message:r,cause:n}){super(r),this[m2]=!0,this.name=t,this.cause=n}static isInstance(t){return O_.hasMarker(t,h2)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};m2=VS;var mt=ZS,g2="AI_APICallError",y2=`vercel.ai.error.${g2}`,BS=Symbol.for(y2),_2,Ir=class extends mt{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:g2,message:e,cause:a}),this[_2]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return mt.hasMarker(e,y2)}};_2=BS;var v2="AI_EmptyResponseBodyError",w2=`vercel.ai.error.${v2}`,HS=Symbol.for(w2),b2,JS=class extends mt{constructor({message:e="Empty response body"}={}){super({name:v2,message:e}),this[b2]=!0}static isInstance(e){return mt.hasMarker(e,w2)}};b2=HS;function k2(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var C2="AI_InvalidArgumentError",T2=`vercel.ai.error.${C2}`,GS=Symbol.for(T2),S2,I2=class extends mt{constructor({message:e,cause:t,argument:r}){super({name:C2,message:e,cause:t}),this[S2]=!0,this.argument=r}static isInstance(e){return mt.hasMarker(e,T2)}};S2=GS;var x2="AI_InvalidResponseDataError",E2=`vercel.ai.error.${x2}`,WS=Symbol.for(E2),$2,R2=class extends mt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:x2,message:t}),this[$2]=!0,this.data=e}static isInstance(e){return mt.hasMarker(e,E2)}};$2=WS;var P2="AI_JSONParseError",M2=`vercel.ai.error.${P2}`,KS=Symbol.for(M2),N2,la=class extends mt{constructor({text:e,cause:t}){super({name:P2,message:`JSON parsing failed: Text: ${e}.
80
- Error message: ${k2(t)}`,cause:t}),this[N2]=!0,this.text=e}static isInstance(e){return mt.hasMarker(e,M2)}};N2=KS;var O2="AI_LoadAPIKeyError",A2=`vercel.ai.error.${O2}`,YS=Symbol.for(A2),q2,ca=class extends mt{constructor({message:e}){super({name:O2,message:e}),this[q2]=!0}static isInstance(e){return mt.hasMarker(e,A2)}};q2=YS;var L2="AI_NoSuchModelError",j2=`vercel.ai.error.${L2}`,QS=Symbol.for(j2),U2,D2=class extends mt{constructor({errorName:e=L2,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[U2]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return mt.hasMarker(e,j2)}};U2=QS;var z2="AI_TypeValidationError",F2=`vercel.ai.error.${z2}`,XS=Symbol.for(F2),V2,eI=class Au extends mt{constructor({value:t,cause:r}){super({name:z2,message:`Type validation failed: Value: ${JSON.stringify(t)}.
81
- Error message: ${k2(r)}`,cause:r}),this[V2]=!0,this.value=t}static isInstance(t){return mt.hasMarker(t,F2)}static wrap({value:t,cause:r}){return Au.isInstance(r)&&r.value===t?r:new Au({value:t,cause:r})}};V2=XS;var Wo=eI,Z2="AI_UnsupportedFunctionalityError",B2=`vercel.ai.error.${Z2}`,tI=Symbol.for(B2),H2,J2=class extends mt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Z2,message:t}),this[H2]=!0,this.functionality=e}static isInstance(e){return mt.hasMarker(e,B2)}};H2=tI;function G2(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function ua(e){return Object.fromEntries([...e.headers])}var rI=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new I2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},da=rI();function Tc(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var nI=["fetch failed","failed to fetch"];function oI({error:e,url:t,requestBodyValues:r}){if(Tc(e))return e;if(e instanceof TypeError&&nI.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Ir({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function sI(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function aI(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function W2(e,...t){const r=new Headers(aI(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var iI="3.0.18";function lI({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ca({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ca({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ca({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ca({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var cI=/"__proto__"\s*:/,uI=/"constructor"\s*:/;function K2(e){const t=JSON.parse(e);return t===null||typeof t!="object"||cI.test(e)===!1&&uI.test(e)===!1?t:dI(t)}function dI(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Sc(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return K2(e)}try{return K2(e)}finally{Error.stackTraceLimit=t}}var Ic=Symbol.for("vercel.ai.validator");function pI(e){return{[Ic]:!0,validate:e}}function fI(e){return typeof e=="object"&&e!==null&&Ic in e&&e[Ic]===!0&&"validate"in e}function hI(e){return fI(e)?e:typeof e=="function"?e():mI(e)}function mI(e){return pI(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Wo({value:t,cause:r.issues})}})}async function gI({value:e,schema:t}){const r=await Ko({value:e,schema:t});if(!r.success)throw Wo.wrap({value:e,cause:r.error});return r.value}async function Ko({value:e,schema:t}){const r=hI(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:Wo.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Wo.wrap({value:e,cause:n}),rawValue:e}}}async function yI({text:e,schema:t}){try{const r=Sc(e);return t==null?r:gI({value:r,schema:t})}catch(r){throw la.isInstance(r)||Wo.isInstance(r)?r:new la({text:e,cause:r})}}async function Y2({text:e,schema:t}){try{const r=Sc(e);return t==null?{success:!0,value:r,rawValue:r}:await Ko({value:r,schema:t})}catch(r){return{success:!1,error:la.isInstance(r)?r:new la({text:e,cause:r}),rawValue:void 0}}}function Q2(e){try{return Sc(e),!0}catch{return!1}}function _I({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Un).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Y2({text:r,schema:t}))}}))}async function X2({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Ko({value:t[e],schema:r});if(!n.success)throw new I2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var vI=()=>globalThis.fetch,eg=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>wI({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),wI=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=vI()})=>{try{const i=await a(e,{method:"POST",headers:W2(t,`ai-sdk/provider-utils/${iI}`,sI()),body:r.content,signal:s}),l=ua(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Tc(u)||Ir.isInstance(u)?u:new Ir({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Tc(c)||Ir.isInstance(c))?c:new Ir({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw oI({error:i,url:e,requestBodyValues:r.values})}},bI=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=ua(n);if(a.trim()==="")return{responseHeaders:i,value:new Ir({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await yI({text:a,schema:e});return{responseHeaders:i,value:new Ir({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new Ir({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},kI=e=>async({response:t})=>{const r=ua(t);if(t.body==null)throw new JS({});return{responseHeaders:r,value:_I({stream:t.body,schema:e})}},CI=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Y2({text:o,schema:e}),a=ua(t);if(!s.success)throw new Ir({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:TI}=globalThis;function SI(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return TI(t)}function II(e){return e instanceof Uint8Array?SI(e):e}function xI(e){return e?.replace(/\/$/,"")}function Yo(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function EI(e){const t=[];for(const{role:r,content:n,...o}of e){const s=Yo({...o});switch(r){case"system":{t.push({role:"system",content:n,...s});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...Yo(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=Yo(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,${II(a.data)}`},...i}}else throw new J2({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=Yo(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)},...c});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of n){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 c=Yo(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return t}function tg({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function rg(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 xc=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),$I=T({error:T({message:d(),type:d().nullish(),param:ft().nullish(),code:oe([d(),j()]).nullish()})}),RI={errorSchema:$I,errorToMessage:e=>e.error.message};function PI({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new J2({functionality:`tool choice type: ${s}`})}}}var MI=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:RI;this.chunkSchema=OI(o.errorSchema),this.failedResponseHandler=bI(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:g,tools:p}){var h,y,w,m;const b=[],_=Object.assign((h=await X2({provider:"openai-compatible",providerOptions:i,schema:xc}))!=null?h:{},(y=await X2({provider:this.providerOptionsName,providerOptions:i,schema:xc}))!=null?y:{});o!=null&&b.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&b.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:f,toolChoice:C,toolWarnings:k}=PI({tools:p,toolChoice:g});return{args:{model:this.modelId,user:_.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(w=c.name)!=null?w:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((m=i?.[this.providerOptionsName])!=null?m:{}).filter(([v])=>!Object.keys(xc.shape).includes(v))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:EI(e),tools:f,tool_choice:C},warnings:[...b,...k]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,p,h,y,w,m,b;const{args:_,warnings:f}=await this.getArgs({...e}),C=JSON.stringify(_),{responseHeaders:k,value:v,rawValue:S}=await eg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:G2(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:CI(NI),abortSignal:e.abortSignal,fetch:this.config.fetch}),$=v.choices[0],E=[],D=$.message.content;D!=null&&D.length>0&&E.push({type:"text",text:D});const M=(t=$.message.reasoning_content)!=null?t:$.message.reasoning;if(M!=null&&M.length>0&&E.push({type:"reasoning",text:M}),$.message.tool_calls!=null)for(const L of $.message.tool_calls)E.push({type:"tool-call",toolCallId:(r=L.id)!=null?r:da(),toolName:L.function.name,input:L.function.arguments});const N={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},O=(s=v.usage)==null?void 0:s.completion_tokens_details;return O?.accepted_prediction_tokens!=null&&(N[this.providerOptionsName].acceptedPredictionTokens=O?.accepted_prediction_tokens),O?.rejected_prediction_tokens!=null&&(N[this.providerOptionsName].rejectedPredictionTokens=O?.rejected_prediction_tokens),{content:E,finishReason:rg($.finish_reason),usage:{inputTokens:(i=(a=v.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=v.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(g=(u=v.usage)==null?void 0:u.total_tokens)!=null?g:void 0,reasoningTokens:(y=(h=(p=v.usage)==null?void 0:p.completion_tokens_details)==null?void 0:h.reasoning_tokens)!=null?y:void 0,cachedInputTokens:(b=(m=(w=v.usage)==null?void 0:w.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?b:void 0},providerMetadata:N,request:{body:C},response:{...tg(v),headers:k,body:S},warnings:f}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,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 eg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:G2(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:kI(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let g=!0;const p=this.providerOptionsName;let h=!1,y=!1;return{stream:i.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,m){var b,_,f,C,k,v,S,$,E,D,M,N,O;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",m.enqueue({type:"error",error:w.error});return}const L=w.value;if(s?.processChunk(w.rawValue),"error"in L){c="error",m.enqueue({type:"error",error:L.error.message});return}if(g&&(g=!1,m.enqueue({type:"response-metadata",...tg(L)})),L.usage!=null){const{prompt_tokens:W,completion_tokens:Ee,total_tokens:F,prompt_tokens_details:A,completion_tokens_details:B}=L.usage;u.promptTokens=W??void 0,u.completionTokens=Ee??void 0,u.totalTokens=F??void 0,B?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=B?.reasoning_tokens),B?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=B?.rejected_prediction_tokens),A?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=A?.cached_tokens)}const K=L.choices[0];if(K?.finish_reason!=null&&(c=rg(K.finish_reason)),K?.delta==null)return;const H=K.delta,le=(b=H.reasoning_content)!=null?b:H.reasoning;if(le&&(h||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),h=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:le})),H.content&&(y||(m.enqueue({type:"text-start",id:"txt-0"}),y=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:H.content})),H.tool_calls!=null)for(const W of H.tool_calls){const Ee=W.index;if(l[Ee]==null){if(W.id==null)throw new R2({data:W,message:"Expected 'id' to be a string."});if(((_=W.function)==null?void 0:_.name)==null)throw new R2({data:W,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:W.id,toolName:W.function.name}),l[Ee]={id:W.id,type:"function",function:{name:W.function.name,arguments:(f=W.function.arguments)!=null?f:""},hasFinished:!1};const A=l[Ee];((C=A.function)==null?void 0:C.name)!=null&&((k=A.function)==null?void 0:k.arguments)!=null&&(A.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:A.id,delta:A.function.arguments}),Q2(A.function.arguments)&&(m.enqueue({type:"tool-input-end",id:A.id}),m.enqueue({type:"tool-call",toolCallId:(v=A.id)!=null?v:da(),toolName:A.function.name,input:A.function.arguments}),A.hasFinished=!0));continue}const F=l[Ee];F.hasFinished||(((S=W.function)==null?void 0:S.arguments)!=null&&(F.function.arguments+=(E=($=W.function)==null?void 0:$.arguments)!=null?E:""),m.enqueue({type:"tool-input-delta",id:F.id,delta:(D=W.function.arguments)!=null?D:""}),((M=F.function)==null?void 0:M.name)!=null&&((N=F.function)==null?void 0:N.arguments)!=null&&Q2(F.function.arguments)&&(m.enqueue({type:"tool-input-end",id:F.id}),m.enqueue({type:"tool-call",toolCallId:(O=F.id)!=null?O:da(),toolName:F.function.name,input:F.function.arguments}),F.hasFinished=!0))}},flush(w){var m,b,_,f,C,k;h&&w.enqueue({type:"reasoning-end",id:"reasoning-0"}),y&&w.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter($=>!$.hasFinished))w.enqueue({type:"tool-input-end",id:S.id}),w.enqueue({type:"tool-call",toolCallId:(m=S.id)!=null?m:da(),toolName:S.function.name,input:S.function.arguments});const v={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(v[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(v[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),w.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(b=u.promptTokens)!=null?b:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(f=u.totalTokens)!=null?f:void 0,reasoningTokens:(C=u.completionTokensDetails.reasoningTokens)!=null?C:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:v})}})),request:{body:o},response:{headers:a}}}},ng=T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),NI=T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({message:T({role:P("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({id:d().nullish(),function:T({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:ng}),OI=e=>oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({delta:T({role:Se(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({index:j(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:ng}),e]);T({echo:fe().optional(),logitBias:me(d(),j()).optional(),suffix:d().optional(),user:d().optional()});var AI=T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d()})),usage:AI.nullish()}),T({dimensions:j().optional(),user:d().optional()}),T({data:q(T({embedding:q(j())})),usage:T({prompt_tokens:j()}).nullish(),providerMetadata:me(d(),me(d(),ft())).optional()}),T({data:q(T({b64_json:d()}))});var og=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},qI={extractMetadata:async({parsedBody:e})=>{const t=await Ko({value:e,schema:LI});return!t.success||t.value.usage==null?void 0:og(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Ko({value:t,schema:jI});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>og(e)}}},sg=T({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),LI=T({usage:sg.nullish()}),jI=T({choices:q(T({finish_reason:d().nullish()})).nullish(),usage:sg.nullish()}),UI="1.0.30";function ag(e={}){var t;const r=xI((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>W2({Authorization:`Bearer ${lI({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${UI}`);class o extends MI{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:qI}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new D2({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new D2({modelId:i,modelType:"imageModel"})},a}ag();const DI=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},zI=(e,t,r,n)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===r){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class FI{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=zI("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=vn.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const n=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!n,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const o=n.tabIds[n.tabIds.length-1];DI("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:o,mcpMessage:t},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}function pa(e){return!!e._zod}function Gr(e,t){return pa(e)?Nd(e,t):e.safeParse(t)}function ig(e){if(!e)return;let t;if(pa(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function VI(e){if(pa(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}function Cn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function lg(e){const r=ig(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=VI(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function cg(e,t){const r=Gr(e,t);if(!r.success)throw r.error;return r.data}const ZI=6e4;class BI{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ql,r=>{this._oncancel(r)}),this.setNotificationHandler(jl,r=>{this._onprogress(r)}),this.setRequestHandler(Ll,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ul,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke($e.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(zl,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(i.type==="response"||i.type==="error"){const l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{const g=l,p=new ke(g.error.code,g.error.message,g.error.data);u(p)}else{const g=i.type==="response"?"Response":"Error";this._onerror(new Error(`${g} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new ke($e.InvalidParams,`Task not found: ${s}`);if(!Cn(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Cn(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[_n]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Fl,async(r,n)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new ke($e.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Zl,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke($e.InvalidParams,`Task not found: ${r.params.taskId}`);if(Cn(o.status))throw new ke($e.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ke($e.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ke?o:new ke($e.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),ke.fromError($e.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),zo(s)||CC(s)?this._onresponse(s):Nl(s)?this._onrequest(s,a):kC(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=ke.fromError($e.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[_n]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:$e.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.send(u).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=bC(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const g={relatedRequestId:t.id};s&&(g.relatedTask={taskId:s}),await this.notification(u,g)},sendRequest:async(u,g,p)=>{const h={...p,relatedRequestId:t.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});const y=h.relatedTask?.taskId??s;return y&&l&&await l.updateTaskStatus(y,"input_required"),await this.request(u,g,h)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const g={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)},async u=>{if(a.signal.aborted)return;const g={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:$e.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.send(g)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),zo(t))n(t);else{const a=new ke(t.error.code,t.error.message,t.error.data);n(a)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(zo(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,r))}}if(s||this._progressHandlers.delete(r),zo(t))o(t);else{const a=ke.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof ke?a:new ke($e.InternalError,String(a))}}return}let s;try{const a=await this.request(t,Ho,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ke($e.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},Cn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new ke($e.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new ke($e.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof ke?a:new ke($e.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const g=_=>{u(_)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(_){g(_);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(h.params={...h.params,task:i}),l&&(h.params={...h.params,_meta:{...h.params?._meta||{},[_n]:l}});const y=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));const f=_ instanceof ke?_:new ke($e.RequestTimeout,String(_));u(f)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{const f=Gr(r,_.result);f.success?c(f.data):u(f.error)}catch(f){u(f)}}}),n?.signal?.addEventListener("abort",()=>{y(n?.signal?.reason)});const w=n?.timeout??ZI,m=()=>y(ke.fromError($e.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(p,w,n?.maxTotalTimeout,m,n?.resetTimeoutOnProgress??!1);const b=l?.taskId;if(b){const _=f=>{const C=this._responseHandlers.get(p);C?C(f):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(b,{type:"request",message:h,timestamp:Date.now()}).catch(f=>{this._cleanupTimeout(p),u(f)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(_=>{this._cleanupTimeout(p),u(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Dl,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Vl,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},DC,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const i={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[_n]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[_n]:r.relatedTask}}}),this._transport?.send(i,r).catch(l=>this._onerror(l))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[_n]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=lg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=cg(t,o);return Promise.resolve(r(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const n=lg(t);this._notificationHandlers.set(n,o=>{const s=cg(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&Nl(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new ke($e.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new ke($e.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ke($e.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new ke($e.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=Xs.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Cn(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,a)=>{const i=await n.getTask(o,r);if(!i)throw new ke($e.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Cn(i.status))throw new ke($e.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=Xs.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Cn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function ug(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function HI(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const a=r[o];ug(a)&&ug(s)?r[o]={...a,...s}:r[o]=s}return r}var fa={exports:{}},Ec={},xr={},Tn={},$c={},Rc={},Pc={},dg;function ha(){return dg||(dg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((f,C)=>`${f}${C}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((f,C)=>(C instanceof r&&(f[C.str]=(f[C.str]||0)+1),f),{})}}e._Code=n,e.nil=new n("");function o(b,..._){const f=[b[0]];let C=0;for(;C<_.length;)i(f,_[C]),f.push(b[++C]);return new n(f)}e._=o;const s=new n("+");function a(b,..._){const f=[h(b[0])];let C=0;for(;C<_.length;)f.push(s),i(f,_[C]),f.push(s,h(b[++C]));return l(f),new n(f)}e.str=a;function i(b,_){_ instanceof n?b.push(..._._items):_ instanceof r?b.push(_):b.push(g(_))}e.addCodeArg=i;function l(b){let _=1;for(;_<b.length-1;){if(b[_]===s){const f=c(b[_-1],b[_+1]);if(f!==void 0){b.splice(_-1,3,f);continue}b[_++]="+"}_++}}function c(b,_){if(_==='""')return b;if(b==='""')return _;if(typeof b=="string")return _ instanceof r||b[b.length-1]!=='"'?void 0:typeof _!="string"?`${b.slice(0,-1)}${_}"`:_[0]==='"'?b.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(b instanceof r))return`"${b}${_.slice(1)}`}function u(b,_){return _.emptyStr()?b:b.emptyStr()?_:a`${b}${_}`}e.strConcat=u;function g(b){return typeof b=="number"||typeof b=="boolean"||b===null?b:h(Array.isArray(b)?b.join(","):b)}function p(b){return new n(h(b))}e.stringify=p;function h(b){return JSON.stringify(b).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function y(b){return typeof b=="string"&&e.IDENTIFIER.test(b)?new n(`.${b}`):o`[${b}]`}e.getProperty=y;function w(b){if(typeof b=="string"&&e.IDENTIFIER.test(b))return new n(`${b}`);throw new Error(`CodeGen: invalid export name: ${b}, use explicit $id name mapping`)}e.getEsmExportName=w;function m(b){return new n(b.toString())}e.regexpCode=m})(Pc)),Pc}var Mc={},pg;function fg(){return pg||(pg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=ha();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,g;if(!((g=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||g===void 0)&&g.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:g}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${g}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var g;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:h}=p,y=(g=u.key)!==null&&g!==void 0?g:u.ref;let w=this._values[h];if(w){const _=w.get(y);if(_)return _}else w=this._values[h]=new Map;w.set(y,p);const m=this._scope[h]||(this._scope[h]=[]),b=m.length;return m[b]=u.ref,p.setValue(u,{property:h,itemIndex:b}),p}getValue(c,u){const g=this._values[c];if(g)return g.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,g=>{if(g.scopePath===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return(0,t._)`${c}${g.scopePath}`})}scopeCode(c=this._values,u,g){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,g)}_reduceValues(c,u,g={},p){let h=t.nil;for(const y in c){const w=c[y];if(!w)continue;const m=g[y]=g[y]||new Map;w.forEach(b=>{if(m.has(b))return;m.set(b,n.Started);let _=u(b);if(_){const f=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${f} ${b} = ${_};${this.opts._n}`}else if(_=p?.(b))h=(0,t._)`${h}${_}${this.opts._n}`;else throw new r(b);m.set(b,n.Completed)})}return h}}e.ValueScope=i})(Mc)),Mc}var hg;function Ne(){return hg||(hg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=ha(),r=fg();var n=ha();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=fg();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(I,x){return this}}class a extends s{constructor(I,x,Z){super(),this.varKind=I,this.name=x,this.rhs=Z}render({es5:I,_n:x}){const Z=I?r.varKinds.var:this.varKind,ee=this.rhs===void 0?"":` = ${this.rhs}`;return`${Z} ${this.name}${ee};`+x}optimizeNames(I,x){if(I[this.name.str])return this.rhs&&(this.rhs=L(this.rhs,I,x)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(I,x,Z){super(),this.lhs=I,this.rhs=x,this.sideEffects=Z}render({_n:I}){return`${this.lhs} = ${this.rhs};`+I}optimizeNames(I,x){if(!(this.lhs instanceof t.Name&&!I[this.lhs.str]&&!this.sideEffects))return this.rhs=L(this.rhs,I,x),this}get names(){const I=this.lhs instanceof t.Name?{}:{...this.lhs.names};return O(I,this.rhs)}}class l extends i{constructor(I,x,Z,ee){super(I,Z,ee),this.op=x}render({_n:I}){return`${this.lhs} ${this.op}= ${this.rhs};`+I}}class c extends s{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`${this.label}:`+I}}class u extends s{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`break${this.label?` ${this.label}`:""};`+I}}class g extends s{constructor(I){super(),this.error=I}render({_n:I}){return`throw ${this.error};`+I}get names(){return this.error.names}}class p extends s{constructor(I){super(),this.code=I}render({_n:I}){return`${this.code};`+I}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(I,x){return this.code=L(this.code,I,x),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(I=[]){super(),this.nodes=I}render(I){return this.nodes.reduce((x,Z)=>x+Z.render(I),"")}optimizeNodes(){const{nodes:I}=this;let x=I.length;for(;x--;){const Z=I[x].optimizeNodes();Array.isArray(Z)?I.splice(x,1,...Z):Z?I[x]=Z:I.splice(x,1)}return I.length>0?this:void 0}optimizeNames(I,x){const{nodes:Z}=this;let ee=Z.length;for(;ee--;){const Y=Z[ee];Y.optimizeNames(I,x)||(K(I,Y.names),Z.splice(ee,1))}return Z.length>0?this:void 0}get names(){return this.nodes.reduce((I,x)=>N(I,x.names),{})}}class y extends h{render(I){return"{"+I._n+super.render(I)+"}"+I._n}}class w extends h{}class m extends y{}m.kind="else";class b extends y{constructor(I,x){super(x),this.condition=I}render(I){let x=`if(${this.condition})`+super.render(I);return this.else&&(x+="else "+this.else.render(I)),x}optimizeNodes(){super.optimizeNodes();const I=this.condition;if(I===!0)return this.nodes;let x=this.else;if(x){const Z=x.optimizeNodes();x=this.else=Array.isArray(Z)?new m(Z):Z}if(x)return I===!1?x instanceof b?x:x.nodes:this.nodes.length?this:new b(H(I),x instanceof b?[x]:x.nodes);if(!(I===!1||!this.nodes.length))return this}optimizeNames(I,x){var Z;if(this.else=(Z=this.else)===null||Z===void 0?void 0:Z.optimizeNames(I,x),!!(super.optimizeNames(I,x)||this.else))return this.condition=L(this.condition,I,x),this}get names(){const I=super.names;return O(I,this.condition),this.else&&N(I,this.else.names),I}}b.kind="if";class _ extends y{}_.kind="for";class f extends _{constructor(I){super(),this.iteration=I}render(I){return`for(${this.iteration})`+super.render(I)}optimizeNames(I,x){if(super.optimizeNames(I,x))return this.iteration=L(this.iteration,I,x),this}get names(){return N(super.names,this.iteration.names)}}class C extends _{constructor(I,x,Z,ee){super(),this.varKind=I,this.name=x,this.from=Z,this.to=ee}render(I){const x=I.es5?r.varKinds.var:this.varKind,{name:Z,from:ee,to:Y}=this;return`for(${x} ${Z}=${ee}; ${Z}<${Y}; ${Z}++)`+super.render(I)}get names(){const I=O(super.names,this.from);return O(I,this.to)}}class k extends _{constructor(I,x,Z,ee){super(),this.loop=I,this.varKind=x,this.name=Z,this.iterable=ee}render(I){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(I)}optimizeNames(I,x){if(super.optimizeNames(I,x))return this.iterable=L(this.iterable,I,x),this}get names(){return N(super.names,this.iterable.names)}}class v extends y{constructor(I,x,Z){super(),this.name=I,this.args=x,this.async=Z}render(I){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(I)}}v.kind="func";class S extends h{render(I){return"return "+super.render(I)}}S.kind="return";class $ extends y{render(I){let x="try"+super.render(I);return this.catch&&(x+=this.catch.render(I)),this.finally&&(x+=this.finally.render(I)),x}optimizeNodes(){var I,x;return super.optimizeNodes(),(I=this.catch)===null||I===void 0||I.optimizeNodes(),(x=this.finally)===null||x===void 0||x.optimizeNodes(),this}optimizeNames(I,x){var Z,ee;return super.optimizeNames(I,x),(Z=this.catch)===null||Z===void 0||Z.optimizeNames(I,x),(ee=this.finally)===null||ee===void 0||ee.optimizeNames(I,x),this}get names(){const I=super.names;return this.catch&&N(I,this.catch.names),this.finally&&N(I,this.finally.names),I}}class E extends y{constructor(I){super(),this.error=I}render(I){return`catch(${this.error})`+super.render(I)}}E.kind="catch";class D extends y{render(I){return"finally"+super.render(I)}}D.kind="finally";class M{constructor(I,x={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...x,_n:x.lines?`
82
- `:""},this._extScope=I,this._scope=new r.Scope({parent:I}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(I){return this._scope.name(I)}scopeName(I){return this._extScope.name(I)}scopeValue(I,x){const Z=this._extScope.value(I,x);return(this._values[Z.prefix]||(this._values[Z.prefix]=new Set)).add(Z),Z}getScopeValue(I,x){return this._extScope.getValue(I,x)}scopeRefs(I){return this._extScope.scopeRefs(I,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(I,x,Z,ee){const Y=this._scope.toName(x);return Z!==void 0&&ee&&(this._constants[Y.str]=Z),this._leafNode(new a(I,Y,Z)),Y}const(I,x,Z){return this._def(r.varKinds.const,I,x,Z)}let(I,x,Z){return this._def(r.varKinds.let,I,x,Z)}var(I,x,Z){return this._def(r.varKinds.var,I,x,Z)}assign(I,x,Z){return this._leafNode(new i(I,x,Z))}add(I,x){return this._leafNode(new l(I,e.operators.ADD,x))}code(I){return typeof I=="function"?I():I!==t.nil&&this._leafNode(new p(I)),this}object(...I){const x=["{"];for(const[Z,ee]of I)x.length>1&&x.push(","),x.push(Z),(Z!==ee||this.opts.es5)&&(x.push(":"),(0,t.addCodeArg)(x,ee));return x.push("}"),new t._Code(x)}if(I,x,Z){if(this._blockNode(new b(I)),x&&Z)this.code(x).else().code(Z).endIf();else if(x)this.code(x).endIf();else if(Z)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(I){return this._elseNode(new b(I))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(b,m)}_for(I,x){return this._blockNode(I),x&&this.code(x).endFor(),this}for(I,x){return this._for(new f(I),x)}forRange(I,x,Z,ee,Y=this.opts.es5?r.varKinds.var:r.varKinds.let){const ye=this._scope.toName(I);return this._for(new C(Y,ye,x,Z),()=>ee(ye))}forOf(I,x,Z,ee=r.varKinds.const){const Y=this._scope.toName(I);if(this.opts.es5){const ye=x instanceof t.Name?x:this.var("_arr",x);return this.forRange("_i",0,(0,t._)`${ye}.length`,Ie=>{this.var(Y,(0,t._)`${ye}[${Ie}]`),Z(Y)})}return this._for(new k("of",ee,Y,x),()=>Z(Y))}forIn(I,x,Z,ee=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(I,(0,t._)`Object.keys(${x})`,Z);const Y=this._scope.toName(I);return this._for(new k("in",ee,Y,x),()=>Z(Y))}endFor(){return this._endBlockNode(_)}label(I){return this._leafNode(new c(I))}break(I){return this._leafNode(new u(I))}return(I){const x=new S;if(this._blockNode(x),this.code(I),x.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(I,x,Z){if(!x&&!Z)throw new Error('CodeGen: "try" without "catch" and "finally"');const ee=new $;if(this._blockNode(ee),this.code(I),x){const Y=this.name("e");this._currNode=ee.catch=new E(Y),x(Y)}return Z&&(this._currNode=ee.finally=new D,this.code(Z)),this._endBlockNode(E,D)}throw(I){return this._leafNode(new g(I))}block(I,x){return this._blockStarts.push(this._nodes.length),I&&this.code(I).endBlock(x),this}endBlock(I){const x=this._blockStarts.pop();if(x===void 0)throw new Error("CodeGen: not in self-balancing block");const Z=this._nodes.length-x;if(Z<0||I!==void 0&&Z!==I)throw new Error(`CodeGen: wrong number of nodes: ${Z} vs ${I} expected`);return this._nodes.length=x,this}func(I,x=t.nil,Z,ee){return this._blockNode(new v(I,x,Z)),ee&&this.code(ee).endFunc(),this}endFunc(){return this._endBlockNode(v)}optimize(I=1){for(;I-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(I){return this._currNode.nodes.push(I),this}_blockNode(I){this._currNode.nodes.push(I),this._nodes.push(I)}_endBlockNode(I,x){const Z=this._currNode;if(Z instanceof I||x&&Z instanceof x)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${x?`${I.kind}/${x.kind}`:I.kind}"`)}_elseNode(I){const x=this._currNode;if(!(x instanceof b))throw new Error('CodeGen: "else" without "if"');return this._currNode=x.else=I,this}get _root(){return this._nodes[0]}get _currNode(){const I=this._nodes;return I[I.length-1]}set _currNode(I){const x=this._nodes;x[x.length-1]=I}}e.CodeGen=M;function N(z,I){for(const x in I)z[x]=(z[x]||0)+(I[x]||0);return z}function O(z,I){return I instanceof t._CodeOrName?N(z,I.names):z}function L(z,I,x){if(z instanceof t.Name)return Z(z);if(!ee(z))return z;return new t._Code(z._items.reduce((Y,ye)=>(ye instanceof t.Name&&(ye=Z(ye)),ye instanceof t._Code?Y.push(...ye._items):Y.push(ye),Y),[]));function Z(Y){const ye=x[Y.str];return ye===void 0||I[Y.str]!==1?Y:(delete I[Y.str],ye)}function ee(Y){return Y instanceof t._Code&&Y._items.some(ye=>ye instanceof t.Name&&I[ye.str]===1&&x[ye.str]!==void 0)}}function K(z,I){for(const x in I)z[x]=(z[x]||0)-(I[x]||0)}function H(z){return typeof z=="boolean"||typeof z=="number"||z===null?!z:(0,t._)`!${B(z)}`}e.not=H;const le=A(e.operators.AND);function W(...z){return z.reduce(le)}e.and=W;const Ee=A(e.operators.OR);function F(...z){return z.reduce(Ee)}e.or=F;function A(z){return(I,x)=>I===t.nil?x:x===t.nil?I:(0,t._)`${B(I)} ${z} ${B(x)}`}function B(z){return z instanceof t.Name?z:(0,t._)`(${z})`}})(Rc)),Rc}var Oe={},mg;function Fe(){if(mg)return Oe;mg=1,Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.checkStrictMode=Oe.getErrorPath=Oe.Type=Oe.useFunc=Oe.setEvaluated=Oe.evaluatedPropsToName=Oe.mergeEvaluated=Oe.eachItem=Oe.unescapeJsonPointer=Oe.escapeJsonPointer=Oe.escapeFragment=Oe.unescapeFragment=Oe.schemaRefOrVal=Oe.schemaHasRulesButRef=Oe.schemaHasRules=Oe.checkUnknownRules=Oe.alwaysValidSchema=Oe.toHash=void 0;const e=Ne(),t=ha();function r(k){const v={};for(const S of k)v[S]=!0;return v}Oe.toHash=r;function n(k,v){return typeof v=="boolean"?v:Object.keys(v).length===0?!0:(o(k,v),!s(v,k.self.RULES.all))}Oe.alwaysValidSchema=n;function o(k,v=k.schema){const{opts:S,self:$}=k;if(!S.strictSchema||typeof v=="boolean")return;const E=$.RULES.keywords;for(const D in v)E[D]||C(k,`unknown keyword: "${D}"`)}Oe.checkUnknownRules=o;function s(k,v){if(typeof k=="boolean")return!k;for(const S in k)if(v[S])return!0;return!1}Oe.schemaHasRules=s;function a(k,v){if(typeof k=="boolean")return!k;for(const S in k)if(S!=="$ref"&&v.all[S])return!0;return!1}Oe.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:v},S,$,E){if(!E){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${k}${v}${(0,e.getProperty)($)}`}Oe.schemaRefOrVal=i;function l(k){return g(decodeURIComponent(k))}Oe.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}Oe.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}Oe.escapeJsonPointer=u;function g(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}Oe.unescapeJsonPointer=g;function p(k,v){if(Array.isArray(k))for(const S of k)v(S);else v(k)}Oe.eachItem=p;function h({mergeNames:k,mergeToName:v,mergeValues:S,resultToName:$}){return(E,D,M,N)=>{const O=M===void 0?D:M instanceof e.Name?(D instanceof e.Name?k(E,D,M):v(E,D,M),M):D instanceof e.Name?(v(E,M,D),D):S(D,M);return N===e.Name&&!(O instanceof e.Name)?$(E,O):O}}Oe.mergeEvaluated={props:h({mergeNames:(k,v,S)=>k.if((0,e._)`${S} !== true && ${v} !== undefined`,()=>{k.if((0,e._)`${v} === true`,()=>k.assign(S,!0),()=>k.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${v})`))}),mergeToName:(k,v,S)=>k.if((0,e._)`${S} !== true`,()=>{v===!0?k.assign(S,!0):(k.assign(S,(0,e._)`${S} || {}`),w(k,S,v))}),mergeValues:(k,v)=>k===!0?!0:{...k,...v},resultToName:y}),items:h({mergeNames:(k,v,S)=>k.if((0,e._)`${S} !== true && ${v} !== undefined`,()=>k.assign(S,(0,e._)`${v} === true ? true : ${S} > ${v} ? ${S} : ${v}`)),mergeToName:(k,v,S)=>k.if((0,e._)`${S} !== true`,()=>k.assign(S,v===!0?!0:(0,e._)`${S} > ${v} ? ${S} : ${v}`)),mergeValues:(k,v)=>k===!0?!0:Math.max(k,v),resultToName:(k,v)=>k.var("items",v)})};function y(k,v){if(v===!0)return k.var("props",!0);const S=k.var("props",(0,e._)`{}`);return v!==void 0&&w(k,S,v),S}Oe.evaluatedPropsToName=y;function w(k,v,S){Object.keys(S).forEach($=>k.assign((0,e._)`${v}${(0,e.getProperty)($)}`,!0))}Oe.setEvaluated=w;const m={};function b(k,v){return k.scopeValue("func",{ref:v,code:m[v.code]||(m[v.code]=new t._Code(v.code))})}Oe.useFunc=b;var _;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(_||(Oe.Type=_={}));function f(k,v,S){if(k instanceof e.Name){const $=v===_.Num;return S?$?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:$?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(k).toString():"/"+u(k)}Oe.getErrorPath=f;function C(k,v,S=k.opts.strictSchema){if(S){if(v=`strict mode: ${v}`,S===!0)throw new Error(v);k.self.logger.warn(v)}}return Oe.checkStrictMode=C,Oe}var ma={},gg;function Wr(){if(gg)return ma;gg=1,Object.defineProperty(ma,"__esModule",{value:!0});const e=Ne(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return ma.default=t,ma}var yg;function ga(){return yg||(yg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Ne(),r=Fe(),n=Wr();e.keywordError={message:({keyword:m})=>(0,t.str)`must pass "${m}" keyword validation`},e.keyword$DataError={message:({keyword:m,schemaType:b})=>b?(0,t.str)`"${m}" keyword must be ${b} ($data)`:(0,t.str)`"${m}" keyword is invalid ($data)`};function o(m,b=e.keywordError,_,f){const{it:C}=m,{gen:k,compositeRule:v,allErrors:S}=C,$=g(m,b,_);f??(v||S)?l(k,$):c(C,(0,t._)`[${$}]`)}e.reportError=o;function s(m,b=e.keywordError,_){const{it:f}=m,{gen:C,compositeRule:k,allErrors:v}=f,S=g(m,b,_);l(C,S),k||v||c(f,n.default.vErrors)}e.reportExtraError=s;function a(m,b){m.assign(n.default.errors,b),m.if((0,t._)`${n.default.vErrors} !== null`,()=>m.if(b,()=>m.assign((0,t._)`${n.default.vErrors}.length`,b),()=>m.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:m,keyword:b,schemaValue:_,data:f,errsCount:C,it:k}){if(C===void 0)throw new Error("ajv implementation error");const v=m.name("err");m.forRange("i",C,n.default.errors,S=>{m.const(v,(0,t._)`${n.default.vErrors}[${S}]`),m.if((0,t._)`${v}.instancePath === undefined`,()=>m.assign((0,t._)`${v}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),m.assign((0,t._)`${v}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${b}`),k.opts.verbose&&(m.assign((0,t._)`${v}.schema`,_),m.assign((0,t._)`${v}.data`,f))})}e.extendErrors=i;function l(m,b){const _=m.const("err",b);m.if((0,t._)`${n.default.vErrors} === null`,()=>m.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),m.code((0,t._)`${n.default.errors}++`)}function c(m,b){const{gen:_,validateName:f,schemaEnv:C}=m;C.$async?_.throw((0,t._)`new ${m.ValidationError}(${b})`):(_.assign((0,t._)`${f}.errors`,b),_.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function g(m,b,_){const{createErrors:f}=m.it;return f===!1?(0,t._)`{}`:p(m,b,_)}function p(m,b,_={}){const{gen:f,it:C}=m,k=[h(C,_),y(m,_)];return w(m,b,k),f.object(...k)}function h({errorPath:m},{instancePath:b}){const _=b?(0,t.str)`${m}${(0,r.getErrorPath)(b,r.Type.Str)}`:m;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function y({keyword:m,it:{errSchemaPath:b}},{schemaPath:_,parentSchema:f}){let C=f?b:(0,t.str)`${b}/${m}`;return _&&(C=(0,t.str)`${C}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,C]}function w(m,{params:b,message:_},f){const{keyword:C,data:k,schemaValue:v,it:S}=m,{opts:$,propertyName:E,topSchemaRef:D,schemaPath:M}=S;f.push([u.keyword,C],[u.params,typeof b=="function"?b(m):b||(0,t._)`{}`]),$.messages&&f.push([u.message,typeof _=="function"?_(m):_]),$.verbose&&f.push([u.schema,v],[u.parentSchema,(0,t._)`${D}${M}`],[n.default.data,k]),E&&f.push([u.propertyName,E])}})($c)),$c}var _g;function JI(){if(_g)return Tn;_g=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.boolOrEmptySchema=Tn.topBoolOrEmptySchema=void 0;const e=ga(),t=Ne(),r=Wr(),n={message:"boolean schema is false"};function o(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}Tn.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}Tn.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,g={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(g,n,void 0,l)}return Tn}var bt={},Sn={},vg;function wg(){if(vg)return Sn;vg=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.getRules=Sn.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}Sn.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return Sn.getRules=n,Sn}var Er={},bg;function kg(){if(bg)return Er;bg=1,Object.defineProperty(Er,"__esModule",{value:!0}),Er.shouldUseRule=Er.shouldUseGroup=Er.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}Er.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Er.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(a=>n[a]!==void 0))}return Er.shouldUseRule=r,Er}var Cg;function ya(){if(Cg)return bt;Cg=1,Object.defineProperty(bt,"__esModule",{value:!0}),bt.reportTypeError=bt.checkDataTypes=bt.checkDataType=bt.coerceAndCheckDataType=bt.getJSONTypes=bt.getSchemaTypes=bt.DataType=void 0;const e=wg(),t=kg(),r=ga(),n=Ne(),o=Fe();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||(bt.DataType=s={}));function a(_){const f=i(_.type);if(f.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!f.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&f.push("null")}return f}bt.getSchemaTypes=a;function i(_){const f=Array.isArray(_)?_:_?[_]:[];if(f.every(e.isJSONType))return f;throw new Error("type must be JSONType or JSONType[]: "+f.join(","))}bt.getJSONTypes=i;function l(_,f){const{gen:C,data:k,opts:v}=_,S=u(f,v.coerceTypes),$=f.length>0&&!(S.length===0&&f.length===1&&(0,t.schemaHasRulesForType)(_,f[0]));if($){const E=y(f,k,v.strictNumbers,s.Wrong);C.if(E,()=>{S.length?g(_,f,S):m(_)})}return $}bt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,f){return f?_.filter(C=>c.has(C)||f==="array"&&C==="array"):[]}function g(_,f,C){const{gen:k,data:v,opts:S}=_,$=k.let("dataType",(0,n._)`typeof ${v}`),E=k.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&k.if((0,n._)`${$} == 'object' && Array.isArray(${v}) && ${v}.length == 1`,()=>k.assign(v,(0,n._)`${v}[0]`).assign($,(0,n._)`typeof ${v}`).if(y(f,v,S.strictNumbers),()=>k.assign(E,v))),k.if((0,n._)`${E} !== undefined`);for(const M of C)(c.has(M)||M==="array"&&S.coerceTypes==="array")&&D(M);k.else(),m(_),k.endIf(),k.if((0,n._)`${E} !== undefined`,()=>{k.assign(v,E),p(_,E)});function D(M){switch(M){case"string":k.elseIf((0,n._)`${$} == "number" || ${$} == "boolean"`).assign(E,(0,n._)`"" + ${v}`).elseIf((0,n._)`${v} === null`).assign(E,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${$} == "boolean" || ${v} === null
83
- || (${$} == "string" && ${v} && ${v} == +${v})`).assign(E,(0,n._)`+${v}`);return;case"integer":k.elseIf((0,n._)`${$} === "boolean" || ${v} === null
84
- || (${$} === "string" && ${v} && ${v} == +${v} && !(${v} % 1))`).assign(E,(0,n._)`+${v}`);return;case"boolean":k.elseIf((0,n._)`${v} === "false" || ${v} === 0 || ${v} === null`).assign(E,!1).elseIf((0,n._)`${v} === "true" || ${v} === 1`).assign(E,!0);return;case"null":k.elseIf((0,n._)`${v} === "" || ${v} === 0 || ${v} === false`),k.assign(E,null);return;case"array":k.elseIf((0,n._)`${$} === "string" || ${$} === "number"
85
- || ${$} === "boolean" || ${v} === null`).assign(E,(0,n._)`[${v}]`)}}}function p({gen:_,parentData:f,parentDataProperty:C},k){_.if((0,n._)`${f} !== undefined`,()=>_.assign((0,n._)`${f}[${C}]`,k))}function h(_,f,C,k=s.Correct){const v=k===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(_){case"null":return(0,n._)`${f} ${v} null`;case"array":S=(0,n._)`Array.isArray(${f})`;break;case"object":S=(0,n._)`${f} && typeof ${f} == "object" && !Array.isArray(${f})`;break;case"integer":S=$((0,n._)`!(${f} % 1) && !isNaN(${f})`);break;case"number":S=$();break;default:return(0,n._)`typeof ${f} ${v} ${_}`}return k===s.Correct?S:(0,n.not)(S);function $(E=n.nil){return(0,n.and)((0,n._)`typeof ${f} == "number"`,E,C?(0,n._)`isFinite(${f})`:n.nil)}}bt.checkDataType=h;function y(_,f,C,k){if(_.length===1)return h(_[0],f,C,k);let v;const S=(0,o.toHash)(_);if(S.array&&S.object){const $=(0,n._)`typeof ${f} != "object"`;v=S.null?$:(0,n._)`!${f} || ${$}`,delete S.null,delete S.array,delete S.object}else v=n.nil;S.number&&delete S.integer;for(const $ in S)v=(0,n.and)(v,h($,f,C,k));return v}bt.checkDataTypes=y;const w={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:f})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${f}}`};function m(_){const f=b(_);(0,r.reportError)(f,w)}bt.reportTypeError=m;function b(_){const{gen:f,data:C,schema:k}=_,v=(0,o.schemaRefOrVal)(_,k,"type");return{gen:f,keyword:"type",data:C,schema:k.type,schemaCode:v,schemaValue:v,parentSchema:k,params:{},it:_}}return bt}var Qo={},Tg;function GI(){if(Tg)return Qo;Tg=1,Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.assignDefaults=void 0;const e=Ne(),t=Fe();function r(o,s){const{properties:a,items:i}=o.schema;if(s==="object"&&a)for(const l in a)n(o,l,a[l].default);else s==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}Qo.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const g=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${g}`);return}let p=(0,e._)`${g} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${g} === null || ${g} === ""`),i.if(p,(0,e._)`${g} = ${(0,e.stringify)(a)}`)}return Qo}var nr={},He={},Sg;function or(){if(Sg)return He;Sg=1,Object.defineProperty(He,"__esModule",{value:!0}),He.validateUnion=He.validateArray=He.usePattern=He.callValidateCode=He.schemaProperties=He.allSchemaProperties=He.noPropertyInData=He.propertyInData=He.isOwnProperty=He.hasPropFunc=He.reportMissingProp=He.checkMissingProp=He.checkReportMissingProp=void 0;const e=Ne(),t=Fe(),r=Wr(),n=Fe();function o(_,f){const{gen:C,data:k,it:v}=_;C.if(u(C,k,f,v.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${f}`},!0),_.error()})}He.checkReportMissingProp=o;function s({gen:_,data:f,it:{opts:C}},k,v){return(0,e.or)(...k.map(S=>(0,e.and)(u(_,f,S,C.ownProperties),(0,e._)`${v} = ${S}`)))}He.checkMissingProp=s;function a(_,f){_.setParams({missingProperty:f},!0),_.error()}He.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}He.hasPropFunc=i;function l(_,f,C){return(0,e._)`${i(_)}.call(${f}, ${C})`}He.isOwnProperty=l;function c(_,f,C,k){const v=(0,e._)`${f}${(0,e.getProperty)(C)} !== undefined`;return k?(0,e._)`${v} && ${l(_,f,C)}`:v}He.propertyInData=c;function u(_,f,C,k){const v=(0,e._)`${f}${(0,e.getProperty)(C)} === undefined`;return k?(0,e.or)(v,(0,e.not)(l(_,f,C))):v}He.noPropertyInData=u;function g(_){return _?Object.keys(_).filter(f=>f!=="__proto__"):[]}He.allSchemaProperties=g;function p(_,f){return g(f).filter(C=>!(0,t.alwaysValidSchema)(_,f[C]))}He.schemaProperties=p;function h({schemaCode:_,data:f,it:{gen:C,topSchemaRef:k,schemaPath:v,errorPath:S},it:$},E,D,M){const N=M?(0,e._)`${_}, ${f}, ${k}${v}`:f,O=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,$.parentData],[r.default.parentDataProperty,$.parentDataProperty],[r.default.rootData,r.default.rootData]];$.opts.dynamicRef&&O.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const L=(0,e._)`${N}, ${C.object(...O)}`;return D!==e.nil?(0,e._)`${E}.call(${D}, ${L})`:(0,e._)`${E}(${L})`}He.callValidateCode=h;const y=(0,e._)`new RegExp`;function w({gen:_,it:{opts:f}},C){const k=f.unicodeRegExp?"u":"",{regExp:v}=f.code,S=v(C,k);return _.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${v.code==="new RegExp"?y:(0,n.useFunc)(_,v)}(${C}, ${k})`})}He.usePattern=w;function m(_){const{gen:f,data:C,keyword:k,it:v}=_,S=f.name("valid");if(v.allErrors){const E=f.let("valid",!0);return $(()=>f.assign(E,!1)),E}return f.var(S,!0),$(()=>f.break()),S;function $(E){const D=f.const("len",(0,e._)`${C}.length`);f.forRange("i",0,D,M=>{_.subschema({keyword:k,dataProp:M,dataPropType:t.Type.Num},S),f.if((0,e.not)(S),E)})}}He.validateArray=m;function b(_){const{gen:f,schema:C,keyword:k,it:v}=_;if(!Array.isArray(C))throw new Error("ajv implementation error");if(C.some(D=>(0,t.alwaysValidSchema)(v,D))&&!v.opts.unevaluated)return;const $=f.let("valid",!1),E=f.name("_valid");f.block(()=>C.forEach((D,M)=>{const N=_.subschema({keyword:k,schemaProp:M,compositeRule:!0},E);f.assign($,(0,e._)`${$} || ${E}`),_.mergeValidEvaluated(N,E)||f.if((0,e.not)($))})),_.result($,()=>_.reset(),()=>_.error(!0))}return He.validateUnion=b,He}var Ig;function WI(){if(Ig)return nr;Ig=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.validateKeywordUsage=nr.validSchemaType=nr.funcKeywordCode=nr.macroKeywordCode=void 0;const e=Ne(),t=Wr(),r=or(),n=ga();function o(p,h){const{gen:y,keyword:w,schema:m,parentSchema:b,it:_}=p,f=h.macro.call(_.self,m,b,_),C=c(y,w,f);_.opts.validateSchema!==!1&&_.self.validateSchema(f,!0);const k=y.name("valid");p.subschema({schema:f,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${w}`,topSchemaRef:C,compositeRule:!0},k),p.pass(k,()=>p.error(!0))}nr.macroKeywordCode=o;function s(p,h){var y;const{gen:w,keyword:m,schema:b,parentSchema:_,$data:f,it:C}=p;l(C,h);const k=!f&&h.compile?h.compile.call(C.self,b,_,C):h.validate,v=c(w,m,k),S=w.let("valid");p.block$data(S,$),p.ok((y=h.valid)!==null&&y!==void 0?y:S);function $(){if(h.errors===!1)M(),h.modifying&&a(p),N(()=>p.error());else{const O=h.async?E():D();h.modifying&&a(p),N(()=>i(p,O))}}function E(){const O=w.let("ruleErrs",null);return w.try(()=>M((0,e._)`await `),L=>w.assign(S,!1).if((0,e._)`${L} instanceof ${C.ValidationError}`,()=>w.assign(O,(0,e._)`${L}.errors`),()=>w.throw(L))),O}function D(){const O=(0,e._)`${v}.errors`;return w.assign(O,null),M(e.nil),O}function M(O=h.async?(0,e._)`await `:e.nil){const L=C.opts.passContext?t.default.this:t.default.self,K=!("compile"in h&&!f||h.schema===!1);w.assign(S,(0,e._)`${O}${(0,r.callValidateCode)(p,v,L,K)}`,h.modifying)}function N(O){var L;w.if((0,e.not)((L=h.valid)!==null&&L!==void 0?L:S),O)}}nr.funcKeywordCode=s;function a(p){const{gen:h,data:y,it:w}=p;h.if(w.parentData,()=>h.assign(y,(0,e._)`${w.parentData}[${w.parentDataProperty}]`))}function i(p,h){const{gen:y}=p;y.if((0,e._)`Array.isArray(${h})`,()=>{y.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${h} : ${t.default.vErrors}.concat(${h})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},h){if(h.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,h,y){if(y===void 0)throw new Error(`keyword "${h}" failed to compile`);return p.scopeValue("keyword",typeof y=="function"?{ref:y}:{ref:y,code:(0,e.stringify)(y)})}function u(p,h,y=!1){return!h.length||h.some(w=>w==="array"?Array.isArray(p):w==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==w||y&&typeof p>"u")}nr.validSchemaType=u;function g({schema:p,opts:h,self:y,errSchemaPath:w},m,b){if(Array.isArray(m.keyword)?!m.keyword.includes(b):m.keyword!==b)throw new Error("ajv implementation error");const _=m.dependencies;if(_?.some(f=>!Object.prototype.hasOwnProperty.call(p,f)))throw new Error(`parent schema must have dependencies of ${b}: ${_.join(",")}`);if(m.validateSchema&&!m.validateSchema(p[b])){const C=`keyword "${b}" value is invalid at path "${w}": `+y.errorsText(m.validateSchema.errors);if(h.validateSchema==="log")y.logger.error(C);else throw new Error(C)}}return nr.validateKeywordUsage=g,nr}var $r={},xg;function KI(){if(xg)return $r;xg=1,Object.defineProperty($r,"__esModule",{value:!0}),$r.extendSubschemaMode=$r.extendSubschemaData=$r.getSubschema=void 0;const e=Ne(),t=Fe();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:g}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const p=s.schema[a];return i===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:p[i],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||g===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:g,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}$r.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:g}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=a;if(i!==void 0){const{errorPath:y,dataPathArr:w,opts:m}=a,b=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);h(b),s.errorPath=(0,e.str)`${y}${(0,t.getErrorPath)(i,l,m.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[...w,s.parentDataProperty]}if(c!==void 0){const y=c instanceof e.Name?c:p.let("data",c,!0);h(y),g!==void 0&&(s.propertyName=g)}u&&(s.dataTypes=u);function h(y){s.data=y,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,y]}}$r.extendSubschemaData=n;function o(s,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=a,s.jtdMetadata=i}return $r.extendSubschemaMode=o,$r}var Mt={},Nc,Eg;function $g(){return Eg||(Eg=1,Nc=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var a=s[o];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}),Nc}var Oc={exports:{}},Rg;function YI(){if(Rg)return Oc.exports;Rg=1;var e=Oc.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var a=typeof s=="function"?s:s.pre||function(){},i=s.post||function(){};t(o,a,i,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,a,i,l,c,u,g,p){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,g,p);for(var h in a){var y=a[h];if(Array.isArray(y)){if(h in e.arrayKeywords)for(var w=0;w<y.length;w++)t(n,o,s,y[w],i+"/"+h+"/"+w,l,i,h,a,w)}else if(h in e.propsKeywords){if(y&&typeof y=="object")for(var m in y)t(n,o,s,y[m],i+"/"+h+"/"+r(m),l,i,h,a,m)}else(h in e.keywords||n.allKeys&&!(h in e.skipKeywords))&&t(n,o,s,y,i+"/"+h,l,i,h,a)}s(a,i,l,c,u,g,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Oc.exports}var Pg;function _a(){if(Pg)return Mt;Pg=1,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.getSchemaRefs=Mt.resolveUrl=Mt.normalizeId=Mt._getFullPath=Mt.getFullPath=Mt.inlineRef=void 0;const e=Fe(),t=$g(),r=YI(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(w,m=!0){return typeof w=="boolean"?!0:m===!0?!a(w):m?i(w)<=m:!1}Mt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(w){for(const m in w){if(s.has(m))return!0;const b=w[m];if(Array.isArray(b)&&b.some(a)||typeof b=="object"&&a(b))return!0}return!1}function i(w){let m=0;for(const b in w){if(b==="$ref")return 1/0;if(m++,!n.has(b)&&(typeof w[b]=="object"&&(0,e.eachItem)(w[b],_=>m+=i(_)),m===1/0))return 1/0}return m}function l(w,m="",b){b!==!1&&(m=g(m));const _=w.parse(m);return c(w,_)}Mt.getFullPath=l;function c(w,m){return w.serialize(m).split("#")[0]+"#"}Mt._getFullPath=c;const u=/#\/?$/;function g(w){return w?w.replace(u,""):""}Mt.normalizeId=g;function p(w,m,b){return b=g(b),w.resolve(m,b)}Mt.resolveUrl=p;const h=/^[a-z_][-a-z0-9._]*$/i;function y(w,m){if(typeof w=="boolean")return{};const{schemaId:b,uriResolver:_}=this.opts,f=g(w[b]||m),C={"":f},k=l(_,f,!1),v={},S=new Set;return r(w,{allKeys:!0},(D,M,N,O)=>{if(O===void 0)return;const L=k+M;let K=C[O];typeof D[b]=="string"&&(K=H.call(this,D[b])),le.call(this,D.$anchor),le.call(this,D.$dynamicAnchor),C[M]=K;function H(W){const Ee=this.opts.uriResolver.resolve;if(W=g(K?Ee(K,W):W),S.has(W))throw E(W);S.add(W);let F=this.refs[W];return typeof F=="string"&&(F=this.refs[F]),typeof F=="object"?$(D,F.schema,W):W!==g(L)&&(W[0]==="#"?($(D,v[W],W),v[W]=D):this.refs[W]=L),W}function le(W){if(typeof W=="string"){if(!h.test(W))throw new Error(`invalid anchor "${W}"`);H.call(this,`#${W}`)}}}),v;function $(D,M,N){if(M!==void 0&&!t(D,M))throw E(N)}function E(D){return new Error(`reference "${D}" resolves to more than one schema`)}}return Mt.getSchemaRefs=y,Mt}var Mg;function va(){if(Mg)return xr;Mg=1,Object.defineProperty(xr,"__esModule",{value:!0}),xr.getData=xr.KeywordCxt=xr.validateFunctionCode=void 0;const e=JI(),t=ya(),r=kg(),n=ya(),o=GI(),s=WI(),a=KI(),i=Ne(),l=Wr(),c=_a(),u=Fe(),g=ga();function p(U){if(k(U)&&(S(U),C(U))){m(U);return}h(U,()=>(0,e.topBoolOrEmptySchema)(U))}xr.validateFunctionCode=p;function h({gen:U,validateName:V,schema:G,schemaEnv:Q,opts:ce},ve){ce.code.es5?U.func(V,(0,i._)`${l.default.data}, ${l.default.valCxt}`,Q.$async,()=>{U.code((0,i._)`"use strict"; ${_(G,ce)}`),w(U,ce),U.code(ve)}):U.func(V,(0,i._)`${l.default.data}, ${y(ce)}`,Q.$async,()=>U.code(_(G,ce)).code(ve))}function y(U){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${U.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function w(U,V){U.if(l.default.valCxt,()=>{U.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),U.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),U.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),U.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),V.dynamicRef&&U.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{U.var(l.default.instancePath,(0,i._)`""`),U.var(l.default.parentData,(0,i._)`undefined`),U.var(l.default.parentDataProperty,(0,i._)`undefined`),U.var(l.default.rootData,l.default.data),V.dynamicRef&&U.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function m(U){const{schema:V,opts:G,gen:Q}=U;h(U,()=>{G.$comment&&V.$comment&&O(U),D(U),Q.let(l.default.vErrors,null),Q.let(l.default.errors,0),G.unevaluated&&b(U),$(U),L(U)})}function b(U){const{gen:V,validateName:G}=U;U.evaluated=V.const("evaluated",(0,i._)`${G}.evaluated`),V.if((0,i._)`${U.evaluated}.dynamicProps`,()=>V.assign((0,i._)`${U.evaluated}.props`,(0,i._)`undefined`)),V.if((0,i._)`${U.evaluated}.dynamicItems`,()=>V.assign((0,i._)`${U.evaluated}.items`,(0,i._)`undefined`))}function _(U,V){const G=typeof U=="object"&&U[V.schemaId];return G&&(V.code.source||V.code.process)?(0,i._)`/*# sourceURL=${G} */`:i.nil}function f(U,V){if(k(U)&&(S(U),C(U))){v(U,V);return}(0,e.boolOrEmptySchema)(U,V)}function C({schema:U,self:V}){if(typeof U=="boolean")return!U;for(const G in U)if(V.RULES.all[G])return!0;return!1}function k(U){return typeof U.schema!="boolean"}function v(U,V){const{schema:G,gen:Q,opts:ce}=U;ce.$comment&&G.$comment&&O(U),M(U),N(U);const ve=Q.const("_errs",l.default.errors);$(U,ve),Q.var(V,(0,i._)`${ve} === ${l.default.errors}`)}function S(U){(0,u.checkUnknownRules)(U),E(U)}function $(U,V){if(U.opts.jtd)return H(U,[],!1,V);const G=(0,t.getSchemaTypes)(U.schema),Q=(0,t.coerceAndCheckDataType)(U,G);H(U,G,!Q,V)}function E(U){const{schema:V,errSchemaPath:G,opts:Q,self:ce}=U;V.$ref&&Q.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(V,ce.RULES)&&ce.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function D(U){const{schema:V,opts:G}=U;V.default!==void 0&&G.useDefaults&&G.strictSchema&&(0,u.checkStrictMode)(U,"default is ignored in the schema root")}function M(U){const V=U.schema[U.opts.schemaId];V&&(U.baseId=(0,c.resolveUrl)(U.opts.uriResolver,U.baseId,V))}function N(U){if(U.schema.$async&&!U.schemaEnv.$async)throw new Error("async schema in sync schema")}function O({gen:U,schemaEnv:V,schema:G,errSchemaPath:Q,opts:ce}){const ve=G.$comment;if(ce.$comment===!0)U.code((0,i._)`${l.default.self}.logger.log(${ve})`);else if(typeof ce.$comment=="function"){const R=(0,i.str)`${Q}/$comment`,re=U.scopeValue("root",{ref:V.root});U.code((0,i._)`${l.default.self}.opts.$comment(${ve}, ${R}, ${re}.schema)`)}}function L(U){const{gen:V,schemaEnv:G,validateName:Q,ValidationError:ce,opts:ve}=U;G.$async?V.if((0,i._)`${l.default.errors} === 0`,()=>V.return(l.default.data),()=>V.throw((0,i._)`new ${ce}(${l.default.vErrors})`)):(V.assign((0,i._)`${Q}.errors`,l.default.vErrors),ve.unevaluated&&K(U),V.return((0,i._)`${l.default.errors} === 0`))}function K({gen:U,evaluated:V,props:G,items:Q}){G instanceof i.Name&&U.assign((0,i._)`${V}.props`,G),Q instanceof i.Name&&U.assign((0,i._)`${V}.items`,Q)}function H(U,V,G,Q){const{gen:ce,schema:ve,data:R,allErrors:re,opts:ge,self:we}=U,{RULES:Re}=we;if(ve.$ref&&(ge.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ve,Re))){ce.block(()=>ee(U,"$ref",Re.all.$ref.definition));return}ge.jtd||W(U,V),ce.block(()=>{for(const ae of Re.rules)Ge(ae);Ge(Re.post)});function Ge(ae){(0,r.shouldUseGroup)(ve,ae)&&(ae.type?(ce.if((0,n.checkDataType)(ae.type,R,ge.strictNumbers)),le(U,ae),V.length===1&&V[0]===ae.type&&G&&(ce.else(),(0,n.reportTypeError)(U)),ce.endIf()):le(U,ae),re||ce.if((0,i._)`${l.default.errors} === ${Q||0}`))}}function le(U,V){const{gen:G,schema:Q,opts:{useDefaults:ce}}=U;ce&&(0,o.assignDefaults)(U,V.type),G.block(()=>{for(const ve of V.rules)(0,r.shouldUseRule)(Q,ve)&&ee(U,ve.keyword,ve.definition,V.type)})}function W(U,V){U.schemaEnv.meta||!U.opts.strictTypes||(Ee(U,V),U.opts.allowUnionTypes||F(U,V),A(U,U.dataTypes))}function Ee(U,V){if(V.length){if(!U.dataTypes.length){U.dataTypes=V;return}V.forEach(G=>{z(U.dataTypes,G)||x(U,`type "${G}" not allowed by context "${U.dataTypes.join(",")}"`)}),I(U,V)}}function F(U,V){V.length>1&&!(V.length===2&&V.includes("null"))&&x(U,"use allowUnionTypes to allow union type keyword")}function A(U,V){const G=U.self.RULES.all;for(const Q in G){const ce=G[Q];if(typeof ce=="object"&&(0,r.shouldUseRule)(U.schema,ce)){const{type:ve}=ce.definition;ve.length&&!ve.some(R=>B(V,R))&&x(U,`missing type "${ve.join(",")}" for keyword "${Q}"`)}}}function B(U,V){return U.includes(V)||V==="number"&&U.includes("integer")}function z(U,V){return U.includes(V)||V==="integer"&&U.includes("number")}function I(U,V){const G=[];for(const Q of U.dataTypes)z(V,Q)?G.push(Q):V.includes("integer")&&Q==="number"&&G.push("integer");U.dataTypes=G}function x(U,V){const G=U.schemaEnv.baseId+U.errSchemaPath;V+=` at "${G}" (strictTypes)`,(0,u.checkStrictMode)(U,V,U.opts.strictTypes)}class Z{constructor(V,G,Q){if((0,s.validateKeywordUsage)(V,G,Q),this.gen=V.gen,this.allErrors=V.allErrors,this.keyword=Q,this.data=V.data,this.schema=V.schema[Q],this.$data=G.$data&&V.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(V,this.schema,Q,this.$data),this.schemaType=G.schemaType,this.parentSchema=V.schema,this.params={},this.it=V,this.def=G,this.$data)this.schemaCode=V.gen.const("vSchema",Ie(this.$data,V));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,G.schemaType,G.allowUndefined))throw new Error(`${Q} value must be ${JSON.stringify(G.schemaType)}`);("code"in G?G.trackErrors:G.errors!==!1)&&(this.errsCount=V.gen.const("_errs",l.default.errors))}result(V,G,Q){this.failResult((0,i.not)(V),G,Q)}failResult(V,G,Q){this.gen.if(V),Q?Q():this.error(),G?(this.gen.else(),G(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(V,G){this.failResult((0,i.not)(V),void 0,G)}fail(V){if(V===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(V),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(V){if(!this.$data)return this.fail(V);const{schemaCode:G}=this;this.fail((0,i._)`${G} !== undefined && (${(0,i.or)(this.invalid$data(),V)})`)}error(V,G,Q){if(G){this.setParams(G),this._error(V,Q),this.setParams({});return}this._error(V,Q)}_error(V,G){(V?g.reportExtraError:g.reportError)(this,this.def.error,G)}$dataError(){(0,g.reportError)(this,this.def.$dataError||g.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,g.resetErrorsCount)(this.gen,this.errsCount)}ok(V){this.allErrors||this.gen.if(V)}setParams(V,G){G?Object.assign(this.params,V):this.params=V}block$data(V,G,Q=i.nil){this.gen.block(()=>{this.check$data(V,Q),G()})}check$data(V=i.nil,G=i.nil){if(!this.$data)return;const{gen:Q,schemaCode:ce,schemaType:ve,def:R}=this;Q.if((0,i.or)((0,i._)`${ce} === undefined`,G)),V!==i.nil&&Q.assign(V,!0),(ve.length||R.validateSchema)&&(Q.elseIf(this.invalid$data()),this.$dataError(),V!==i.nil&&Q.assign(V,!1)),Q.else()}invalid$data(){const{gen:V,schemaCode:G,schemaType:Q,def:ce,it:ve}=this;return(0,i.or)(R(),re());function R(){if(Q.length){if(!(G instanceof i.Name))throw new Error("ajv implementation error");const ge=Array.isArray(Q)?Q:[Q];return(0,i._)`${(0,n.checkDataTypes)(ge,G,ve.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function re(){if(ce.validateSchema){const ge=V.scopeValue("validate$data",{ref:ce.validateSchema});return(0,i._)`!${ge}(${G})`}return i.nil}}subschema(V,G){const Q=(0,a.getSubschema)(this.it,V);(0,a.extendSubschemaData)(Q,this.it,V),(0,a.extendSubschemaMode)(Q,V);const ce={...this.it,...Q,items:void 0,props:void 0};return f(ce,G),ce}mergeEvaluated(V,G){const{it:Q,gen:ce}=this;Q.opts.unevaluated&&(Q.props!==!0&&V.props!==void 0&&(Q.props=u.mergeEvaluated.props(ce,V.props,Q.props,G)),Q.items!==!0&&V.items!==void 0&&(Q.items=u.mergeEvaluated.items(ce,V.items,Q.items,G)))}mergeValidEvaluated(V,G){const{it:Q,gen:ce}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return ce.if(G,()=>this.mergeEvaluated(V,i.Name)),!0}}xr.KeywordCxt=Z;function ee(U,V,G,Q){const ce=new Z(U,G,V);"code"in G?G.code(ce,Q):ce.$data&&G.validate?(0,s.funcKeywordCode)(ce,G):"macro"in G?(0,s.macroKeywordCode)(ce,G):(G.compile||G.validate)&&(0,s.funcKeywordCode)(ce,G)}const Y=/^\/(?:[^~]|~0|~1)*$/,ye=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ie(U,{dataLevel:V,dataNames:G,dataPathArr:Q}){let ce,ve;if(U==="")return l.default.rootData;if(U[0]==="/"){if(!Y.test(U))throw new Error(`Invalid JSON-pointer: ${U}`);ce=U,ve=l.default.rootData}else{const we=ye.exec(U);if(!we)throw new Error(`Invalid JSON-pointer: ${U}`);const Re=+we[1];if(ce=we[2],ce==="#"){if(Re>=V)throw new Error(ge("property/index",Re));return Q[V-Re]}if(Re>V)throw new Error(ge("data",Re));if(ve=G[V-Re],!ce)return ve}let R=ve;const re=ce.split("/");for(const we of re)we&&(ve=(0,i._)`${ve}${(0,i.getProperty)((0,u.unescapeJsonPointer)(we))}`,R=(0,i._)`${R} && ${ve}`);return R;function ge(we,Re){return`Cannot access ${we} ${Re} levels up, current level is ${V}`}}return xr.getData=Ie,xr}var wa={},Ng;function Ac(){if(Ng)return wa;Ng=1,Object.defineProperty(wa,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return wa.default=e,wa}var ba={},Og;function ka(){if(Og)return ba;Og=1,Object.defineProperty(ba,"__esModule",{value:!0});const e=_a();class t extends Error{constructor(n,o,s,a){super(a||`can't resolve reference ${s} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return ba.default=t,ba}var Vt={},Ag;function qc(){if(Ag)return Vt;Ag=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.resolveSchema=Vt.getCompilingSchema=Vt.resolveRef=Vt.compileSchema=Vt.SchemaEnv=void 0;const e=Ne(),t=Ac(),r=Wr(),n=_a(),o=Fe(),s=va();class a{constructor(b){var _;this.refs={},this.dynamicAnchors={};let f;typeof b.schema=="object"&&(f=b.schema),this.schema=b.schema,this.schemaId=b.schemaId,this.root=b.root||this,this.baseId=(_=b.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(f?.[b.schemaId||"$id"]),this.schemaPath=b.schemaPath,this.localRefs=b.localRefs,this.meta=b.meta,this.$async=f?.$async,this.refs={}}}Vt.SchemaEnv=a;function i(m){const b=u.call(this,m);if(b)return b;const _=(0,n.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:f,lines:C}=this.opts.code,{ownProperties:k}=this.opts,v=new e.CodeGen(this.scope,{es5:f,lines:C,ownProperties:k});let S;m.$async&&(S=v.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const $=v.scopeName("validate");m.validateName=$;const E={gen:v,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:v.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,e.stringify)(m.schema)}:{ref:m.schema}),validateName:$,ValidationError:S,schema:m.schema,schemaEnv:m,rootId:_,baseId:m.baseId||_,schemaPath:e.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let D;try{this._compilations.add(m),(0,s.validateFunctionCode)(E),v.optimize(this.opts.code.optimize);const M=v.toString();D=`${v.scopeRefs(r.default.scope)}return ${M}`,this.opts.code.process&&(D=this.opts.code.process(D,m));const O=new Function(`${r.default.self}`,`${r.default.scope}`,D)(this,this.scope.get());if(this.scope.value($,{ref:O}),O.errors=null,O.schema=m.schema,O.schemaEnv=m,m.$async&&(O.$async=!0),this.opts.code.source===!0&&(O.source={validateName:$,validateCode:M,scopeValues:v._values}),this.opts.unevaluated){const{props:L,items:K}=E;O.evaluated={props:L instanceof e.Name?void 0:L,items:K instanceof e.Name?void 0:K,dynamicProps:L instanceof e.Name,dynamicItems:K instanceof e.Name},O.source&&(O.source.evaluated=(0,e.stringify)(O.evaluated))}return m.validate=O,m}catch(M){throw delete m.validate,delete m.validateName,D&&this.logger.error("Error compiling schema, function code:",D),M}finally{this._compilations.delete(m)}}Vt.compileSchema=i;function l(m,b,_){var f;_=(0,n.resolveUrl)(this.opts.uriResolver,b,_);const C=m.refs[_];if(C)return C;let k=p.call(this,m,_);if(k===void 0){const v=(f=m.localRefs)===null||f===void 0?void 0:f[_],{schemaId:S}=this.opts;v&&(k=new a({schema:v,schemaId:S,root:m,baseId:b}))}if(k!==void 0)return m.refs[_]=c.call(this,k)}Vt.resolveRef=l;function c(m){return(0,n.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:i.call(this,m)}function u(m){for(const b of this._compilations)if(g(b,m))return b}Vt.getCompilingSchema=u;function g(m,b){return m.schema===b.schema&&m.root===b.root&&m.baseId===b.baseId}function p(m,b){let _;for(;typeof(_=this.refs[b])=="string";)b=_;return _||this.schemas[b]||h.call(this,m,b)}function h(m,b){const _=this.opts.uriResolver.parse(b),f=(0,n._getFullPath)(this.opts.uriResolver,_);let C=(0,n.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&f===C)return w.call(this,_,m);const k=(0,n.normalizeId)(f),v=this.refs[k]||this.schemas[k];if(typeof v=="string"){const S=h.call(this,m,v);return typeof S?.schema!="object"?void 0:w.call(this,_,S)}if(typeof v?.schema=="object"){if(v.validate||i.call(this,v),k===(0,n.normalizeId)(b)){const{schema:S}=v,{schemaId:$}=this.opts,E=S[$];return E&&(C=(0,n.resolveUrl)(this.opts.uriResolver,C,E)),new a({schema:S,schemaId:$,root:m,baseId:C})}return w.call(this,_,v)}}Vt.resolveSchema=h;const y=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(m,{baseId:b,schema:_,root:f}){var C;if(((C=m.fragment)===null||C===void 0?void 0:C[0])!=="/")return;for(const S of m.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const $=_[(0,o.unescapeFragment)(S)];if($===void 0)return;_=$;const E=typeof _=="object"&&_[this.opts.schemaId];!y.has(S)&&E&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,E))}let k;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const S=(0,n.resolveUrl)(this.opts.uriResolver,b,_.$ref);k=h.call(this,f,S)}const{schemaId:v}=this.opts;if(k=k||new a({schema:_,schemaId:v,root:f,baseId:b}),k.schema!==k.root.schema)return k}return Vt}const QI={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Ca={},Xo={exports:{}},Lc,qg;function Lg(){if(qg)return Lc;qg=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(p){let h="",y=0,w=0;for(w=0;w<p.length;w++)if(y=p[w].charCodeAt(0),y!==48){if(!(y>=48&&y<=57||y>=65&&y<=70||y>=97&&y<=102))return"";h+=p[w];break}for(w+=1;w<p.length;w++){if(y=p[w].charCodeAt(0),!(y>=48&&y<=57||y>=65&&y<=70||y>=97&&y<=102))return"";h+=p[w]}return h}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,h,y){if(p.length){const w=r(p);if(w!=="")h.push(w);else return y.error=!0,!1;p.length=0}return!0}function a(p){let h=0;const y={error:!1,address:"",zone:""},w=[],m=[];let b=!1,_=!1,f=s;for(let C=0;C<p.length;C++){const k=p[C];if(!(k==="["||k==="]"))if(k===":"){if(b===!0&&(_=!0),!f(m,w,y))break;if(++h>7){y.error=!0;break}C>0&&p[C-1]===":"&&(b=!0),w.push(":");continue}else if(k==="%"){if(!f(m,w,y))break;f=o}else{m.push(k);continue}}return m.length&&(f===o?y.zone=m.join(""):_?w.push(m.join("")):w.push(r(m))),y.address=w.join(""),y}function i(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const h=a(p);if(h.error)return{host:p,isIPV6:!1};{let y=h.address,w=h.address;return h.zone&&(y+="%"+h.zone,w+="%25"+h.zone),{host:y,isIPV6:!0,escapedHost:w}}}function l(p,h){let y=0;for(let w=0;w<p.length;w++)p[w]===h&&y++;return y}function c(p){let h=p;const y=[];let w=-1,m=0;for(;m=h.length;){if(m===1){if(h===".")break;if(h==="/"){y.push("/");break}else{y.push(h);break}}else if(m===2){if(h[0]==="."){if(h[1]===".")break;if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&(h[1]==="."||h[1]==="/")){y.push("/");break}}else if(m===3&&h==="/.."){y.length!==0&&y.pop(),y.push("/");break}if(h[0]==="."){if(h[1]==="."){if(h[2]==="/"){h=h.slice(3);continue}}else if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&h[1]==="."){if(h[2]==="/"){h=h.slice(2);continue}else if(h[2]==="."&&h[3]==="/"){h=h.slice(3),y.length!==0&&y.pop();continue}}if((w=h.indexOf("/",1))===-1){y.push(h);break}else y.push(h.slice(0,w)),h=h.slice(w)}return y.join("")}function u(p,h){const y=h!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=y(p.scheme)),p.userinfo!==void 0&&(p.userinfo=y(p.userinfo)),p.host!==void 0&&(p.host=y(p.host)),p.path!==void 0&&(p.path=y(p.path)),p.query!==void 0&&(p.query=y(p.query)),p.fragment!==void 0&&(p.fragment=y(p.fragment)),p}function g(p){const h=[];if(p.userinfo!==void 0&&(h.push(p.userinfo),h.push("@")),p.host!==void 0){let y=unescape(p.host);if(!t(y)){const w=i(y);w.isIPV6===!0?y=`[${w.escapedHost}]`:y=p.host}h.push(y)}return(typeof p.port=="number"||typeof p.port=="string")&&(h.push(":"),h.push(String(p.port))),h.length?h.join(""):void 0}return Lc={nonSimpleDomain:n,recomposeAuthority:g,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},Lc}var jc,jg;function XI(){if(jg)return jc;jg=1;const{isUUID:e}=Lg(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function o(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function s(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const v=String(k.scheme).toLowerCase()==="https";return(k.port===(v?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=o(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function l(k){if((k.port===(o(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[v,S]=k.resourceName.split("?");k.path=v&&v!=="/"?v:void 0,k.query=S,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,v){if(!k.path)return k.error="URN can not be parsed",k;const S=k.path.match(t);if(S){const $=v.scheme||k.scheme||"urn";k.nid=S[1].toLowerCase(),k.nss=S[2];const E=`${$}:${v.nid||k.nid}`,D=C(E);k.path=void 0,D&&(k=D.parse(k,v))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,v){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=v.scheme||k.scheme||"urn",$=k.nid.toLowerCase(),E=`${S}:${v.nid||$}`,D=C(E);D&&(k=D.serialize(k,v));const M=k,N=k.nss;return M.path=`${$||v.nid}:${N}`,v.skipEscape=!0,M}function g(k,v){const S=k;return S.uuid=S.nss,S.nss=void 0,!v.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(k){const v=k;return v.nss=(k.uuid||"").toLowerCase(),v}const h={scheme:"http",domainHost:!0,parse:s,serialize:a},y={scheme:"https",domainHost:h.domainHost,parse:s,serialize:a},w={scheme:"ws",domainHost:!0,parse:i,serialize:l},m={scheme:"wss",domainHost:w.domainHost,parse:w.parse,serialize:w.serialize},f={http:h,https:y,ws:w,wss:m,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:g,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(f,null);function C(k){return k&&(f[k]||f[k.toLowerCase()])||void 0}return jc={wsIsSecure:o,SCHEMES:f,isValidSchemeName:n,getSchemeHandler:C},jc}var Ug;function e7(){if(Ug)return Xo.exports;Ug=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Lg(),{SCHEMES:a,getSchemeHandler:i}=XI();function l(m,b){return typeof m=="string"?m=p(y(m,b),b):typeof m=="object"&&(m=y(p(m,b),b)),m}function c(m,b,_){const f=_?Object.assign({scheme:"null"},_):{scheme:"null"},C=u(y(m,f),y(b,f),f,!0);return f.skipEscape=!0,p(C,f)}function u(m,b,_,f){const C={};return f||(m=y(p(m,_),_),b=y(p(b,_),_)),_=_||{},!_.tolerant&&b.scheme?(C.scheme=b.scheme,C.userinfo=b.userinfo,C.host=b.host,C.port=b.port,C.path=t(b.path||""),C.query=b.query):(b.userinfo!==void 0||b.host!==void 0||b.port!==void 0?(C.userinfo=b.userinfo,C.host=b.host,C.port=b.port,C.path=t(b.path||""),C.query=b.query):(b.path?(b.path[0]==="/"?C.path=t(b.path):((m.userinfo!==void 0||m.host!==void 0||m.port!==void 0)&&!m.path?C.path="/"+b.path:m.path?C.path=m.path.slice(0,m.path.lastIndexOf("/")+1)+b.path:C.path=b.path,C.path=t(C.path)),C.query=b.query):(C.path=m.path,b.query!==void 0?C.query=b.query:C.query=m.query),C.userinfo=m.userinfo,C.host=m.host,C.port=m.port),C.scheme=m.scheme),C.fragment=b.fragment,C}function g(m,b,_){return typeof m=="string"?(m=unescape(m),m=p(n(y(m,_),!0),{..._,skipEscape:!0})):typeof m=="object"&&(m=p(n(m,!0),{..._,skipEscape:!0})),typeof b=="string"?(b=unescape(b),b=p(n(y(b,_),!0),{..._,skipEscape:!0})):typeof b=="object"&&(b=p(n(b,!0),{..._,skipEscape:!0})),m.toLowerCase()===b.toLowerCase()}function p(m,b){const _={host:m.host,scheme:m.scheme,userinfo:m.userinfo,port:m.port,path:m.path,query:m.query,nid:m.nid,nss:m.nss,uuid:m.uuid,fragment:m.fragment,reference:m.reference,resourceName:m.resourceName,secure:m.secure,error:""},f=Object.assign({},b),C=[],k=i(f.scheme||_.scheme);k&&k.serialize&&k.serialize(_,f),_.path!==void 0&&(f.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),f.reference!=="suffix"&&_.scheme&&C.push(_.scheme,":");const v=r(_);if(v!==void 0&&(f.reference!=="suffix"&&C.push("//"),C.push(v),_.path&&_.path[0]!=="/"&&C.push("/")),_.path!==void 0){let S=_.path;!f.absolutePath&&(!k||!k.absolutePath)&&(S=t(S)),v===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),C.push(S)}return _.query!==void 0&&C.push("?",_.query),_.fragment!==void 0&&C.push("#",_.fragment),C.join("")}const h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function y(m,b){const _=Object.assign({},b),f={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let C=!1;_.reference==="suffix"&&(_.scheme?m=_.scheme+":"+m:m="//"+m);const k=m.match(h);if(k){if(f.scheme=k[1],f.userinfo=k[3],f.host=k[4],f.port=parseInt(k[5],10),f.path=k[6]||"",f.query=k[7],f.fragment=k[8],isNaN(f.port)&&(f.port=k[5]),f.host)if(o(f.host)===!1){const $=e(f.host);f.host=$.host.toLowerCase(),C=$.isIPV6}else C=!0;f.scheme===void 0&&f.userinfo===void 0&&f.host===void 0&&f.port===void 0&&f.query===void 0&&!f.path?f.reference="same-document":f.scheme===void 0?f.reference="relative":f.fragment===void 0?f.reference="absolute":f.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==f.reference&&(f.error=f.error||"URI is not a "+_.reference+" reference.");const v=i(_.scheme||f.scheme);if(!_.unicodeSupport&&(!v||!v.unicodeSupport)&&f.host&&(_.domainHost||v&&v.domainHost)&&C===!1&&s(f.host))try{f.host=URL.domainToASCII(f.host.toLowerCase())}catch(S){f.error=f.error||"Host's domain name can not be converted to ASCII: "+S}(!v||v&&!v.skipNormalize)&&(m.indexOf("%")!==-1&&(f.scheme!==void 0&&(f.scheme=unescape(f.scheme)),f.host!==void 0&&(f.host=unescape(f.host))),f.path&&(f.path=escape(unescape(f.path))),f.fragment&&(f.fragment=encodeURI(decodeURIComponent(f.fragment)))),v&&v.parse&&v.parse(f,_)}else f.error=f.error||"URI can not be parsed.";return f}const w={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:g,serialize:p,parse:y};return Xo.exports=w,Xo.exports.default=w,Xo.exports.fastUri=w,Xo.exports}var Dg;function t7(){if(Dg)return Ca;Dg=1,Object.defineProperty(Ca,"__esModule",{value:!0});const e=e7();return e.code='require("ajv/dist/runtime/uri").default',Ca.default=e,Ca}var zg;function r7(){return zg||(zg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=va();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ne();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Ac(),o=ka(),s=wg(),a=qc(),i=Ne(),l=_a(),c=ya(),u=Fe(),g=QI,p=t7(),h=(F,A)=>new RegExp(F,A);h.code="new RegExp";const y=["removeAdditional","useDefaults","coerceTypes"],w=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},b={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function f(F){var A,B,z,I,x,Z,ee,Y,ye,Ie,U,V,G,Q,ce,ve,R,re,ge,we,Re,Ge,ae,st,kt;const ne=F.strict,Ue=(A=F.code)===null||A===void 0?void 0:A.optimize,Le=Ue===!0||Ue===void 0?1:Ue||0,cr=(z=(B=F.code)===null||B===void 0?void 0:B.regExp)!==null&&z!==void 0?z:h,Nr=(I=F.uriResolver)!==null&&I!==void 0?I:p.default;return{strictSchema:(Z=(x=F.strictSchema)!==null&&x!==void 0?x:ne)!==null&&Z!==void 0?Z:!0,strictNumbers:(Y=(ee=F.strictNumbers)!==null&&ee!==void 0?ee:ne)!==null&&Y!==void 0?Y:!0,strictTypes:(Ie=(ye=F.strictTypes)!==null&&ye!==void 0?ye:ne)!==null&&Ie!==void 0?Ie:"log",strictTuples:(V=(U=F.strictTuples)!==null&&U!==void 0?U:ne)!==null&&V!==void 0?V:"log",strictRequired:(Q=(G=F.strictRequired)!==null&&G!==void 0?G:ne)!==null&&Q!==void 0?Q:!1,code:F.code?{...F.code,optimize:Le,regExp:cr}:{optimize:Le,regExp:cr},loopRequired:(ce=F.loopRequired)!==null&&ce!==void 0?ce:_,loopEnum:(ve=F.loopEnum)!==null&&ve!==void 0?ve:_,meta:(R=F.meta)!==null&&R!==void 0?R:!0,messages:(re=F.messages)!==null&&re!==void 0?re:!0,inlineRefs:(ge=F.inlineRefs)!==null&&ge!==void 0?ge:!0,schemaId:(we=F.schemaId)!==null&&we!==void 0?we:"$id",addUsedSchema:(Re=F.addUsedSchema)!==null&&Re!==void 0?Re:!0,validateSchema:(Ge=F.validateSchema)!==null&&Ge!==void 0?Ge:!0,validateFormats:(ae=F.validateFormats)!==null&&ae!==void 0?ae:!0,unicodeRegExp:(st=F.unicodeRegExp)!==null&&st!==void 0?st:!0,int32range:(kt=F.int32range)!==null&&kt!==void 0?kt:!0,uriResolver:Nr}}class C{constructor(A={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,A=this.opts={...A,...f(A)};const{es5:B,lines:z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:w,es5:B,lines:z}),this.logger=N(A.logger);const I=A.validateFormats;A.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,m,A,"NOT SUPPORTED"),k.call(this,b,A,"DEPRECATED","warn"),this._metaOpts=D.call(this),A.formats&&$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),A.keywords&&E.call(this,A.keywords),typeof A.meta=="object"&&this.addMetaSchema(A.meta),S.call(this),A.validateFormats=I}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:A,meta:B,schemaId:z}=this.opts;let I=g;z==="id"&&(I={...g},I.id=I.$id,delete I.$id),B&&A&&this.addMetaSchema(I,I[z],!1)}defaultMeta(){const{meta:A,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof A=="object"?A[B]||A:void 0}validate(A,B){let z;if(typeof A=="string"){if(z=this.getSchema(A),!z)throw new Error(`no schema with key or ref "${A}"`)}else z=this.compile(A);const I=z(B);return"$async"in z||(this.errors=z.errors),I}compile(A,B){const z=this._addSchema(A,B);return z.validate||this._compileSchemaEnv(z)}compileAsync(A,B){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:z}=this.opts;return I.call(this,A,B);async function I(Ie,U){await x.call(this,Ie.$schema);const V=this._addSchema(Ie,U);return V.validate||Z.call(this,V)}async function x(Ie){Ie&&!this.getSchema(Ie)&&await I.call(this,{$ref:Ie},!0)}async function Z(Ie){try{return this._compileSchemaEnv(Ie)}catch(U){if(!(U instanceof o.default))throw U;return ee.call(this,U),await Y.call(this,U.missingSchema),Z.call(this,Ie)}}function ee({missingSchema:Ie,missingRef:U}){if(this.refs[Ie])throw new Error(`AnySchema ${Ie} is loaded but ${U} cannot be resolved`)}async function Y(Ie){const U=await ye.call(this,Ie);this.refs[Ie]||await x.call(this,U.$schema),this.refs[Ie]||this.addSchema(U,Ie,B)}async function ye(Ie){const U=this._loading[Ie];if(U)return U;try{return await(this._loading[Ie]=z(Ie))}finally{delete this._loading[Ie]}}}addSchema(A,B,z,I=this.opts.validateSchema){if(Array.isArray(A)){for(const Z of A)this.addSchema(Z,void 0,z,I);return this}let x;if(typeof A=="object"){const{schemaId:Z}=this.opts;if(x=A[Z],x!==void 0&&typeof x!="string")throw new Error(`schema ${Z} must be string`)}return B=(0,l.normalizeId)(B||x),this._checkUnique(B),this.schemas[B]=this._addSchema(A,z,B,I,!0),this}addMetaSchema(A,B,z=this.opts.validateSchema){return this.addSchema(A,B,!0,z),this}validateSchema(A,B){if(typeof A=="boolean")return!0;let z;if(z=A.$schema,z!==void 0&&typeof z!="string")throw new Error("$schema must be a string");if(z=z||this.opts.defaultMeta||this.defaultMeta(),!z)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const I=this.validate(z,A);if(!I&&B){const x="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(x);else throw new Error(x)}return I}getSchema(A){let B;for(;typeof(B=v.call(this,A))=="string";)A=B;if(B===void 0){const{schemaId:z}=this.opts,I=new a.SchemaEnv({schema:{},schemaId:z});if(B=a.resolveSchema.call(this,I,A),!B)return;this.refs[A]=B}return B.validate||this._compileSchemaEnv(B)}removeSchema(A){if(A instanceof RegExp)return this._removeAllSchemas(this.schemas,A),this._removeAllSchemas(this.refs,A),this;switch(typeof A){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const B=v.call(this,A);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[A],delete this.refs[A],this}case"object":{const B=A;this._cache.delete(B);let z=A[this.opts.schemaId];return z&&(z=(0,l.normalizeId)(z),delete this.schemas[z],delete this.refs[z]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(A){for(const B of A)this.addKeyword(B);return this}addKeyword(A,B){let z;if(typeof A=="string")z=A,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=z);else if(typeof A=="object"&&B===void 0){if(B=A,z=B.keyword,Array.isArray(z)&&!z.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(L.call(this,z,B),!B)return(0,u.eachItem)(z,x=>K.call(this,x)),this;le.call(this,B);const I={...B,type:(0,c.getJSONTypes)(B.type),schemaType:(0,c.getJSONTypes)(B.schemaType)};return(0,u.eachItem)(z,I.type.length===0?x=>K.call(this,x,I):x=>I.type.forEach(Z=>K.call(this,x,I,Z))),this}getKeyword(A){const B=this.RULES.all[A];return typeof B=="object"?B.definition:!!B}removeKeyword(A){const{RULES:B}=this;delete B.keywords[A],delete B.all[A];for(const z of B.rules){const I=z.rules.findIndex(x=>x.keyword===A);I>=0&&z.rules.splice(I,1)}return this}addFormat(A,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[A]=B,this}errorsText(A=this.errors,{separator:B=", ",dataVar:z="data"}={}){return!A||A.length===0?"No errors":A.map(I=>`${z}${I.instancePath} ${I.message}`).reduce((I,x)=>I+B+x)}$dataMetaSchema(A,B){const z=this.RULES.all;A=JSON.parse(JSON.stringify(A));for(const I of B){const x=I.split("/").slice(1);let Z=A;for(const ee of x)Z=Z[ee];for(const ee in z){const Y=z[ee];if(typeof Y!="object")continue;const{$data:ye}=Y.definition,Ie=Z[ee];ye&&Ie&&(Z[ee]=Ee(Ie))}}return A}_removeAllSchemas(A,B){for(const z in A){const I=A[z];(!B||B.test(z))&&(typeof I=="string"?delete A[z]:I&&!I.meta&&(this._cache.delete(I.schema),delete A[z]))}}_addSchema(A,B,z,I=this.opts.validateSchema,x=this.opts.addUsedSchema){let Z;const{schemaId:ee}=this.opts;if(typeof A=="object")Z=A[ee];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof A!="boolean")throw new Error("schema must be object or boolean")}let Y=this._cache.get(A);if(Y!==void 0)return Y;z=(0,l.normalizeId)(Z||z);const ye=l.getSchemaRefs.call(this,A,z);return Y=new a.SchemaEnv({schema:A,schemaId:ee,meta:B,baseId:z,localRefs:ye}),this._cache.set(Y.schema,Y),x&&!z.startsWith("#")&&(z&&this._checkUnique(z),this.refs[z]=Y),I&&this.validateSchema(A,!0),Y}_checkUnique(A){if(this.schemas[A]||this.refs[A])throw new Error(`schema with key or id "${A}" already exists`)}_compileSchemaEnv(A){if(A.meta?this._compileMetaSchema(A):a.compileSchema.call(this,A),!A.validate)throw new Error("ajv implementation error");return A.validate}_compileMetaSchema(A){const B=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,A)}finally{this.opts=B}}}C.ValidationError=n.default,C.MissingRefError=o.default,e.default=C;function k(F,A,B,z="error"){for(const I in F){const x=I;x in A&&this.logger[z](`${B}: option ${I}. ${F[x]}`)}}function v(F){return F=(0,l.normalizeId)(F),this.schemas[F]||this.refs[F]}function S(){const F=this.opts.schemas;if(F)if(Array.isArray(F))this.addSchema(F);else for(const A in F)this.addSchema(F[A],A)}function $(){for(const F in this.opts.formats){const A=this.opts.formats[F];A&&this.addFormat(F,A)}}function E(F){if(Array.isArray(F)){this.addVocabulary(F);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const A in F){const B=F[A];B.keyword||(B.keyword=A),this.addKeyword(B)}}function D(){const F={...this.opts};for(const A of y)delete F[A];return F}const M={log(){},warn(){},error(){}};function N(F){if(F===!1)return M;if(F===void 0)return console;if(F.log&&F.warn&&F.error)return F;throw new Error("logger must implement log, warn and error methods")}const O=/^[a-z_$][a-z0-9_$:-]*$/i;function L(F,A){const{RULES:B}=this;if((0,u.eachItem)(F,z=>{if(B.keywords[z])throw new Error(`Keyword ${z} is already defined`);if(!O.test(z))throw new Error(`Keyword ${z} has invalid name`)}),!!A&&A.$data&&!("code"in A||"validate"in A))throw new Error('$data keyword must have "code" or "validate" function')}function K(F,A,B){var z;const I=A?.post;if(B&&I)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:x}=this;let Z=I?x.post:x.rules.find(({type:Y})=>Y===B);if(Z||(Z={type:B,rules:[]},x.rules.push(Z)),x.keywords[F]=!0,!A)return;const ee={keyword:F,definition:{...A,type:(0,c.getJSONTypes)(A.type),schemaType:(0,c.getJSONTypes)(A.schemaType)}};A.before?H.call(this,Z,ee,A.before):Z.rules.push(ee),x.all[F]=ee,(z=A.implements)===null||z===void 0||z.forEach(Y=>this.addKeyword(Y))}function H(F,A,B){const z=F.rules.findIndex(I=>I.keyword===B);z>=0?F.rules.splice(z,0,A):(F.rules.push(A),this.logger.warn(`rule ${B} is not defined`))}function le(F){let{metaSchema:A}=F;A!==void 0&&(F.$data&&this.opts.$data&&(A=Ee(A)),F.validateSchema=this.compile(A,!0))}const W={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ee(F){return{anyOf:[F,W]}}})(Ec)),Ec}var Ta={},Sa={},Ia={},Fg;function n7(){if(Fg)return Ia;Fg=1,Object.defineProperty(Ia,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Ia.default=e,Ia}var Kr={},Vg;function o7(){if(Vg)return Kr;Vg=1,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.callRef=Kr.getValidate=void 0;const e=ka(),t=or(),r=Ne(),n=Wr(),o=qc(),s=Fe(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:g,it:p}=c,{baseId:h,schemaEnv:y,validateName:w,opts:m,self:b}=p,{root:_}=y;if((g==="#"||g==="#/")&&h===_.baseId)return C();const f=o.resolveRef.call(b,_,h,g);if(f===void 0)throw new e.default(p.opts.uriResolver,h,g);if(f instanceof o.SchemaEnv)return k(f);return v(f);function C(){if(y===_)return l(c,w,y,y.$async);const S=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${S}.validate`,_,_.$async)}function k(S){const $=i(c,S);l(c,$,S,S.$async)}function v(S){const $=u.scopeValue("schema",m.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),E=u.name("valid"),D=c.subschema({schema:S,dataTypes:[],schemaPath:r.nil,topSchemaRef:$,errSchemaPath:g},E);c.mergeEvaluated(D),c.ok(E)}}};function i(c,u){const{gen:g}=c;return u.validate?g.scopeValue("validate",{ref:u.validate}):(0,r._)`${g.scopeValue("wrapper",{ref:u})}.validate`}Kr.getValidate=i;function l(c,u,g,p){const{gen:h,it:y}=c,{allErrors:w,schemaEnv:m,opts:b}=y,_=b.passContext?n.default.this:r.nil;p?f():C();function f(){if(!m.$async)throw new Error("async schema referenced by sync schema");const S=h.let("valid");h.try(()=>{h.code((0,r._)`await ${(0,t.callValidateCode)(c,u,_)}`),v(u),w||h.assign(S,!0)},$=>{h.if((0,r._)`!(${$} instanceof ${y.ValidationError})`,()=>h.throw($)),k($),w||h.assign(S,!1)}),c.ok(S)}function C(){c.result((0,t.callValidateCode)(c,u,_),()=>v(u),()=>k(u))}function k(S){const $=(0,r._)`${S}.errors`;h.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${$} : ${n.default.vErrors}.concat(${$})`),h.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function v(S){var $;if(!y.opts.unevaluated)return;const E=($=g?.validate)===null||$===void 0?void 0:$.evaluated;if(y.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(y.props=s.mergeEvaluated.props(h,E.props,y.props));else{const D=h.var("props",(0,r._)`${S}.evaluated.props`);y.props=s.mergeEvaluated.props(h,D,y.props,r.Name)}if(y.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(y.items=s.mergeEvaluated.items(h,E.items,y.items));else{const D=h.var("items",(0,r._)`${S}.evaluated.items`);y.items=s.mergeEvaluated.items(h,D,y.items,r.Name)}}}return Kr.callRef=l,Kr.default=a,Kr}var Zg;function s7(){if(Zg)return Sa;Zg=1,Object.defineProperty(Sa,"__esModule",{value:!0});const e=n7(),t=o7(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Sa.default=r,Sa}var xa={},Ea={},Bg;function a7(){if(Bg)return Ea;Bg=1,Object.defineProperty(Ea,"__esModule",{value:!0});const e=Ne(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:a})=>(0,e.str)`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${a}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:a,data:i,schemaCode:l}=s;s.fail$data((0,e._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return Ea.default=o,Ea}var $a={},Hg;function i7(){if(Hg)return $a;Hg=1,Object.defineProperty($a,"__esModule",{value:!0});const e=Ne(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${a} === 0 || (${c} = ${s}/${a}, ${u}))`)}};return $a.default=r,$a}var Ra={},Pa={},Jg;function l7(){if(Jg)return Pa;Jg=1,Object.defineProperty(Pa,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,s;for(;o<r;)n++,s=t.charCodeAt(o++),s>=55296&&s<=56319&&o<r&&(s=t.charCodeAt(o),(s&64512)===56320&&o++);return n}return Pa.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Pa}var Gg;function c7(){if(Gg)return Ra;Gg=1,Object.defineProperty(Ra,"__esModule",{value:!0});const e=Ne(),t=Fe(),r=l7(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:a}){const i=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:a,data:i,schemaCode:l,it:c}=s,u=a==="maxLength"?e.operators.GT:e.operators.LT,g=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${g} ${u} ${l}`)}};return Ra.default=o,Ra}var Ma={},Wg;function u7(){if(Wg)return Ma;Wg=1,Object.defineProperty(Ma,"__esModule",{value:!0});const e=or(),t=Ne(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:o})=>(0,t.str)`must match pattern "${o}"`,params:({schemaCode:o})=>(0,t._)`{pattern: ${o}}`},code(o){const{data:s,$data:a,schema:i,schemaCode:l,it:c}=o,u=c.opts.unicodeRegExp?"u":"",g=a?(0,t._)`(new RegExp(${l}, ${u}))`:(0,e.usePattern)(o,i);o.fail$data((0,t._)`!${g}.test(${s})`)}};return Ma.default=n,Ma}var Na={},Kg;function d7(){if(Kg)return Na;Kg=1,Object.defineProperty(Na,"__esModule",{value:!0});const e=Ne(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${i} ${a}`)}};return Na.default=r,Na}var Oa={},Yg;function p7(){if(Yg)return Oa;Yg=1,Object.defineProperty(Oa,"__esModule",{value:!0});const e=or(),t=Ne(),r=Fe(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:g}=s,{opts:p}=g;if(!u&&i.length===0)return;const h=i.length>=p.loopRequired;if(g.allErrors?y():w(),p.strictRequired){const _=s.parentSchema.properties,{definedProperties:f}=s.it;for(const C of i)if(_?.[C]===void 0&&!f.has(C)){const k=g.schemaEnv.baseId+g.errSchemaPath,v=`required property "${C}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(g,v,g.opts.strictRequired)}}function y(){if(h||u)s.block$data(t.nil,m);else for(const _ of i)(0,e.checkReportMissingProp)(s,_)}function w(){const _=a.let("missing");if(h||u){const f=a.let("valid",!0);s.block$data(f,()=>b(_,f)),s.ok(f)}else a.if((0,e.checkMissingProp)(s,i,_)),(0,e.reportMissingProp)(s,_),a.else()}function m(){a.forOf("prop",l,_=>{s.setParams({missingProperty:_}),a.if((0,e.noPropertyInData)(a,c,_,p.ownProperties),()=>s.error())})}function b(_,f){s.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(f,(0,e.propertyInData)(a,c,_,p.ownProperties)),a.if((0,t.not)(f),()=>{s.error(),a.break()})},t.nil)}}};return Oa.default=o,Oa}var Aa={},Qg;function f7(){if(Qg)return Aa;Qg=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=Ne(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${i} ${a}`)}};return Aa.default=r,Aa}var qa={},La={},Xg;function Uc(){if(Xg)return La;Xg=1,Object.defineProperty(La,"__esModule",{value:!0});const e=$g();return e.code='require("ajv/dist/runtime/equal").default',La.default=e,La}var ey;function h7(){if(ey)return qa;ey=1,Object.defineProperty(qa,"__esModule",{value:!0});const e=ya(),t=Ne(),r=Fe(),n=Uc(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,t._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:g,schemaCode:p,it:h}=a;if(!c&&!u)return;const y=i.let("valid"),w=g.items?(0,e.getSchemaTypes)(g.items):[];a.block$data(y,m,(0,t._)`${p} === false`),a.ok(y);function m(){const C=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:C,j:k}),i.assign(y,!0),i.if((0,t._)`${C} > 1`,()=>(b()?_:f)(C,k))}function b(){return w.length>0&&!w.some(C=>C==="object"||C==="array")}function _(C,k){const v=i.name("item"),S=(0,e.checkDataTypes)(w,v,h.opts.strictNumbers,e.DataType.Wrong),$=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${C}--;`,()=>{i.let(v,(0,t._)`${l}[${C}]`),i.if(S,(0,t._)`continue`),w.length>1&&i.if((0,t._)`typeof ${v} == "string"`,(0,t._)`${v} += "_"`),i.if((0,t._)`typeof ${$}[${v}] == "number"`,()=>{i.assign(k,(0,t._)`${$}[${v}]`),a.error(),i.assign(y,!1).break()}).code((0,t._)`${$}[${v}] = ${C}`)})}function f(C,k){const v=(0,r.useFunc)(i,n.default),S=i.name("outer");i.label(S).for((0,t._)`;${C}--;`,()=>i.for((0,t._)`${k} = ${C}; ${k}--;`,()=>i.if((0,t._)`${v}(${l}[${C}], ${l}[${k}])`,()=>{a.error(),i.assign(y,!1).break(S)})))}}};return qa.default=s,qa}var ja={},ty;function m7(){if(ty)return ja;ty=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=Ne(),t=Fe(),r=Uc(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${i}, ${c})`):s.fail((0,e._)`${u} !== ${i}`)}};return ja.default=o,ja}var Ua={},ry;function g7(){if(ry)return Ua;ry=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e=Ne(),t=Fe(),r=Uc(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:g}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=g.opts.loopEnum;let h;const y=()=>h??(h=(0,t.useFunc)(a,r.default));let w;if(p||l)w=a.let("valid"),s.block$data(w,m);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);w=(0,e.or)(...c.map((f,C)=>b(_,C)))}s.pass(w);function m(){a.assign(w,!1),a.forOf("v",u,_=>a.if((0,e._)`${y()}(${i}, ${_})`,()=>a.assign(w,!0).break()))}function b(_,f){const C=c[f];return typeof C=="object"&&C!==null?(0,e._)`${y()}(${i}, ${_}[${f}])`:(0,e._)`${i} === ${C}`}}};return Ua.default=o,Ua}var ny;function y7(){if(ny)return xa;ny=1,Object.defineProperty(xa,"__esModule",{value:!0});const e=a7(),t=i7(),r=c7(),n=u7(),o=d7(),s=p7(),a=f7(),i=h7(),l=m7(),c=g7(),u=[e.default,t.default,r.default,n.default,o.default,s.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return xa.default=u,xa}var Da={},Qn={},oy;function sy(){if(oy)return Qn;oy=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.validateAdditionalItems=void 0;const e=Ne(),t=Fe(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:a,it:i}=s,{items:l}=a;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,a){const{gen:i,schema:l,data:c,keyword:u,it:g}=s;g.items=!0;const p=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${p} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(g,l)){const y=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(y),()=>h(y)),s.ok(y)}function h(y){i.forRange("i",a.length,p,w=>{s.subschema({keyword:u,dataProp:w,dataPropType:t.Type.Num},y),g.allErrors||i.if((0,e.not)(y),()=>i.break())})}}return Qn.validateAdditionalItems=o,Qn.default=n,Qn}var za={},Xn={},ay;function iy(){if(ay)return Xn;ay=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.validateTuple=void 0;const e=Ne(),t=Fe(),r=or(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:a,it:i}=s;if(Array.isArray(a))return o(s,"additionalItems",a);i.items=!0,!(0,t.alwaysValidSchema)(i,a)&&s.ok((0,r.validateArray)(s))}};function o(s,a,i=s.schema){const{gen:l,parentSchema:c,data:u,keyword:g,it:p}=s;w(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const h=l.name("valid"),y=l.const("len",(0,e._)`${u}.length`);i.forEach((m,b)=>{(0,t.alwaysValidSchema)(p,m)||(l.if((0,e._)`${y} > ${b}`,()=>s.subschema({keyword:g,schemaProp:b,dataProp:b},h)),s.ok(h))});function w(m){const{opts:b,errSchemaPath:_}=p,f=i.length,C=f===m.minItems&&(f===m.maxItems||m[a]===!1);if(b.strictTuples&&!C){const k=`"${g}" is ${f}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(p,k,b.strictTuples)}}}return Xn.validateTuple=o,Xn.default=n,Xn}var ly;function _7(){if(ly)return za;ly=1,Object.defineProperty(za,"__esModule",{value:!0});const e=iy(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return za.default=t,za}var Fa={},cy;function v7(){if(cy)return Fa;cy=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=Ne(),t=Fe(),r=or(),n=sy(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return Fa.default=s,Fa}var Va={},uy;function w7(){if(uy)return Va;uy=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Ne(),t=Fe(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:a,parentSchema:i,data:l,it:c}=o;let u,g;const{minContains:p,maxContains:h}=i;c.opts.next?(u=p===void 0?1:p,g=h):u=1;const y=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:g}),g===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(g!==void 0&&u>g){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let f=(0,e._)`${y} >= ${u}`;g!==void 0&&(f=(0,e._)`${f} && ${y} <= ${g}`),o.pass(f);return}c.items=!0;const w=s.name("valid");g===void 0&&u===1?b(w,()=>s.if(w,()=>s.break())):u===0?(s.let(w,!0),g!==void 0&&s.if((0,e._)`${l}.length > 0`,m)):(s.let(w,!1),m()),o.result(w,()=>o.reset());function m(){const f=s.name("_valid"),C=s.let("count",0);b(f,()=>s.if(f,()=>_(C)))}function b(f,C){s.forRange("i",0,y,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},f),C()})}function _(f){s.code((0,e._)`${f}++`),g===void 0?s.if((0,e._)`${f} >= ${u}`,()=>s.assign(w,!0).break()):(s.if((0,e._)`${f} > ${g}`,()=>s.assign(w,!1).break()),u===1?s.assign(w,!0):s.if((0,e._)`${f} >= ${u}`,()=>s.assign(w,!0)))}}};return Va.default=n,Va}var Dc={},dy;function b7(){return dy||(dy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ne(),r=Fe(),n=or();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const g=c===1?"property":"properties";return(0,t.str)`must have ${g} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:g}})=>(0,t._)`{property: ${l},
86
- missingProperty: ${g},
79
+ ${t}:`]}}function d2({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function p2(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var HS=be(()=>we(C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d(),logprobs:C({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ge(d(),j())).nullish()}).nullish()})),usage:C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),JS=be(()=>we(oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d().nullish(),index:j(),logprobs:C({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ge(d(),j())).nullish()}).nullish()})),usage:C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Dc]))),f2=be(()=>we(C({echo:pe().optional(),logitBias:ge(d(),j()).optional(),suffix:d().optional(),user:d().optional(),logprobs:oe([pe(),j()]).optional()}))),GS=class{constructor(e,t){this.specificationVersion="v3",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:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:m,providerOptions:p}){const f=[],g={...await Mr({provider:"openai",providerOptions:p,schema:f2}),...await Mr({provider:this.providerOptionsName,providerOptions:p,schema:f2})};o!=null&&f.push({type:"unsupported",feature:"topK"}),c?.length&&f.push({type:"unsupported",feature:"tools"}),u!=null&&f.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:y}=BS({prompt:e}),w=[...y??[],...i??[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:g?.logprobs===!0?0:g?.logprobs===!1?void 0:g?.logprobs,suffix:g.suffix,user:g.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:m,prompt:v,stop:w.length>0?w:void 0},warnings:f}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:a}=await Ut({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:r,failedResponseHandler:dr,successfulResponseHandler:Xt(HS),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=s.choices[0],l={openai:{}};return i.logprobs!=null&&(l.openai.logprobs=i.logprobs),{content:[{type:"text",text:i.text}],usage:u2(s.usage),finishReason:{unified:p2(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...d2(s),headers:o,body:a},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Ut({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:n,failedResponseHandler:dr,successfulResponseHandler:Bs(JS),abortSignal:e.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,m){if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},m.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},m.enqueue({type:"error",error:p.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",...d2(p)}),m.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const f=p.choices[0];f?.finish_reason!=null&&(a={unified:p2(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(i.openai.logprobs=f.logprobs),f?.text!=null&&f.text.length>0&&m.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:u2(l)})}})),request:{body:n},response:{headers:o}}}},WS=be(()=>we(C({dimensions:j().optional(),user:d().optional()}))),KS=be(()=>we(C({data:q(C({embedding:q(j())})),usage:C({prompt_tokens:j()}).nullish()}))),YS=class{constructor(e,t){this.specificationVersion="v3",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:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new uv({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Mr({provider:"openai",providerOptions:n,schema:WS}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Ut({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Nt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:dr,successfulResponseHandler:Xt(KS),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},h2=be(()=>we(C({created:j().nullish(),data:q(C({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:C({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:C({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),QS={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},XS=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function eI(e){return XS.some(t=>e.startsWith(t))}var tI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=QS[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:s,seed:a,providerOptions:i,headers:l,abortSignal:c}){var u,m,p,f,g,v,y,w,_,h,T;const k=[];s!=null&&k.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&k.push({type:"unsupported",feature:"seed"});const b=(p=(m=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:m.call(u))!=null?p:new Date;if(t!=null){const{value:I,responseHeaders:L}=await Nf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Nt(this.config.headers(),l),formData:j3({model:this.modelId,prompt:e,image:await Promise.all(t.map($=>$.type==="file"?new Blob([$.data instanceof Uint8Array?new Blob([$.data],{type:$.mediaType}):new Blob([Wn($.data)],{type:$.mediaType})],{type:$.mediaType}):vf($.url))),mask:r!=null?await rI(r):void 0,n,size:o,...(f=i.openai)!=null?f:{}}),failedResponseHandler:dr,successfulResponseHandler:Xt(h2),abortSignal:c,fetch:this.config.fetch});return{images:I.data.map($=>$.b64_json),warnings:k,usage:I.usage!=null?{inputTokens:(g=I.usage.input_tokens)!=null?g:void 0,outputTokens:(v=I.usage.output_tokens)!=null?v:void 0,totalTokens:(y=I.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:b,modelId:this.modelId,headers:L},providerMetadata:{openai:{images:I.data.map(($,O)=>{var A,U,Z,Y,ye,X;return{...$.revised_prompt?{revisedPrompt:$.revised_prompt}:{},created:(A=I.created)!=null?A:void 0,size:(U=I.size)!=null?U:void 0,quality:(Z=I.quality)!=null?Z:void 0,background:(Y=I.background)!=null?Y:void 0,outputFormat:(ye=I.output_format)!=null?ye:void 0,...m2((X=I.usage)==null?void 0:X.input_tokens_details,O,I.data.length)}})}}}}const{value:S,responseHeaders:x}=await Ut({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Nt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=i.openai)!=null?w:{},...eI(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:dr,successfulResponseHandler:Xt(h2),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(I=>I.b64_json),warnings:k,usage:S.usage!=null?{inputTokens:(_=S.usage.input_tokens)!=null?_:void 0,outputTokens:(h=S.usage.output_tokens)!=null?h:void 0,totalTokens:(T=S.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:b,modelId:this.modelId,headers:x},providerMetadata:{openai:{images:S.data.map((I,L)=>{var $,O,A,U,Z,Y;return{...I.revised_prompt?{revisedPrompt:I.revised_prompt}:{},created:($=S.created)!=null?$:void 0,size:(O=S.size)!=null?O:void 0,quality:(A=S.quality)!=null?A:void 0,background:(U=S.background)!=null?U:void 0,outputFormat:(Z=S.output_format)!=null?Z:void 0,...m2((Y=S.usage)==null?void 0:Y.input_tokens_details,L,S.data.length)}})}}}}};function m2(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),s=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),s=e.text_tokens-o*(r-1);n.textTokens=t===r-1?s:o}return n}async function rI(e){if(!e)return;if(e.type==="url")return vf(e.url);const t=e.data instanceof Uint8Array?e.data:Wn(e.data);return new Blob([t],{type:e.mediaType})}var g2=be(()=>we(C({callId:d(),operation:De("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}))),y2=be(()=>we(C({status:fe(["completed","failed"]),output:d().optional()}))),nI=lr({id:"openai.apply_patch",inputSchema:g2,outputSchema:y2}),oI=nI,sI=be(()=>we(C({code:d().nullish(),containerId:d()}))),aI=be(()=>we(C({outputs:q(De("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullish()}))),iI=be(()=>we(C({container:oe([d(),C({fileIds:q(d()).optional()})]).optional()}))),lI=lr({id:"openai.code_interpreter",inputSchema:sI,outputSchema:aI}),cI=(e={})=>lI(e),_2=C({key:d(),type:fe(["eq","ne","gt","gte","lt","lte","in","nin"]),value:oe([d(),j(),pe(),q(d())])}),v2=C({type:fe(["and","or"]),filters:q(oe([_2,Qi(()=>v2)]))}),uI=be(()=>we(C({vectorStoreIds:q(d()),maxNumResults:j().optional(),ranking:C({ranker:d().optional(),scoreThreshold:j().optional()}).optional(),filters:oe([_2,v2]).optional()}))),dI=be(()=>we(C({queries:q(d()),results:q(C({attributes:ge(d(),$e()),fileId:d(),filename:d(),score:j(),text:d()})).nullable()}))),pI=lr({id:"openai.file_search",inputSchema:C({}),outputSchema:dI}),fI=be(()=>we(C({background:fe(["auto","opaque","transparent"]).optional(),inputFidelity:fe(["low","high"]).optional(),inputImageMask:C({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:fe(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:fe(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:fe(["auto","low","medium","high"]).optional(),size:fe(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),hI=be(()=>we(C({}))),mI=be(()=>we(C({result:d()}))),gI=lr({id:"openai.image_generation",inputSchema:hI,outputSchema:mI}),yI=(e={})=>gI(e),w2=be(()=>we(C({action:C({type:R("exec"),command:q(d()),timeoutMs:j().optional(),user:d().optional(),workingDirectory:d().optional(),env:ge(d(),d()).optional()})}))),b2=be(()=>we(C({output:d()}))),_I=lr({id:"openai.local_shell",inputSchema:w2,outputSchema:b2}),k2=be(()=>we(C({action:C({commands:q(d()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),zc=be(()=>we(C({output:q(C({stdout:d(),stderr:d(),outcome:De("type",[C({type:R("timeout")}),C({type:R("exit"),exitCode:j()})])}))}))),vI=q(De("type",[C({type:R("skillReference"),skillId:d(),version:d().optional()}),C({type:R("inline"),name:d(),description:d(),source:C({type:R("base64"),mediaType:R("application/zip"),data:d()})})])).optional(),wI=be(()=>we(C({environment:oe([C({type:R("containerAuto"),fileIds:q(d()).optional(),memoryLimit:fe(["1g","4g","16g","64g"]).optional(),networkPolicy:De("type",[C({type:R("disabled")}),C({type:R("allowlist"),allowedDomains:q(d()),domainSecrets:q(C({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:vI}),C({type:R("containerReference"),containerId:d()}),C({type:R("local").optional(),skills:q(C({name:d(),description:d(),path:d()})).optional()})]).optional()}))),bI=lr({id:"openai.shell",inputSchema:k2,outputSchema:zc}),kI=be(()=>we(C({externalWebAccess:pe().optional(),filters:C({allowedDomains:q(d()).optional()}).optional(),searchContextSize:fe(["low","medium","high"]).optional(),userLocation:C({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),CI=be(()=>we(C({}))),TI=be(()=>we(C({action:De("type",[C({type:R("search"),query:d().optional()}),C({type:R("openPage"),url:d().nullish()}),C({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(De("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).optional()}))),SI=lr({id:"openai.web_search",inputSchema:CI,outputSchema:TI}),II=(e={})=>SI(e),xI=be(()=>we(C({searchContextSize:fe(["low","medium","high"]).optional(),userLocation:C({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),EI=be(()=>we(C({}))),$I=be(()=>we(C({action:De("type",[C({type:R("search"),query:d().optional()}),C({type:R("openPage"),url:d().nullish()}),C({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),RI=lr({id:"openai.web_search_preview",inputSchema:EI,outputSchema:$I}),Fc=Qi(()=>oe([d(),j(),pe(),Ls(),q(Fc),ge(d(),Fc)])),PI=be(()=>we(C({serverLabel:d(),allowedTools:oe([q(d()),C({readOnly:pe().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ge(d(),d()).optional(),requireApproval:oe([fe(["always","never"]),C({never:C({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),NI=be(()=>we(C({}))),MI=be(()=>we(C({type:R("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:oe([d(),Fc]).optional()}))),OI=lr({id:"openai.mcp",inputSchema:NI,outputSchema:MI}),AI=e=>OI(e),qI={applyPatch:oI,codeInterpreter:cI,fileSearch:pI,imageGeneration:yI,localShell:_I,shell:bI,webSearchPreview:RI,webSearch:II,mcp:AI};function C2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,i=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-i,cacheRead:i,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}function T2(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function LI({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var u,m,p,f,g,v,y,w,_,h,T,k;const b=[],S=[],x=new Set;for(const{role:I,content:L}of e)switch(I){case"system":{switch(r){case"system":{b.push({role:"system",content:L});break}case"developer":{b.push({role:"developer",content:L});break}case"remove":{S.push({type:"other",message:"system messages are removed for this model"});break}default:{const $=r;throw new Error(`Unsupported system message mode: ${$}`)}}break}case"user":{b.push({role:"user",content:L.map(($,O)=>{var A,U,Z;switch($.type){case"text":return{type:"input_text",text:$.text};case"file":if($.mediaType.startsWith("image/")){const Y=$.mediaType==="image/*"?"image/jpeg":$.mediaType;return{type:"input_image",...$.data instanceof URL?{image_url:$.data.toString()}:typeof $.data=="string"&&T2($.data,o)?{file_id:$.data}:{image_url:`data:${Y};base64,${Yn($.data)}`},detail:(U=(A=$.providerOptions)==null?void 0:A[n])==null?void 0:U.imageDetail}}else{if($.mediaType==="application/pdf")return $.data instanceof URL?{type:"input_file",file_url:$.data.toString()}:{type:"input_file",...typeof $.data=="string"&&T2($.data,o)?{file_id:$.data}:{filename:(Z=$.filename)!=null?Z:`part-${O}.pdf`,file_data:`data:application/pdf;base64,${Yn($.data)}`}};throw new br({functionality:`file part media type ${$.mediaType}`})}}})});break}case"assistant":{const $={};for(const O of L)switch(O.type){case"text":{const A=(u=O.providerOptions)==null?void 0:u[n],U=A?.itemId,Z=A?.phase;if(a&&U!=null)break;if(s&&U!=null){b.push({type:"item_reference",id:U});break}b.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:U,...Z!=null&&{phase:Z}});break}case"tool-call":{const A=(v=(p=(m=O.providerOptions)==null?void 0:m[n])==null?void 0:p.itemId)!=null?v:(g=(f=O.providerMetadata)==null?void 0:f[n])==null?void 0:g.itemId;if(a&&A!=null)break;if(O.providerExecuted){s&&A!=null&&b.push({type:"item_reference",id:A});break}if(s&&A!=null){b.push({type:"item_reference",id:A});break}const U=t.toProviderToolName(O.toolName);if(i&&U==="local_shell"){const Z=await St({value:O.input,schema:w2});b.push({type:"local_shell_call",call_id:O.toolCallId,id:A,action:{type:"exec",command:Z.action.command,timeout_ms:Z.action.timeoutMs,user:Z.action.user,working_directory:Z.action.workingDirectory,env:Z.action.env}});break}if(l&&U==="shell"){const Z=await St({value:O.input,schema:k2});b.push({type:"shell_call",call_id:O.toolCallId,id:A,status:"completed",action:{commands:Z.action.commands,timeout_ms:Z.action.timeoutMs,max_output_length:Z.action.maxOutputLength}});break}if(c&&U==="apply_patch"){const Z=await St({value:O.input,schema:g2});b.push({type:"apply_patch_call",call_id:Z.callId,id:A,status:"completed",operation:Z.operation});break}b.push({type:"function_call",call_id:O.toolCallId,name:U,arguments:JSON.stringify(O.input),id:A});break}case"tool-result":{if(O.output.type==="execution-denied"||O.output.type==="json"&&typeof O.output.value=="object"&&O.output.value!=null&&"type"in O.output.value&&O.output.value.type==="execution-denied"||a)break;const A=t.toProviderToolName(O.toolName);if(l&&A==="shell"){if(O.output.type==="json"){const U=await St({value:O.output.value,schema:zc});b.push({type:"shell_call_output",call_id:O.toolCallId,output:U.output.map(Z=>({stdout:Z.stdout,stderr:Z.stderr,outcome:Z.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Z.outcome.exitCode}}))})}break}if(s){const U=(_=(w=(y=O.providerOptions)==null?void 0:y[n])==null?void 0:w.itemId)!=null?_:O.toolCallId;b.push({type:"item_reference",id:U})}else S.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const A=await Mr({provider:n,providerOptions:O.providerOptions,schema:jI}),U=A?.itemId;if(a&&U!=null)break;if(U!=null){const Z=$[U];if(s)Z===void 0&&(b.push({type:"item_reference",id:U}),$[U]={type:"reasoning",id:U,summary:[]});else{const Y=[];O.text.length>0?Y.push({type:"summary_text",text:O.text}):Z!==void 0&&S.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),Z===void 0?($[U]={type:"reasoning",id:U,encrypted_content:A?.reasoningEncryptedContent,summary:Y},b.push($[U])):(Z.summary.push(...Y),A?.reasoningEncryptedContent!=null&&(Z.encrypted_content=A.reasoningEncryptedContent))}}else{const Z=A?.reasoningEncryptedContent;if(Z!=null){const Y=[];O.text.length>0&&Y.push({type:"summary_text",text:O.text}),b.push({type:"reasoning",encrypted_content:Z,summary:Y})}else S.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(O)}.`})}break}}break}case"tool":{for(const $ of L){if($.type==="tool-approval-response"){const Z=$;if(x.has(Z.approvalId))continue;x.add(Z.approvalId),s&&b.push({type:"item_reference",id:Z.approvalId}),b.push({type:"mcp_approval_response",approval_request_id:Z.approvalId,approve:Z.approved});continue}const O=$.output;if(O.type==="execution-denied"&&((T=(h=O.providerOptions)==null?void 0:h.openai)==null?void 0:T.approvalId))continue;const A=t.toProviderToolName($.toolName);if(i&&A==="local_shell"&&O.type==="json"){const Z=await St({value:O.value,schema:b2});b.push({type:"local_shell_call_output",call_id:$.toolCallId,output:Z.output});continue}if(l&&A==="shell"&&O.type==="json"){const Z=await St({value:O.value,schema:zc});b.push({type:"shell_call_output",call_id:$.toolCallId,output:Z.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Y.outcome.exitCode}}))});continue}if(c&&$.toolName==="apply_patch"&&O.type==="json"){const Z=await St({value:O.value,schema:y2});b.push({type:"apply_patch_call_output",call_id:$.toolCallId,status:Z.status,output:Z.output});continue}let U;switch(O.type){case"text":case"error-text":U=O.value;break;case"execution-denied":U=(k=O.reason)!=null?k:"Tool execution denied.";break;case"json":case"error-json":U=JSON.stringify(O.value);break;case"content":U=O.value.map(Z=>{var Y;switch(Z.type){case"text":return{type:"input_text",text:Z.text};case"image-data":return{type:"input_image",image_url:`data:${Z.mediaType};base64,${Z.data}`};case"image-url":return{type:"input_image",image_url:Z.url};case"file-data":return{type:"input_file",filename:(Y=Z.filename)!=null?Y:"data",file_data:`data:${Z.mediaType};base64,${Z.data}`};default:{S.push({type:"other",message:`unsupported tool content part type: ${Z.type}`});return}}}).filter(B3);break}b.push({type:"function_call_output",call_id:$.toolCallId,output:U})}break}default:{const $=I;throw new Error(`Unsupported role: ${$}`)}}return{input:b,warnings:S}}var jI=C({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function S2({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var DI=be(()=>we(oe([C({type:R("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish()}),C({type:fe(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:j(),input_tokens_details:C({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:C({reasoning_tokens:j().nullish()}).nullish()}),service_tier:d().nullish()})}),C({type:R("response.created"),response:C({id:d(),created_at:j(),model:d(),service_tier:d().nullish()})}),C({type:R("response.output_item.added"),output_index:j(),item:De("type",[C({type:R("message"),id:d(),phase:fe(["commentary","final_answer"]).nullish()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),C({type:R("web_search_call"),id:d(),status:d()}),C({type:R("computer_call"),id:d(),status:d()}),C({type:R("file_search_call"),id:d()}),C({type:R("image_generation_call"),id:d()}),C({type:R("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(De("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable(),status:d()}),C({type:R("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d()}),C({type:R("mcp_approval_request"),id:d()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:fe(["in_progress","completed"]),operation:De("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("shell_call"),id:d(),call_id:d(),status:fe(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:fe(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:De("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:j()})])}))})])}),C({type:R("response.output_item.done"),output_index:j(),item:De("type",[C({type:R("message"),id:d(),phase:fe(["commentary","final_answer"]).nullish()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:R("completed")}),C({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(De("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable()}),C({type:R("image_generation_call"),id:d(),result:d()}),C({type:R("web_search_call"),id:d(),status:d(),action:De("type",[C({type:R("search"),query:d().nullish(),sources:q(De("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).nullish()}),C({type:R("open_page"),url:d().nullish()}),C({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:R("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ge(d(),oe([d(),j(),pe()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),C({type:R("local_shell_call"),id:d(),call_id:d(),action:C({type:R("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ge(d(),d()).optional()})}),C({type:R("computer_call"),id:d(),status:R("completed")}),C({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:wt(),annotations:ge(d(),$e()).optional()})),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:fe(["in_progress","completed"]),operation:De("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("shell_call"),id:d(),call_id:d(),status:fe(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:fe(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:De("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:j()})])}))})])}),C({type:R("response.function_call_arguments.delta"),item_id:d(),output_index:j(),delta:d()}),C({type:R("response.image_generation_call.partial_image"),item_id:d(),output_index:j(),partial_image_b64:d()}),C({type:R("response.code_interpreter_call_code.delta"),item_id:d(),output_index:j(),delta:d()}),C({type:R("response.code_interpreter_call_code.done"),item_id:d(),output_index:j(),code:d()}),C({type:R("response.output_text.annotation.added"),annotation:De("type",[C({type:R("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),C({type:R("file_citation"),file_id:d(),filename:d(),index:j()}),C({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),C({type:R("file_path"),file_id:d(),index:j()})])}),C({type:R("response.reasoning_summary_part.added"),item_id:d(),summary_index:j()}),C({type:R("response.reasoning_summary_text.delta"),item_id:d(),summary_index:j(),delta:d()}),C({type:R("response.reasoning_summary_part.done"),item_id:d(),summary_index:j()}),C({type:R("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:j(),delta:d(),obfuscation:d().nullish()}),C({type:R("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:j(),diff:d()}),C({type:R("error"),sequence_number:j(),error:C({type:d(),code:d(),message:d(),param:d().nullish()})}),C({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),UI=be(()=>we(C({id:d().optional(),created_at:j().optional(),error:C({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(De("type",[C({type:R("message"),role:R("assistant"),id:d(),phase:fe(["commentary","final_answer"]).nullish(),content:q(C({type:R("output_text"),text:d(),logprobs:q(C({token:d(),logprob:j(),top_logprobs:q(C({token:d(),logprob:j()}))})).nullish(),annotations:q(De("type",[C({type:R("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),C({type:R("file_citation"),file_id:d(),filename:d(),index:j()}),C({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),C({type:R("file_path"),file_id:d(),index:j()})]))}))}),C({type:R("web_search_call"),id:d(),status:d(),action:De("type",[C({type:R("search"),query:d().nullish(),sources:q(De("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).nullish()}),C({type:R("open_page"),url:d().nullish()}),C({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:R("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ge(d(),oe([d(),j(),pe()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),C({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(De("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable()}),C({type:R("image_generation_call"),id:d(),result:d()}),C({type:R("local_shell_call"),id:d(),call_id:d(),action:C({type:R("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ge(d(),d()).optional()})}),C({type:R("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),C({type:R("computer_call"),id:d(),status:d().optional()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(C({type:R("summary_text"),text:d()}))}),C({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:wt(),annotations:ge(d(),$e()).optional()})),error:oe([d(),C({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:fe(["in_progress","completed"]),operation:De("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("shell_call"),id:d(),call_id:d(),status:fe(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:fe(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:De("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:j()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:j(),input_tokens_details:C({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:C({reasoning_tokens:j().nullish()}).nullish()}).optional()}))),I2=20,x2=be(()=>we(C({conversation:d().nullish(),include:q(fe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:oe([pe(),j().min(1).max(I2)]).optional(),maxToolCalls:j().nullish(),metadata:wt().nullish(),parallelToolCalls:pe().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:fe(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:fe(["auto","flex","priority","default"]).nullish(),store:pe().nullish(),strictJsonSchema:pe().nullish(),textVerbosity:fe(["low","medium","high"]).nullish(),truncation:fe(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:fe(["system","developer","remove"]).optional(),forceReasoning:pe().optional()})));async function zI({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await St({value:s.args,schema:uI});n.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{n.push({type:"local_shell"});break}case"openai.shell":{const a=await St({value:s.args,schema:wI});n.push({type:"shell",...a.environment&&{environment:FI(a.environment)}});break}case"openai.apply_patch":{n.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await St({value:s.args,schema:xI});n.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await St({value:s.args,schema:kI});n.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await St({value:s.args,schema:iI});n.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await St({value:s.args,schema:fI});n.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await St({value:s.args,schema:PI}),i=u=>({tool_names:u.toolNames}),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:i(l.never)}:void 0;n.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:r.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const s=o;throw new br({functionality:`tool choice type: ${s}`})}}}function FI(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const r=e;return{type:"container_auto",file_ids:r.fileIds,memory_limit:r.memoryLimit,network_policy:r.networkPolicy==null?void 0:r.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:r.networkPolicy.allowedDomains,domain_secrets:r.networkPolicy.domainSecrets},skills:VI(r.skills)}}return{type:"local",skills:e.skills}}function VI(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function E2(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;a!=null&&(n[a]=s.toolCallId)}return n}var ZI=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:m,responseFormat:p}){var f,g,v,y,w,_,h,T,k;const b=[],S=i2(this.modelId);o!=null&&b.push({type:"unsupported",feature:"topK"}),i!=null&&b.push({type:"unsupported",feature:"seed"}),s!=null&&b.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&b.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&b.push({type:"unsupported",feature:"stopSequences"});const x=this.config.provider.includes("azure")?"azure":"openai";let I=await Mr({provider:x,providerOptions:c,schema:x2});I==null&&x!=="openai"&&(I=await Mr({provider:"openai",providerOptions:c,schema:x2}));const L=(f=I?.forceReasoning)!=null?f:S.isReasoningModel;I?.conversation&&I?.previousResponseId&&b.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const $=O3({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:O,warnings:A}=await LI({prompt:l,toolNameMapping:$,systemMessageMode:(g=I?.systemMessageMode)!=null?g:L?"developer":S.systemMessageMode,providerOptionsName:x,fileIdPrefixes:this.config.fileIdPrefixes,store:(v=I?.store)!=null?v:!0,hasConversation:I?.conversation!=null,hasLocalShellTool:ye("openai.local_shell"),hasShellTool:ye("openai.shell"),hasApplyPatchTool:ye("openai.apply_patch")});b.push(...A);const U=(y=I?.strictJsonSchema)!=null?y:!0;let Z=I?.include;function Y(G){Z==null?Z=[G]:Z.includes(G)||(Z=[...Z,G])}function ye(G){return u?.find(te=>te.type==="provider"&&te.id===G)!=null}const X=typeof I?.logprobs=="number"?I?.logprobs:I?.logprobs===!0?I2:void 0;X&&Y("message.output_text.logprobs");const he=(w=u?.find(G=>G.type==="provider"&&(G.id==="openai.web_search"||G.id==="openai.web_search_preview")))==null?void 0:w.name;he&&Y("web_search_call.action.sources"),ye("openai.code_interpreter")&&Y("code_interpreter_call.outputs");const B=I?.store;B===!1&&L&&Y("reasoning.encrypted_content");const N={model:this.modelId,input:O,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||I?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:U,name:(_=p.name)!=null?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...I?.textVerbosity&&{verbosity:I.textVerbosity}}},conversation:I?.conversation,max_tool_calls:I?.maxToolCalls,metadata:I?.metadata,parallel_tool_calls:I?.parallelToolCalls,previous_response_id:I?.previousResponseId,store:B,user:I?.user,instructions:I?.instructions,service_tier:I?.serviceTier,include:Z,prompt_cache_key:I?.promptCacheKey,prompt_cache_retention:I?.promptCacheRetention,safety_identifier:I?.safetyIdentifier,top_logprobs:X,truncation:I?.truncation,...L&&(I?.reasoningEffort!=null||I?.reasoningSummary!=null)&&{reasoning:{...I?.reasoningEffort!=null&&{effort:I.reasoningEffort},...I?.reasoningSummary!=null&&{summary:I.reasoningSummary}}}};L?I?.reasoningEffort==="none"&&S.supportsNonReasoningParameters||(N.temperature!=null&&(N.temperature=void 0,b.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),N.top_p!=null&&(N.top_p=void 0,b.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(I?.reasoningEffort!=null&&b.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),I?.reasoningSummary!=null&&b.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),I?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(b.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete N.service_tier),I?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(b.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete N.service_tier);const{tools:H,toolChoice:F,toolWarnings:E}=await zI({tools:u,toolChoice:m}),M=(k=(T=(h=u?.find(G=>G.type==="provider"&&G.id==="openai.shell"))==null?void 0:h.args)==null?void 0:T.environment)==null?void 0:k.type,D=M==="containerAuto"||M==="containerReference";return{webSearchToolName:he,args:{...N,tools:H,tool_choice:F},warnings:[...b,...E],store:B,toolNameMapping:$,providerOptionsName:x,isShellProviderExecuted:D}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,m,p,f,g,v,y,w,_,h,T,k,b,S,x,I;const{args:L,warnings:$,webSearchToolName:O,toolNameMapping:A,providerOptionsName:U,isShellProviderExecuted:Z}=await this.getArgs(e),Y=this.config.url({path:"/responses",modelId:this.modelId}),ye=E2(e.prompt),{responseHeaders:X,value:he,rawValue:B}=await Ut({url:Y,headers:Nt(this.config.headers(),e.headers),body:L,failedResponseHandler:dr,successfulResponseHandler:Xt(UI),abortSignal:e.abortSignal,fetch:this.config.fetch});if(he.error)throw new st({message:he.error.message,url:Y,requestBodyValues:L,statusCode:400,responseHeaders:X,responseBody:B,isRetryable:!1});const N=[],H=[];let F=!1;for(const D of he.output)switch(D.type){case"reasoning":{D.summary.length===0&&D.summary.push({type:"summary_text",text:""});for(const G of D.summary)N.push({type:"reasoning",text:G.text,providerMetadata:{[U]:{itemId:D.id,reasoningEncryptedContent:(t=D.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{N.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),N.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("image_generation"),result:{result:D.result}});break}case"local_shell_call":{N.push({type:"tool-call",toolCallId:D.call_id,toolName:A.toCustomToolName("local_shell"),input:JSON.stringify({action:D.action}),providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call":{N.push({type:"tool-call",toolCallId:D.call_id,toolName:A.toCustomToolName("shell"),input:JSON.stringify({action:{commands:D.action.commands}}),...Z&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call_output":{N.push({type:"tool-result",toolCallId:D.call_id,toolName:A.toCustomToolName("shell"),result:{output:D.output.map(G=>({stdout:G.stdout,stderr:G.stderr,outcome:G.outcome.type==="exit"?{type:"exit",exitCode:G.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const G of D.content){(n=(r=e.providerOptions)==null?void 0:r[U])!=null&&n.logprobs&&G.logprobs&&H.push(G.logprobs);const te={itemId:D.id,...D.phase!=null&&{phase:D.phase},...G.annotations.length>0&&{annotations:G.annotations}};N.push({type:"text",text:G.text,providerMetadata:{[U]:te}});for(const se of G.annotations)se.type==="url_citation"?N.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:At(),url:se.url,title:se.title}):se.type==="file_citation"?N.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:At(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[U]:{type:se.type,fileId:se.file_id,index:se.index}}}):se.type==="container_file_citation"?N.push({type:"source",sourceType:"document",id:(p=(m=(u=this.config).generateId)==null?void 0:m.call(u))!=null?p:At(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[U]:{type:se.type,fileId:se.file_id,containerId:se.container_id}}}):se.type==="file_path"&&N.push({type:"source",sourceType:"document",id:(v=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?v:At(),mediaType:"application/octet-stream",title:se.file_id,filename:se.file_id,providerMetadata:{[U]:{type:se.type,fileId:se.file_id,index:se.index}}})}break}case"function_call":{F=!0,N.push({type:"tool-call",toolCallId:D.call_id,toolName:D.name,input:D.arguments,providerMetadata:{[U]:{itemId:D.id}}});break}case"web_search_call":{N.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName(O??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),N.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName(O??"web_search"),result:R2(D.action)});break}case"mcp_call":{const G=D.approval_request_id!=null&&(y=ye[D.approval_request_id])!=null?y:D.id,te=`mcp.${D.name}`;N.push({type:"tool-call",toolCallId:G,toolName:te,input:D.arguments,providerExecuted:!0,dynamic:!0}),N.push({type:"tool-result",toolCallId:G,toolName:te,result:{type:"call",serverLabel:D.server_label,name:D.name,arguments:D.arguments,...D.output!=null?{output:D.output}:{},...D.error!=null?{error:D.error}:{}},providerMetadata:{[U]:{itemId:D.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const G=(w=D.approval_request_id)!=null?w:D.id,te=(T=(h=(_=this.config).generateId)==null?void 0:h.call(_))!=null?T:At(),se=`mcp.${D.name}`;N.push({type:"tool-call",toolCallId:te,toolName:se,input:D.arguments,providerExecuted:!0,dynamic:!0}),N.push({type:"tool-approval-request",approvalId:G,toolCallId:te});break}case"computer_call":{N.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),N.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:D.status||"completed"}});break}case"file_search_call":{N.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),N.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("file_search"),result:{queries:D.queries,results:(b=(k=D.results)==null?void 0:k.map(G=>({attributes:G.attributes,fileId:G.file_id,filename:G.filename,score:G.score,text:G.text})))!=null?b:null}});break}case"code_interpreter_call":{N.push({type:"tool-call",toolCallId:D.id,toolName:A.toCustomToolName("code_interpreter"),input:JSON.stringify({code:D.code,containerId:D.container_id}),providerExecuted:!0}),N.push({type:"tool-result",toolCallId:D.id,toolName:A.toCustomToolName("code_interpreter"),result:{outputs:D.outputs}});break}case"apply_patch_call":{N.push({type:"tool-call",toolCallId:D.call_id,toolName:A.toCustomToolName("apply_patch"),input:JSON.stringify({callId:D.call_id,operation:D.operation}),providerMetadata:{[U]:{itemId:D.id}}});break}}const E={[U]:{responseId:he.id,...H.length>0?{logprobs:H}:{},...typeof he.service_tier=="string"?{serviceTier:he.service_tier}:{}}},M=he.usage;return{content:N,finishReason:{unified:S2({finishReason:(S=he.incomplete_details)==null?void 0:S.reason,hasFunctionCall:F}),raw:(I=(x=he.incomplete_details)==null?void 0:x.reason)!=null?I:void 0},usage:C2(M),request:{body:L},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:X,body:B},providerMetadata:E,warnings:$}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a,isShellProviderExecuted:i}=await this.getArgs(e),{responseHeaders:l,value:c}=await Ut({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:dr,successfulResponseHandler:Bs(DI),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,m=E2(e.prompt),p=new Map;let f={unified:"other",raw:void 0},g;const v=[];let y=null;const w={},_=[];let h,T=!1;const k={};let b;return{stream:c.pipeThrough(new TransformStream({start(S){S.enqueue({type:"stream-start",warnings:r})},transform(S,x){var I,L,$,O,A,U,Z,Y,ye,X,he,B,N,H,F,E,M,D,G,te,se,Te,z,V,W,Q,ie,_e,Ye,ct,pt,rt;if(e.includeRawChunks&&x.enqueue({type:"raw",rawValue:S.rawValue}),!S.success){f={unified:"error",raw:void 0},x.enqueue({type:"error",error:S.error});return}const P=S.value;if($2(P)){if(P.item.type==="function_call")w[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},x.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:P.item.name});else if(P.item.type==="web_search_call")w[P.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:P.item.id},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),x.enqueue({type:"tool-input-end",id:P.item.id}),x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(P.item.type==="computer_call")w[P.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:P.item.id},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(P.item.type==="code_interpreter_call")w[P.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:P.item.id,codeInterpreter:{containerId:P.item.container_id}},x.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),x.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`});else if(P.item.type==="file_search_call")x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(P.item.type==="image_generation_call")x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(P.item.type==="mcp_call"||P.item.type==="mcp_list_tools"||P.item.type==="mcp_approval_request"))if(P.item.type==="apply_patch_call"){const{call_id:re,operation:Re}=P.item;if(w[P.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:re,applyPatch:{hasDiff:Re.type==="delete_file",endEmitted:Re.type==="delete_file"}},x.enqueue({type:"tool-input-start",id:re,toolName:o.toCustomToolName("apply_patch")}),Re.type==="delete_file"){const Me=JSON.stringify({callId:re,operation:Re});x.enqueue({type:"tool-input-delta",id:re,delta:Me}),x.enqueue({type:"tool-input-end",id:re})}else x.enqueue({type:"tool-input-delta",id:re,delta:`{"callId":"${Nn(re)}","operation":{"type":"${Nn(Re.type)}","path":"${Nn(Re.path)}","diff":"`})}else P.item.type==="shell_call"?w[P.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:P.item.call_id}:P.item.type==="shell_call_output"||(P.item.type==="message"?(_.splice(0,_.length),h=(I=P.item.phase)!=null?I:void 0,x.enqueue({type:"text-start",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id,...P.item.phase!=null&&{phase:P.item.phase}}}})):$2(P)&&P.item.type==="reasoning"&&(k[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:{0:"active"}},x.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(L=P.item.encrypted_content)!=null?L:null}}})))}else if(HI(P)){if(P.item.type==="message"){const re=($=P.item.phase)!=null?$:h;h=void 0,x.enqueue({type:"text-end",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id,...re!=null&&{phase:re},..._.length>0&&{annotations:_}}}})}else if(P.item.type==="function_call")w[P.output_index]=void 0,T=!0,x.enqueue({type:"tool-input-end",id:P.item.call_id}),x.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:P.item.name,input:P.item.arguments,providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="web_search_call")w[P.output_index]=void 0,x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),result:R2(P.item.action)});else if(P.item.type==="computer_call")w[P.output_index]=void 0,x.enqueue({type:"tool-input-end",id:P.item.id}),x.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:P.item.status||"completed"}});else if(P.item.type==="file_search_call")w[P.output_index]=void 0,x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:P.item.queries,results:(A=(O=P.item.results)==null?void 0:O.map(re=>({attributes:re.attributes,fileId:re.file_id,filename:re.filename,score:re.score,text:re.text})))!=null?A:null}});else if(P.item.type==="code_interpreter_call")w[P.output_index]=void 0,x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:P.item.outputs}});else if(P.item.type==="image_generation_call")x.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:P.item.result}});else if(P.item.type==="mcp_call"){w[P.output_index]=void 0;const re=(U=P.item.approval_request_id)!=null?U:void 0,Re=re!=null&&(Y=(Z=p.get(re))!=null?Z:m[re])!=null?Y:P.item.id,Me=`mcp.${P.item.name}`;x.enqueue({type:"tool-call",toolCallId:Re,toolName:Me,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),x.enqueue({type:"tool-result",toolCallId:Re,toolName:Me,result:{type:"call",serverLabel:P.item.server_label,name:P.item.name,arguments:P.item.arguments,...P.item.output!=null?{output:P.item.output}:{},...P.item.error!=null?{error:P.item.error}:{}},providerMetadata:{[a]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_list_tools")w[P.output_index]=void 0;else if(P.item.type==="apply_patch_call"){const re=w[P.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&P.item.operation.type!=="delete_file"&&(re.applyPatch.hasDiff||x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Nn(P.item.operation.diff)}),x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),x.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0),re&&P.item.status==="completed"&&x.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:P.item.call_id,operation:P.item.operation}),providerMetadata:{[a]:{itemId:P.item.id}}}),w[P.output_index]=void 0}else if(P.item.type==="mcp_approval_request"){w[P.output_index]=void 0;const re=(he=(X=(ye=u.config).generateId)==null?void 0:X.call(ye))!=null?he:At(),Re=(B=P.item.approval_request_id)!=null?B:P.item.id;p.set(Re,re);const Me=`mcp.${P.item.name}`;x.enqueue({type:"tool-call",toolCallId:re,toolName:Me,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),x.enqueue({type:"tool-approval-request",approvalId:Re,toolCallId:re})}else if(P.item.type==="local_shell_call")w[P.output_index]=void 0,x.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:P.item.action.command,timeoutMs:P.item.action.timeout_ms,user:P.item.action.user,workingDirectory:P.item.action.working_directory,env:P.item.action.env}}),providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="shell_call")w[P.output_index]=void 0,x.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:P.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="shell_call_output")x.enqueue({type:"tool-result",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:P.item.output.map(re=>({stdout:re.stdout,stderr:re.stderr,outcome:re.outcome.type==="exit"?{type:"exit",exitCode:re.outcome.exit_code}:{type:"timeout"}}))}});else if(P.item.type==="reasoning"){const re=k[P.item.id],Re=Object.entries(re.summaryParts).filter(([Me,nr])=>nr==="active"||nr==="can-conclude").map(([Me])=>Me);for(const Me of Re)x.enqueue({type:"reasoning-end",id:`${P.item.id}:${Me}`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(N=P.item.encrypted_content)!=null?N:null}}});delete k[P.item.id]}}else if(WI(P)){const re=w[P.output_index];re!=null&&x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:P.delta})}else if(XI(P)){const re=w[P.output_index];re?.applyPatch&&(x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Nn(P.delta)}),re.applyPatch.hasDiff=!0)}else if(e8(P)){const re=w[P.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&(re.applyPatch.hasDiff||(x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Nn(P.diff)}),re.applyPatch.hasDiff=!0),x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),x.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0)}else if(KI(P))x.enqueue({type:"tool-result",toolCallId:P.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:P.partial_image_b64},preliminary:!0});else if(YI(P)){const re=w[P.output_index];re!=null&&x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:Nn(P.delta)})}else if(QI(P)){const re=w[P.output_index];re!=null&&(x.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}'}),x.enqueue({type:"tool-input-end",id:re.toolCallId}),x.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:P.code,containerId:re.codeInterpreter.containerId}),providerExecuted:!0}))}else if(GI(P))y=P.response.id,x.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(P.response.created_at*1e3),modelId:P.response.model});else if(BI(P))x.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(F=(H=e.providerOptions)==null?void 0:H[a])!=null&&F.logprobs&&P.logprobs&&v.push(P.logprobs);else if(P.type==="response.reasoning_summary_part.added"){if(P.summary_index>0){const re=k[P.item_id];re.summaryParts[P.summary_index]="active";for(const Re of Object.keys(re.summaryParts))re.summaryParts[Re]==="can-conclude"&&(x.enqueue({type:"reasoning-end",id:`${P.item_id}:${Re}`,providerMetadata:{[a]:{itemId:P.item_id}}}),re.summaryParts[Re]="concluded");x.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id,reasoningEncryptedContent:(M=(E=k[P.item_id])==null?void 0:E.encryptedContent)!=null?M:null}}})}}else P.type==="response.reasoning_summary_text.delta"?x.enqueue({type:"reasoning-delta",id:`${P.item_id}:${P.summary_index}`,delta:P.delta,providerMetadata:{[a]:{itemId:P.item_id}}}):P.type==="response.reasoning_summary_part.done"?s?(x.enqueue({type:"reasoning-end",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id}}}),k[P.item_id].summaryParts[P.summary_index]="concluded"):k[P.item_id].summaryParts[P.summary_index]="can-conclude":JI(P)?(f={unified:S2({finishReason:(D=P.response.incomplete_details)==null?void 0:D.reason,hasFunctionCall:T}),raw:(te=(G=P.response.incomplete_details)==null?void 0:G.reason)!=null?te:void 0},g=P.response.usage,typeof P.response.service_tier=="string"&&(b=P.response.service_tier)):t8(P)?(_.push(P.annotation),P.annotation.type==="url_citation"?x.enqueue({type:"source",sourceType:"url",id:(z=(Te=(se=u.config).generateId)==null?void 0:Te.call(se))!=null?z:At(),url:P.annotation.url,title:P.annotation.title}):P.annotation.type==="file_citation"?x.enqueue({type:"source",sourceType:"document",id:(Q=(W=(V=u.config).generateId)==null?void 0:W.call(V))!=null?Q:At(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}}):P.annotation.type==="container_file_citation"?x.enqueue({type:"source",sourceType:"document",id:(Ye=(_e=(ie=u.config).generateId)==null?void 0:_e.call(ie))!=null?Ye:At(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,containerId:P.annotation.container_id}}}):P.annotation.type==="file_path"&&x.enqueue({type:"source",sourceType:"document",id:(rt=(pt=(ct=u.config).generateId)==null?void 0:pt.call(ct))!=null?rt:At(),mediaType:"application/octet-stream",title:P.annotation.file_id,filename:P.annotation.file_id,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}})):r8(P)&&x.enqueue({type:"error",error:P})},flush(S){const x={[a]:{responseId:y,...v.length>0?{logprobs:v}:{},...b!==void 0?{serviceTier:b}:{}}};S.enqueue({type:"finish",finishReason:f,usage:C2(g),providerMetadata:x})}})),request:{body:t},response:{headers:l}}}};function BI(e){return e.type==="response.output_text.delta"}function HI(e){return e.type==="response.output_item.done"}function JI(e){return e.type==="response.completed"||e.type==="response.incomplete"}function GI(e){return e.type==="response.created"}function WI(e){return e.type==="response.function_call_arguments.delta"}function KI(e){return e.type==="response.image_generation_call.partial_image"}function YI(e){return e.type==="response.code_interpreter_call_code.delta"}function QI(e){return e.type==="response.code_interpreter_call_code.done"}function XI(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function e8(e){return e.type==="response.apply_patch_call_operation_diff.done"}function $2(e){return e.type==="response.output_item.added"}function t8(e){return e.type==="response.output_text.annotation.added"}function r8(e){return e.type==="error"}function R2(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function Nn(e){return JSON.stringify(e).slice(1,-1)}var n8=be(()=>we(C({instructions:d().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),o8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await Mr({provider:"openai",providerOptions:a,schema:n8}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const m in u){const p=u[m];p!==void 0&&(c[m]=p)}}return s&&i.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await Ut({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),body:s,failedResponseHandler:dr,successfulResponseHandler:B9(),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:c}}}},s8=be(()=>we(C({text:d(),language:d().nullish(),duration:j().nullish(),words:q(C({word:d(),start:j(),end:j()})).nullish(),segments:q(C({id:j(),seek:j(),start:j(),end:j(),text:d(),tokens:q(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),a8=be(()=>we(C({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:q(fe(["word","segment"])).default(["segment"]).optional()}))),P2={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"},i8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await Mr({provider:"openai",providerOptions:r,schema:a8}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Wn(e)]);s.append("model",this.modelId);const i=G3(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const m of u)s.append(`${c}[]`,String(m));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,a,i,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:m}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:g}=await Nf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Nt(this.config.headers(),e.headers),formData:u,failedResponseHandler:dr,successfulResponseHandler:Xt(s8),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in P2?P2[p.language]:void 0;return{text:p.text,segments:(i=(a=(o=p.segments)==null?void 0:o.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?a:(s=p.words)==null?void 0:s.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?i:[],language:v,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:m,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},l8="3.0.36";function N2(e={}){var t,r;const n=(t=Af(Qn({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>rn({Authorization:`Bearer ${J3({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${l8}`),a=v=>new ZS(v,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),i=v=>new GS(v,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=v=>new YS(v,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=v=>new tI(v,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=v=>new i8(v,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),m=v=>new o8(v,{provider:`${o}.speech`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),p=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return f(v)},f=v=>new ZI(v,{provider:`${o}.responses`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(v){return p(v)};return g.specificationVersion="v3",g.languageModel=p,g.chat=a,g.completion=i,g.responses=f,g.embedding=l,g.embeddingModel=l,g.textEmbedding=l,g.textEmbeddingModel=l,g.image=c,g.imageModel=c,g.transcription=u,g.transcriptionModel=u,g.speech=m,g.speechModel=m,g.tools=qI,g}N2();var M2="vercel.ai.error",c8=Symbol.for(M2),O2,u8=class X_ extends Error{constructor({name:t,message:r,cause:n}){super(r),this[O2]=!0,this.name=t,this.cause=n}static isInstance(t){return X_.hasMarker(t,M2)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};O2=c8;var kt=u8,A2="AI_APICallError",q2=`vercel.ai.error.${A2}`,d8=Symbol.for(q2),L2,qr=class extends kt{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:A2,message:e,cause:a}),this[L2]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return kt.hasMarker(e,q2)}};L2=d8;var j2="AI_EmptyResponseBodyError",D2=`vercel.ai.error.${j2}`,p8=Symbol.for(D2),U2,f8=class extends kt{constructor({message:e="Empty response body"}={}){super({name:j2,message:e}),this[U2]=!0}static isInstance(e){return kt.hasMarker(e,D2)}};U2=p8;function z2(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var F2="AI_InvalidArgumentError",V2=`vercel.ai.error.${F2}`,h8=Symbol.for(V2),Z2,B2=class extends kt{constructor({message:e,cause:t,argument:r}){super({name:F2,message:e,cause:t}),this[Z2]=!0,this.argument=r}static isInstance(e){return kt.hasMarker(e,V2)}};Z2=h8;var H2="AI_InvalidResponseDataError",J2=`vercel.ai.error.${H2}`,m8=Symbol.for(J2),G2,W2=class extends kt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:H2,message:t}),this[G2]=!0,this.data=e}static isInstance(e){return kt.hasMarker(e,J2)}};G2=m8;var K2="AI_JSONParseError",Y2=`vercel.ai.error.${K2}`,g8=Symbol.for(Y2),Q2,ka=class extends kt{constructor({text:e,cause:t}){super({name:K2,message:`JSON parsing failed: Text: ${e}.
80
+ Error message: ${z2(t)}`,cause:t}),this[Q2]=!0,this.text=e}static isInstance(e){return kt.hasMarker(e,Y2)}};Q2=g8;var X2="AI_LoadAPIKeyError",eg=`vercel.ai.error.${X2}`,y8=Symbol.for(eg),tg,Ca=class extends kt{constructor({message:e}){super({name:X2,message:e}),this[tg]=!0}static isInstance(e){return kt.hasMarker(e,eg)}};tg=y8;var rg="AI_NoSuchModelError",ng=`vercel.ai.error.${rg}`,_8=Symbol.for(ng),og,sg=class extends kt{constructor({errorName:e=rg,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[og]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return kt.hasMarker(e,ng)}};og=_8;var ag="AI_TypeValidationError",ig=`vercel.ai.error.${ag}`,v8=Symbol.for(ig),lg,w8=class Qu extends kt{constructor({value:t,cause:r}){super({name:ag,message:`Type validation failed: Value: ${JSON.stringify(t)}.
81
+ Error message: ${z2(r)}`,cause:r}),this[lg]=!0,this.value=t}static isInstance(t){return kt.hasMarker(t,ig)}static wrap({value:t,cause:r}){return Qu.isInstance(r)&&r.value===t?r:new Qu({value:t,cause:r})}};lg=v8;var ns=w8,cg="AI_UnsupportedFunctionalityError",ug=`vercel.ai.error.${cg}`,b8=Symbol.for(ug),dg,pg=class extends kt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:cg,message:t}),this[dg]=!0,this.functionality=e}static isInstance(e){return kt.hasMarker(e,ug)}};dg=b8;function fg(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Ta(e){return Object.fromEntries([...e.headers])}var k8=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new B2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Sa=k8();function Vc(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var C8=["fetch failed","failed to fetch"];function T8({error:e,url:t,requestBodyValues:r}){if(Vc(e))return e;if(e instanceof TypeError&&C8.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new qr({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function S8(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function I8(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function hg(e,...t){const r=new Headers(I8(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var x8="3.0.18";function E8({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Ca({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Ca({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Ca({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Ca({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var $8=/"__proto__"\s*:/,R8=/"constructor"\s*:/;function mg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||$8.test(e)===!1&&R8.test(e)===!1?t:P8(t)}function P8(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Zc(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return mg(e)}try{return mg(e)}finally{Error.stackTraceLimit=t}}var Bc=Symbol.for("vercel.ai.validator");function N8(e){return{[Bc]:!0,validate:e}}function M8(e){return typeof e=="object"&&e!==null&&Bc in e&&e[Bc]===!0&&"validate"in e}function O8(e){return M8(e)?e:typeof e=="function"?e():A8(e)}function A8(e){return N8(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new ns({value:t,cause:r.issues})}})}async function q8({value:e,schema:t}){const r=await os({value:e,schema:t});if(!r.success)throw ns.wrap({value:e,cause:r.error});return r.value}async function os({value:e,schema:t}){const r=O8(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:ns.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:ns.wrap({value:e,cause:n}),rawValue:e}}}async function L8({text:e,schema:t}){try{const r=Zc(e);return t==null?r:q8({value:r,schema:t})}catch(r){throw ka.isInstance(r)||ns.isInstance(r)?r:new ka({text:e,cause:r})}}async function gg({text:e,schema:t}){try{const r=Zc(e);return t==null?{success:!0,value:r,rawValue:r}:await os({value:r,schema:t})}catch(r){return{success:!1,error:ka.isInstance(r)?r:new ka({text:e,cause:r}),rawValue:void 0}}}function yg(e){try{return Zc(e),!0}catch{return!1}}function j8({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Jn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await gg({text:r,schema:t}))}}))}async function _g({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await os({value:t[e],schema:r});if(!n.success)throw new B2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var D8=()=>globalThis.fetch,vg=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>U8({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),U8=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=D8()})=>{try{const i=await a(e,{method:"POST",headers:hg(t,`ai-sdk/provider-utils/${x8}`,S8()),body:r.content,signal:s}),l=Ta(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Vc(u)||qr.isInstance(u)?u:new qr({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Vc(c)||qr.isInstance(c))?c:new qr({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw T8({error:i,url:e,requestBodyValues:r.values})}},z8=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Ta(n);if(a.trim()==="")return{responseHeaders:i,value:new qr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await L8({text:a,schema:e});return{responseHeaders:i,value:new qr({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new qr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},F8=e=>async({response:t})=>{const r=Ta(t);if(t.body==null)throw new f8({});return{responseHeaders:r,value:j8({stream:t.body,schema:e})}},V8=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await gg({text:o,schema:e}),a=Ta(t);if(!s.success)throw new qr({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:Z8}=globalThis;function B8(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return Z8(t)}function H8(e){return e instanceof Uint8Array?B8(e):e}function J8(e){return e?.replace(/\/$/,"")}function ss(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function G8(e){const t=[];for(const{role:r,content:n,...o}of e){const s=ss({...o});switch(r){case"system":{t.push({role:"system",content:n,...s});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...ss(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=ss(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,${H8(a.data)}`},...i}}else throw new pg({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=ss(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)},...c});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of n){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 c=ss(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return t}function wg({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function bg(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 Hc=C({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),W8=C({error:C({message:d(),type:d().nullish(),param:wt().nullish(),code:oe([d(),j()]).nullish()})}),K8={errorSchema:W8,errorToMessage:e=>e.error.message};function Y8({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new pg({functionality:`tool choice type: ${s}`})}}}var Q8=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:K8;this.chunkSchema=ex(o.errorSchema),this.failedResponseHandler=z8(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:m,tools:p}){var f,g,v,y;const w=[],_=Object.assign((f=await _g({provider:"openai-compatible",providerOptions:i,schema:Hc}))!=null?f:{},(g=await _g({provider:this.providerOptionsName,providerOptions:i,schema:Hc}))!=null?g:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:h,toolChoice:T,toolWarnings:k}=Y8({tools:p,toolChoice:m});return{args:{model:this.modelId,user:_.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([b])=>!Object.keys(Hc.shape).includes(b))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:G8(e),tools:h,tool_choice:T},warnings:[...w,...k]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,m,p,f,g,v,y,w;const{args:_,warnings:h}=await this.getArgs({...e}),T=JSON.stringify(_),{responseHeaders:k,value:b,rawValue:S}=await vg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:fg(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:V8(X8),abortSignal:e.abortSignal,fetch:this.config.fetch}),x=b.choices[0],I=[],L=x.message.content;L!=null&&L.length>0&&I.push({type:"text",text:L});const $=(t=x.message.reasoning_content)!=null?t:x.message.reasoning;if($!=null&&$.length>0&&I.push({type:"reasoning",text:$}),x.message.tool_calls!=null)for(const U of x.message.tool_calls)I.push({type:"tool-call",toolCallId:(r=U.id)!=null?r:Sa(),toolName:U.function.name,input:U.function.arguments});const O={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},A=(s=b.usage)==null?void 0:s.completion_tokens_details;return A?.accepted_prediction_tokens!=null&&(O[this.providerOptionsName].acceptedPredictionTokens=A?.accepted_prediction_tokens),A?.rejected_prediction_tokens!=null&&(O[this.providerOptionsName].rejectedPredictionTokens=A?.rejected_prediction_tokens),{content:I,finishReason:bg(x.finish_reason),usage:{inputTokens:(i=(a=b.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=b.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(m=(u=b.usage)==null?void 0:u.total_tokens)!=null?m:void 0,reasoningTokens:(g=(f=(p=b.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(y=(v=b.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:O,request:{body:T},response:{...wg(b),headers:k,body:S},warnings:h}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,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 vg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:fg(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:F8(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let m=!0;const p=this.providerOptionsName;let f=!1,g=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,y){var w,_,h,T,k,b,S,x,I,L,$,O,A;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",y.enqueue({type:"error",error:v.error});return}const U=v.value;if(s?.processChunk(v.rawValue),"error"in U){c="error",y.enqueue({type:"error",error:U.error.message});return}if(m&&(m=!1,y.enqueue({type:"response-metadata",...wg(U)})),U.usage!=null){const{prompt_tokens:X,completion_tokens:he,total_tokens:B,prompt_tokens_details:N,completion_tokens_details:H}=U.usage;u.promptTokens=X??void 0,u.completionTokens=he??void 0,u.totalTokens=B??void 0,H?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=H?.reasoning_tokens),H?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=H?.accepted_prediction_tokens),H?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=H?.rejected_prediction_tokens),N?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=N?.cached_tokens)}const Z=U.choices[0];if(Z?.finish_reason!=null&&(c=bg(Z.finish_reason)),Z?.delta==null)return;const Y=Z.delta,ye=(w=Y.reasoning_content)!=null?w:Y.reasoning;if(ye&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ye})),Y.content&&(g||(y.enqueue({type:"text-start",id:"txt-0"}),g=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:Y.content})),Y.tool_calls!=null)for(const X of Y.tool_calls){const he=X.index;if(l[he]==null){if(X.id==null)throw new W2({data:X,message:"Expected 'id' to be a string."});if(((_=X.function)==null?void 0:_.name)==null)throw new W2({data:X,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),l[he]={id:X.id,type:"function",function:{name:X.function.name,arguments:(h=X.function.arguments)!=null?h:""},hasFinished:!1};const N=l[he];((T=N.function)==null?void 0:T.name)!=null&&((k=N.function)==null?void 0:k.arguments)!=null&&(N.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:N.id,delta:N.function.arguments}),yg(N.function.arguments)&&(y.enqueue({type:"tool-input-end",id:N.id}),y.enqueue({type:"tool-call",toolCallId:(b=N.id)!=null?b:Sa(),toolName:N.function.name,input:N.function.arguments}),N.hasFinished=!0));continue}const B=l[he];B.hasFinished||(((S=X.function)==null?void 0:S.arguments)!=null&&(B.function.arguments+=(I=(x=X.function)==null?void 0:x.arguments)!=null?I:""),y.enqueue({type:"tool-input-delta",id:B.id,delta:(L=X.function.arguments)!=null?L:""}),(($=B.function)==null?void 0:$.name)!=null&&((O=B.function)==null?void 0:O.arguments)!=null&&yg(B.function.arguments)&&(y.enqueue({type:"tool-input-end",id:B.id}),y.enqueue({type:"tool-call",toolCallId:(A=B.id)!=null?A:Sa(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}},flush(v){var y,w,_,h,T,k;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(x=>!x.hasFinished))v.enqueue({type:"tool-input-end",id:S.id}),v.enqueue({type:"tool-call",toolCallId:(y=S.id)!=null?y:Sa(),toolName:S.function.name,input:S.function.arguments});const b={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(b[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(b[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(h=u.totalTokens)!=null?h:void 0,reasoningTokens:(T=u.completionTokensDetails.reasoningTokens)!=null?T:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:b})}})),request:{body:o},response:{headers:a}}}},kg=C({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:C({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),X8=C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({message:C({role:R("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({id:d().nullish(),function:C({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:kg}),ex=e=>oe([C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({delta:C({role:fe(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({index:j(),id:d().nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:kg}),e]);C({echo:pe().optional(),logitBias:ge(d(),j()).optional(),suffix:d().optional(),user:d().optional()});var tx=C({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});C({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d()})),usage:tx.nullish()}),C({dimensions:j().optional(),user:d().optional()}),C({data:q(C({embedding:q(j())})),usage:C({prompt_tokens:j()}).nullish(),providerMetadata:ge(d(),ge(d(),wt())).optional()}),C({data:q(C({b64_json:d()}))});var Cg=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},rx={extractMetadata:async({parsedBody:e})=>{const t=await os({value:e,schema:nx});return!t.success||t.value.usage==null?void 0:Cg(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await os({value:t,schema:ox});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>Cg(e)}}},Tg=C({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),nx=C({usage:Tg.nullish()}),ox=C({choices:q(C({finish_reason:d().nullish()})).nullish(),usage:Tg.nullish()}),sx="1.0.30";function Sg(e={}){var t;const r=J8((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>hg({Authorization:`Bearer ${E8({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${sx}`);class o extends Q8{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:rx}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new sg({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new sg({modelId:i,modelType:"imageModel"})},a}Sg();const ax=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},ix=(e,t,r,n)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===r){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class lx{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=ix("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=$n.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const n=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!n,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const o=n.tabIds[n.tabIds.length-1];ax("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:o,mcpMessage:t},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}function Ia(e){return!!e._zod}function sn(e,t){return Ia(e)?Kd(e,t):e.safeParse(t)}function Ig(e){if(!e)return;let t;if(Ia(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function cx(e){if(Ia(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}function Mn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function xg(e){const r=Ig(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=cx(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Eg(e,t){const r=sn(e,t);if(!r.success)throw r.error;return r.data}const ux=6e4;class dx{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ec,r=>{this._oncancel(r)}),this.setNotificationHandler(rc,r=>{this._onprogress(r)}),this.setRequestHandler(tc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(nc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke(Ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(sc,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(i.type==="response"||i.type==="error"){const l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{const m=l,p=new ke(m.error.code,m.error.message,m.error.data);u(p)}else{const m=i.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new ke(Ee.InvalidParams,`Task not found: ${s}`);if(!Mn(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Mn(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[En]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ac,async(r,n)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new ke(Ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(lc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke(Ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(Mn(o.status))throw new ke(Ee.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ke(Ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ke?o:new ke(Ee.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),ke.fromError(Ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),Wo(s)||DC(s)?this._onresponse(s):Yl(s)?this._onrequest(s,a):jC(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=ke.fromError(Ee.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[En]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:Ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):o?.send(u).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=LC(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const m={relatedRequestId:t.id};s&&(m.relatedTask={taskId:s}),await this.notification(u,m)},sendRequest:async(u,m,p)=>{const f={...p,relatedRequestId:t.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});const g=f.relatedTask?.taskId??s;return g&&l&&await l.updateTaskStatus(g,"input_required"),await this.request(u,m,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const m={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)},async u=>{if(a.signal.aborted)return;const m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:Ee.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Wo(t))n(t);else{const a=new ke(t.error.code,t.error.message,t.error.data);n(a)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Wo(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,r))}}if(s||this._progressHandlers.delete(r),Wo(t))o(t);else{const a=ke.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof ke?a:new ke(Ee.InternalError,String(a))}}return}let s;try{const a=await this.request(t,es,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ke(Ee.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},Mn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new ke(Ee.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new ke(Ee.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof ke?a:new ke(Ee.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const m=_=>{u(_)};if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(_){m(_);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(f.params={...f.params,task:i}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[En]:l}});const g=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const h=_ instanceof ke?_:new ke(Ee.RequestTimeout,String(_));u(h)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{const h=sn(r,_.result);h.success?c(h.data):u(h.error)}catch(h){u(h)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});const v=n?.timeout??ux,y=()=>g(ke.fromError(Ee.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(p,v,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const _=h=>{const T=this._responseHandlers.get(p);T?T(h):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(h=>{this._cleanupTimeout(p),u(h)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(_=>{this._cleanupTimeout(p),u(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},oc,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},ic,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},rT,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const i={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[En]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[En]:r.relatedTask}}}),this._transport?.send(i,r).catch(l=>this._onerror(l))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[En]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=xg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=Eg(t,o);return Promise.resolve(r(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const n=xg(t);this._notificationHandlers.set(n,o=>{const s=Eg(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&Yl(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new ke(Ee.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new ke(Ee.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ke(Ee.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new ke(Ee.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=fa.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Mn(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,a)=>{const i=await n.getTask(o,r);if(!i)throw new ke(Ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Mn(i.status))throw new ke(Ee.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=fa.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Mn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function $g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function px(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const a=r[o];$g(a)&&$g(s)?r[o]={...a,...s}:r[o]=s}return r}var xa={exports:{}},Jc={},Lr={},On={},Gc={},Wc={},Kc={},Rg;function Ea(){return Rg||(Rg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((h,T)=>`${h}${T}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((h,T)=>(T instanceof r&&(h[T.str]=(h[T.str]||0)+1),h),{})}}e._Code=n,e.nil=new n("");function o(w,..._){const h=[w[0]];let T=0;for(;T<_.length;)i(h,_[T]),h.push(w[++T]);return new n(h)}e._=o;const s=new n("+");function a(w,..._){const h=[f(w[0])];let T=0;for(;T<_.length;)h.push(s),i(h,_[T]),h.push(s,f(w[++T]));return l(h),new n(h)}e.str=a;function i(w,_){_ instanceof n?w.push(..._._items):_ instanceof r?w.push(_):w.push(m(_))}e.addCodeArg=i;function l(w){let _=1;for(;_<w.length-1;){if(w[_]===s){const h=c(w[_-1],w[_+1]);if(h!==void 0){w.splice(_-1,3,h);continue}w[_++]="+"}_++}}function c(w,_){if(_==='""')return w;if(w==='""')return _;if(typeof w=="string")return _ instanceof r||w[w.length-1]!=='"'?void 0:typeof _!="string"?`${w.slice(0,-1)}${_}"`:_[0]==='"'?w.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(w instanceof r))return`"${w}${_.slice(1)}`}function u(w,_){return _.emptyStr()?w:w.emptyStr()?_:a`${w}${_}`}e.strConcat=u;function m(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:f(Array.isArray(w)?w.join(","):w)}function p(w){return new n(f(w))}e.stringify=p;function f(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function g(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=g;function v(w){if(typeof w=="string"&&e.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}e.getEsmExportName=v;function y(w){return new n(w.toString())}e.regexpCode=y})(Kc)),Kc}var Yc={},Pg;function Ng(){return Pg||(Pg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Ea();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,m;if(!((m=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||m===void 0)&&m.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:m}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${m}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var m;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:f}=p,g=(m=u.key)!==null&&m!==void 0?m:u.ref;let v=this._values[f];if(v){const _=v.get(g);if(_)return _}else v=this._values[f]=new Map;v.set(g,p);const y=this._scope[f]||(this._scope[f]=[]),w=y.length;return y[w]=u.ref,p.setValue(u,{property:f,itemIndex:w}),p}getValue(c,u){const m=this._values[c];if(m)return m.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,m=>{if(m.scopePath===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return(0,t._)`${c}${m.scopePath}`})}scopeCode(c=this._values,u,m){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,m)}_reduceValues(c,u,m={},p){let f=t.nil;for(const g in c){const v=c[g];if(!v)continue;const y=m[g]=m[g]||new Map;v.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let _=u(w);if(_){const h=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${h} ${w} = ${_};${this.opts._n}`}else if(_=p?.(w))f=(0,t._)`${f}${_}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return f}}e.ValueScope=i})(Yc)),Yc}var Mg;function Pe(){return Mg||(Mg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=Ea(),r=Ng();var n=Ea();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=Ng();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(E,M){return this}}class a extends s{constructor(E,M,D){super(),this.varKind=E,this.name=M,this.rhs=D}render({es5:E,_n:M}){const D=E?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${D} ${this.name}${G};`+M}optimizeNames(E,M){if(E[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,E,M)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(E,M,D){super(),this.lhs=E,this.rhs=M,this.sideEffects=D}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,M){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,E,M),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(E,this.rhs)}}class l extends i{constructor(E,M,D,G){super(E,D,G),this.op=M}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class m extends s{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class p extends s{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,M){return this.code=U(this.code,E,M),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((M,D)=>M+D.render(E),"")}optimizeNodes(){const{nodes:E}=this;let M=E.length;for(;M--;){const D=E[M].optimizeNodes();Array.isArray(D)?E.splice(M,1,...D):D?E[M]=D:E.splice(M,1)}return E.length>0?this:void 0}optimizeNames(E,M){const{nodes:D}=this;let G=D.length;for(;G--;){const te=D[G];te.optimizeNames(E,M)||(Z(E,te.names),D.splice(G,1))}return D.length>0?this:void 0}get names(){return this.nodes.reduce((E,M)=>O(E,M.names),{})}}class g extends f{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class v extends f{}class y extends g{}y.kind="else";class w extends g{constructor(E,M){super(M),this.condition=E}render(E){let M=`if(${this.condition})`+super.render(E);return this.else&&(M+="else "+this.else.render(E)),M}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let M=this.else;if(M){const D=M.optimizeNodes();M=this.else=Array.isArray(D)?new y(D):D}if(M)return E===!1?M instanceof w?M:M.nodes:this.nodes.length?this:new w(Y(E),M instanceof w?[M]:M.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,M){var D;if(this.else=(D=this.else)===null||D===void 0?void 0:D.optimizeNames(E,M),!!(super.optimizeNames(E,M)||this.else))return this.condition=U(this.condition,E,M),this}get names(){const E=super.names;return A(E,this.condition),this.else&&O(E,this.else.names),E}}w.kind="if";class _ extends g{}_.kind="for";class h extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,M){if(super.optimizeNames(E,M))return this.iteration=U(this.iteration,E,M),this}get names(){return O(super.names,this.iteration.names)}}class T extends _{constructor(E,M,D,G){super(),this.varKind=E,this.name=M,this.from=D,this.to=G}render(E){const M=E.es5?r.varKinds.var:this.varKind,{name:D,from:G,to:te}=this;return`for(${M} ${D}=${G}; ${D}<${te}; ${D}++)`+super.render(E)}get names(){const E=A(super.names,this.from);return A(E,this.to)}}class k extends _{constructor(E,M,D,G){super(),this.loop=E,this.varKind=M,this.name=D,this.iterable=G}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,M){if(super.optimizeNames(E,M))return this.iterable=U(this.iterable,E,M),this}get names(){return O(super.names,this.iterable.names)}}class b extends g{constructor(E,M,D){super(),this.name=E,this.args=M,this.async=D}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}b.kind="func";class S extends f{render(E){return"return "+super.render(E)}}S.kind="return";class x extends g{render(E){let M="try"+super.render(E);return this.catch&&(M+=this.catch.render(E)),this.finally&&(M+=this.finally.render(E)),M}optimizeNodes(){var E,M;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(M=this.finally)===null||M===void 0||M.optimizeNodes(),this}optimizeNames(E,M){var D,G;return super.optimizeNames(E,M),(D=this.catch)===null||D===void 0||D.optimizeNames(E,M),(G=this.finally)===null||G===void 0||G.optimizeNames(E,M),this}get names(){const E=super.names;return this.catch&&O(E,this.catch.names),this.finally&&O(E,this.finally.names),E}}class I extends g{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}I.kind="catch";class L extends g{render(E){return"finally"+super.render(E)}}L.kind="finally";class ${constructor(E,M={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...M,_n:M.lines?`
82
+ `:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,M){const D=this._extScope.value(E,M);return(this._values[D.prefix]||(this._values[D.prefix]=new Set)).add(D),D}getScopeValue(E,M){return this._extScope.getValue(E,M)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,M,D,G){const te=this._scope.toName(M);return D!==void 0&&G&&(this._constants[te.str]=D),this._leafNode(new a(E,te,D)),te}const(E,M,D){return this._def(r.varKinds.const,E,M,D)}let(E,M,D){return this._def(r.varKinds.let,E,M,D)}var(E,M,D){return this._def(r.varKinds.var,E,M,D)}assign(E,M,D){return this._leafNode(new i(E,M,D))}add(E,M){return this._leafNode(new l(E,e.operators.ADD,M))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new p(E)),this}object(...E){const M=["{"];for(const[D,G]of E)M.length>1&&M.push(","),M.push(D),(D!==G||this.opts.es5)&&(M.push(":"),(0,t.addCodeArg)(M,G));return M.push("}"),new t._Code(M)}if(E,M,D){if(this._blockNode(new w(E)),M&&D)this.code(M).else().code(D).endIf();else if(M)this.code(M).endIf();else if(D)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(E,M){return this._blockNode(E),M&&this.code(M).endFor(),this}for(E,M){return this._for(new h(E),M)}forRange(E,M,D,G,te=this.opts.es5?r.varKinds.var:r.varKinds.let){const se=this._scope.toName(E);return this._for(new T(te,se,M,D),()=>G(se))}forOf(E,M,D,G=r.varKinds.const){const te=this._scope.toName(E);if(this.opts.es5){const se=M instanceof t.Name?M:this.var("_arr",M);return this.forRange("_i",0,(0,t._)`${se}.length`,Te=>{this.var(te,(0,t._)`${se}[${Te}]`),D(te)})}return this._for(new k("of",G,te,M),()=>D(te))}forIn(E,M,D,G=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${M})`,D);const te=this._scope.toName(E);return this._for(new k("in",G,te,M),()=>D(te))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const M=new S;if(this._blockNode(M),this.code(E),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(E,M,D){if(!M&&!D)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new x;if(this._blockNode(G),this.code(E),M){const te=this.name("e");this._currNode=G.catch=new I(te),M(te)}return D&&(this._currNode=G.finally=new L,this.code(D)),this._endBlockNode(I,L)}throw(E){return this._leafNode(new m(E))}block(E,M){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(M),this}endBlock(E){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const D=this._nodes.length-M;if(D<0||E!==void 0&&D!==E)throw new Error(`CodeGen: wrong number of nodes: ${D} vs ${E} expected`);return this._nodes.length=M,this}func(E,M=t.nil,D,G){return this._blockNode(new b(E,M,D)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(b)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,M){const D=this._currNode;if(D instanceof E||M&&D instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${E.kind}/${M.kind}`:E.kind}"`)}_elseNode(E){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const M=this._nodes;M[M.length-1]=E}}e.CodeGen=$;function O(F,E){for(const M in E)F[M]=(F[M]||0)+(E[M]||0);return F}function A(F,E){return E instanceof t._CodeOrName?O(F,E.names):F}function U(F,E,M){if(F instanceof t.Name)return D(F);if(!G(F))return F;return new t._Code(F._items.reduce((te,se)=>(se instanceof t.Name&&(se=D(se)),se instanceof t._Code?te.push(...se._items):te.push(se),te),[]));function D(te){const se=M[te.str];return se===void 0||E[te.str]!==1?te:(delete E[te.str],se)}function G(te){return te instanceof t._Code&&te._items.some(se=>se instanceof t.Name&&E[se.str]===1&&M[se.str]!==void 0)}}function Z(F,E){for(const M in E)F[M]=(F[M]||0)-(E[M]||0)}function Y(F){return typeof F=="boolean"||typeof F=="number"||F===null?!F:(0,t._)`!${H(F)}`}e.not=Y;const ye=N(e.operators.AND);function X(...F){return F.reduce(ye)}e.and=X;const he=N(e.operators.OR);function B(...F){return F.reduce(he)}e.or=B;function N(F){return(E,M)=>E===t.nil?M:M===t.nil?E:(0,t._)`${H(E)} ${F} ${H(M)}`}function H(F){return F instanceof t.Name?F:(0,t._)`(${F})`}})(Wc)),Wc}var Ne={},Og;function je(){if(Og)return Ne;Og=1,Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.checkStrictMode=Ne.getErrorPath=Ne.Type=Ne.useFunc=Ne.setEvaluated=Ne.evaluatedPropsToName=Ne.mergeEvaluated=Ne.eachItem=Ne.unescapeJsonPointer=Ne.escapeJsonPointer=Ne.escapeFragment=Ne.unescapeFragment=Ne.schemaRefOrVal=Ne.schemaHasRulesButRef=Ne.schemaHasRules=Ne.checkUnknownRules=Ne.alwaysValidSchema=Ne.toHash=void 0;const e=Pe(),t=Ea();function r(k){const b={};for(const S of k)b[S]=!0;return b}Ne.toHash=r;function n(k,b){return typeof b=="boolean"?b:Object.keys(b).length===0?!0:(o(k,b),!s(b,k.self.RULES.all))}Ne.alwaysValidSchema=n;function o(k,b=k.schema){const{opts:S,self:x}=k;if(!S.strictSchema||typeof b=="boolean")return;const I=x.RULES.keywords;for(const L in b)I[L]||T(k,`unknown keyword: "${L}"`)}Ne.checkUnknownRules=o;function s(k,b){if(typeof k=="boolean")return!k;for(const S in k)if(b[S])return!0;return!1}Ne.schemaHasRules=s;function a(k,b){if(typeof k=="boolean")return!k;for(const S in k)if(S!=="$ref"&&b.all[S])return!0;return!1}Ne.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:b},S,x,I){if(!I){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${k}${b}${(0,e.getProperty)(x)}`}Ne.schemaRefOrVal=i;function l(k){return m(decodeURIComponent(k))}Ne.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}Ne.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}Ne.escapeJsonPointer=u;function m(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}Ne.unescapeJsonPointer=m;function p(k,b){if(Array.isArray(k))for(const S of k)b(S);else b(k)}Ne.eachItem=p;function f({mergeNames:k,mergeToName:b,mergeValues:S,resultToName:x}){return(I,L,$,O)=>{const A=$===void 0?L:$ instanceof e.Name?(L instanceof e.Name?k(I,L,$):b(I,L,$),$):L instanceof e.Name?(b(I,$,L),L):S(L,$);return O===e.Name&&!(A instanceof e.Name)?x(I,A):A}}Ne.mergeEvaluated={props:f({mergeNames:(k,b,S)=>k.if((0,e._)`${S} !== true && ${b} !== undefined`,()=>{k.if((0,e._)`${b} === true`,()=>k.assign(S,!0),()=>k.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${b})`))}),mergeToName:(k,b,S)=>k.if((0,e._)`${S} !== true`,()=>{b===!0?k.assign(S,!0):(k.assign(S,(0,e._)`${S} || {}`),v(k,S,b))}),mergeValues:(k,b)=>k===!0?!0:{...k,...b},resultToName:g}),items:f({mergeNames:(k,b,S)=>k.if((0,e._)`${S} !== true && ${b} !== undefined`,()=>k.assign(S,(0,e._)`${b} === true ? true : ${S} > ${b} ? ${S} : ${b}`)),mergeToName:(k,b,S)=>k.if((0,e._)`${S} !== true`,()=>k.assign(S,b===!0?!0:(0,e._)`${S} > ${b} ? ${S} : ${b}`)),mergeValues:(k,b)=>k===!0?!0:Math.max(k,b),resultToName:(k,b)=>k.var("items",b)})};function g(k,b){if(b===!0)return k.var("props",!0);const S=k.var("props",(0,e._)`{}`);return b!==void 0&&v(k,S,b),S}Ne.evaluatedPropsToName=g;function v(k,b,S){Object.keys(S).forEach(x=>k.assign((0,e._)`${b}${(0,e.getProperty)(x)}`,!0))}Ne.setEvaluated=v;const y={};function w(k,b){return k.scopeValue("func",{ref:b,code:y[b.code]||(y[b.code]=new t._Code(b.code))})}Ne.useFunc=w;var _;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(_||(Ne.Type=_={}));function h(k,b,S){if(k instanceof e.Name){const x=b===_.Num;return S?x?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:x?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(k).toString():"/"+u(k)}Ne.getErrorPath=h;function T(k,b,S=k.opts.strictSchema){if(S){if(b=`strict mode: ${b}`,S===!0)throw new Error(b);k.self.logger.warn(b)}}return Ne.checkStrictMode=T,Ne}var $a={},Ag;function an(){if(Ag)return $a;Ag=1,Object.defineProperty($a,"__esModule",{value:!0});const e=Pe(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return $a.default=t,$a}var qg;function Ra(){return qg||(qg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Pe(),r=je(),n=an();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,t.str)`"${y}" keyword must be ${w} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,w=e.keywordError,_,h){const{it:T}=y,{gen:k,compositeRule:b,allErrors:S}=T,x=m(y,w,_);h??(b||S)?l(k,x):c(T,(0,t._)`[${x}]`)}e.reportError=o;function s(y,w=e.keywordError,_){const{it:h}=y,{gen:T,compositeRule:k,allErrors:b}=h,S=m(y,w,_);l(T,S),k||b||c(h,n.default.vErrors)}e.reportExtraError=s;function a(y,w){y.assign(n.default.errors,w),y.if((0,t._)`${n.default.vErrors} !== null`,()=>y.if(w,()=>y.assign((0,t._)`${n.default.vErrors}.length`,w),()=>y.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:y,keyword:w,schemaValue:_,data:h,errsCount:T,it:k}){if(T===void 0)throw new Error("ajv implementation error");const b=y.name("err");y.forRange("i",T,n.default.errors,S=>{y.const(b,(0,t._)`${n.default.vErrors}[${S}]`),y.if((0,t._)`${b}.instancePath === undefined`,()=>y.assign((0,t._)`${b}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),y.assign((0,t._)`${b}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${w}`),k.opts.verbose&&(y.assign((0,t._)`${b}.schema`,_),y.assign((0,t._)`${b}.data`,h))})}e.extendErrors=i;function l(y,w){const _=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:_,validateName:h,schemaEnv:T}=y;T.$async?_.throw((0,t._)`new ${y.ValidationError}(${w})`):(_.assign((0,t._)`${h}.errors`,w),_.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function m(y,w,_){const{createErrors:h}=y.it;return h===!1?(0,t._)`{}`:p(y,w,_)}function p(y,w,_={}){const{gen:h,it:T}=y,k=[f(T,_),g(y,_)];return v(y,w,k),h.object(...k)}function f({errorPath:y},{instancePath:w}){const _=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function g({keyword:y,it:{errSchemaPath:w}},{schemaPath:_,parentSchema:h}){let T=h?w:(0,t.str)`${w}/${y}`;return _&&(T=(0,t.str)`${T}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,T]}function v(y,{params:w,message:_},h){const{keyword:T,data:k,schemaValue:b,it:S}=y,{opts:x,propertyName:I,topSchemaRef:L,schemaPath:$}=S;h.push([u.keyword,T],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),x.messages&&h.push([u.message,typeof _=="function"?_(y):_]),x.verbose&&h.push([u.schema,b],[u.parentSchema,(0,t._)`${L}${$}`],[n.default.data,k]),I&&h.push([u.propertyName,I])}})(Gc)),Gc}var Lg;function fx(){if(Lg)return On;Lg=1,Object.defineProperty(On,"__esModule",{value:!0}),On.boolOrEmptySchema=On.topBoolOrEmptySchema=void 0;const e=Ra(),t=Pe(),r=an(),n={message:"boolean schema is false"};function o(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}On.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}On.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,m={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(m,n,void 0,l)}return On}var Rt={},An={},jg;function Dg(){if(jg)return An;jg=1,Object.defineProperty(An,"__esModule",{value:!0}),An.getRules=An.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}An.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return An.getRules=n,An}var jr={},Ug;function zg(){if(Ug)return jr;Ug=1,Object.defineProperty(jr,"__esModule",{value:!0}),jr.shouldUseRule=jr.shouldUseGroup=jr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}jr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}jr.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(a=>n[a]!==void 0))}return jr.shouldUseRule=r,jr}var Fg;function Pa(){if(Fg)return Rt;Fg=1,Object.defineProperty(Rt,"__esModule",{value:!0}),Rt.reportTypeError=Rt.checkDataTypes=Rt.checkDataType=Rt.coerceAndCheckDataType=Rt.getJSONTypes=Rt.getSchemaTypes=Rt.DataType=void 0;const e=Dg(),t=zg(),r=Ra(),n=Pe(),o=je();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||(Rt.DataType=s={}));function a(_){const h=i(_.type);if(h.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!h.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&h.push("null")}return h}Rt.getSchemaTypes=a;function i(_){const h=Array.isArray(_)?_:_?[_]:[];if(h.every(e.isJSONType))return h;throw new Error("type must be JSONType or JSONType[]: "+h.join(","))}Rt.getJSONTypes=i;function l(_,h){const{gen:T,data:k,opts:b}=_,S=u(h,b.coerceTypes),x=h.length>0&&!(S.length===0&&h.length===1&&(0,t.schemaHasRulesForType)(_,h[0]));if(x){const I=g(h,k,b.strictNumbers,s.Wrong);T.if(I,()=>{S.length?m(_,h,S):y(_)})}return x}Rt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,h){return h?_.filter(T=>c.has(T)||h==="array"&&T==="array"):[]}function m(_,h,T){const{gen:k,data:b,opts:S}=_,x=k.let("dataType",(0,n._)`typeof ${b}`),I=k.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&k.if((0,n._)`${x} == 'object' && Array.isArray(${b}) && ${b}.length == 1`,()=>k.assign(b,(0,n._)`${b}[0]`).assign(x,(0,n._)`typeof ${b}`).if(g(h,b,S.strictNumbers),()=>k.assign(I,b))),k.if((0,n._)`${I} !== undefined`);for(const $ of T)(c.has($)||$==="array"&&S.coerceTypes==="array")&&L($);k.else(),y(_),k.endIf(),k.if((0,n._)`${I} !== undefined`,()=>{k.assign(b,I),p(_,I)});function L($){switch($){case"string":k.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(I,(0,n._)`"" + ${b}`).elseIf((0,n._)`${b} === null`).assign(I,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${x} == "boolean" || ${b} === null
83
+ || (${x} == "string" && ${b} && ${b} == +${b})`).assign(I,(0,n._)`+${b}`);return;case"integer":k.elseIf((0,n._)`${x} === "boolean" || ${b} === null
84
+ || (${x} === "string" && ${b} && ${b} == +${b} && !(${b} % 1))`).assign(I,(0,n._)`+${b}`);return;case"boolean":k.elseIf((0,n._)`${b} === "false" || ${b} === 0 || ${b} === null`).assign(I,!1).elseIf((0,n._)`${b} === "true" || ${b} === 1`).assign(I,!0);return;case"null":k.elseIf((0,n._)`${b} === "" || ${b} === 0 || ${b} === false`),k.assign(I,null);return;case"array":k.elseIf((0,n._)`${x} === "string" || ${x} === "number"
85
+ || ${x} === "boolean" || ${b} === null`).assign(I,(0,n._)`[${b}]`)}}}function p({gen:_,parentData:h,parentDataProperty:T},k){_.if((0,n._)`${h} !== undefined`,()=>_.assign((0,n._)`${h}[${T}]`,k))}function f(_,h,T,k=s.Correct){const b=k===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(_){case"null":return(0,n._)`${h} ${b} null`;case"array":S=(0,n._)`Array.isArray(${h})`;break;case"object":S=(0,n._)`${h} && typeof ${h} == "object" && !Array.isArray(${h})`;break;case"integer":S=x((0,n._)`!(${h} % 1) && !isNaN(${h})`);break;case"number":S=x();break;default:return(0,n._)`typeof ${h} ${b} ${_}`}return k===s.Correct?S:(0,n.not)(S);function x(I=n.nil){return(0,n.and)((0,n._)`typeof ${h} == "number"`,I,T?(0,n._)`isFinite(${h})`:n.nil)}}Rt.checkDataType=f;function g(_,h,T,k){if(_.length===1)return f(_[0],h,T,k);let b;const S=(0,o.toHash)(_);if(S.array&&S.object){const x=(0,n._)`typeof ${h} != "object"`;b=S.null?x:(0,n._)`!${h} || ${x}`,delete S.null,delete S.array,delete S.object}else b=n.nil;S.number&&delete S.integer;for(const x in S)b=(0,n.and)(b,f(x,h,T,k));return b}Rt.checkDataTypes=g;const v={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:h})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${h}}`};function y(_){const h=w(_);(0,r.reportError)(h,v)}Rt.reportTypeError=y;function w(_){const{gen:h,data:T,schema:k}=_,b=(0,o.schemaRefOrVal)(_,k,"type");return{gen:h,keyword:"type",data:T,schema:k.type,schemaCode:b,schemaValue:b,parentSchema:k,params:{},it:_}}return Rt}var as={},Vg;function hx(){if(Vg)return as;Vg=1,Object.defineProperty(as,"__esModule",{value:!0}),as.assignDefaults=void 0;const e=Pe(),t=je();function r(o,s){const{properties:a,items:i}=o.schema;if(s==="object"&&a)for(const l in a)n(o,l,a[l].default);else s==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}as.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const m=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${m}`);return}let p=(0,e._)`${m} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${m} === null || ${m} === ""`),i.if(p,(0,e._)`${m} = ${(0,e.stringify)(a)}`)}return as}var pr={},Ze={},Zg;function fr(){if(Zg)return Ze;Zg=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.validateUnion=Ze.validateArray=Ze.usePattern=Ze.callValidateCode=Ze.schemaProperties=Ze.allSchemaProperties=Ze.noPropertyInData=Ze.propertyInData=Ze.isOwnProperty=Ze.hasPropFunc=Ze.reportMissingProp=Ze.checkMissingProp=Ze.checkReportMissingProp=void 0;const e=Pe(),t=je(),r=an(),n=je();function o(_,h){const{gen:T,data:k,it:b}=_;T.if(u(T,k,h,b.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${h}`},!0),_.error()})}Ze.checkReportMissingProp=o;function s({gen:_,data:h,it:{opts:T}},k,b){return(0,e.or)(...k.map(S=>(0,e.and)(u(_,h,S,T.ownProperties),(0,e._)`${b} = ${S}`)))}Ze.checkMissingProp=s;function a(_,h){_.setParams({missingProperty:h},!0),_.error()}Ze.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ze.hasPropFunc=i;function l(_,h,T){return(0,e._)`${i(_)}.call(${h}, ${T})`}Ze.isOwnProperty=l;function c(_,h,T,k){const b=(0,e._)`${h}${(0,e.getProperty)(T)} !== undefined`;return k?(0,e._)`${b} && ${l(_,h,T)}`:b}Ze.propertyInData=c;function u(_,h,T,k){const b=(0,e._)`${h}${(0,e.getProperty)(T)} === undefined`;return k?(0,e.or)(b,(0,e.not)(l(_,h,T))):b}Ze.noPropertyInData=u;function m(_){return _?Object.keys(_).filter(h=>h!=="__proto__"):[]}Ze.allSchemaProperties=m;function p(_,h){return m(h).filter(T=>!(0,t.alwaysValidSchema)(_,h[T]))}Ze.schemaProperties=p;function f({schemaCode:_,data:h,it:{gen:T,topSchemaRef:k,schemaPath:b,errorPath:S},it:x},I,L,$){const O=$?(0,e._)`${_}, ${h}, ${k}${b}`:h,A=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&A.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const U=(0,e._)`${O}, ${T.object(...A)}`;return L!==e.nil?(0,e._)`${I}.call(${L}, ${U})`:(0,e._)`${I}(${U})`}Ze.callValidateCode=f;const g=(0,e._)`new RegExp`;function v({gen:_,it:{opts:h}},T){const k=h.unicodeRegExp?"u":"",{regExp:b}=h.code,S=b(T,k);return _.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${b.code==="new RegExp"?g:(0,n.useFunc)(_,b)}(${T}, ${k})`})}Ze.usePattern=v;function y(_){const{gen:h,data:T,keyword:k,it:b}=_,S=h.name("valid");if(b.allErrors){const I=h.let("valid",!0);return x(()=>h.assign(I,!1)),I}return h.var(S,!0),x(()=>h.break()),S;function x(I){const L=h.const("len",(0,e._)`${T}.length`);h.forRange("i",0,L,$=>{_.subschema({keyword:k,dataProp:$,dataPropType:t.Type.Num},S),h.if((0,e.not)(S),I)})}}Ze.validateArray=y;function w(_){const{gen:h,schema:T,keyword:k,it:b}=_;if(!Array.isArray(T))throw new Error("ajv implementation error");if(T.some(L=>(0,t.alwaysValidSchema)(b,L))&&!b.opts.unevaluated)return;const x=h.let("valid",!1),I=h.name("_valid");h.block(()=>T.forEach((L,$)=>{const O=_.subschema({keyword:k,schemaProp:$,compositeRule:!0},I);h.assign(x,(0,e._)`${x} || ${I}`),_.mergeValidEvaluated(O,I)||h.if((0,e.not)(x))})),_.result(x,()=>_.reset(),()=>_.error(!0))}return Ze.validateUnion=w,Ze}var Bg;function mx(){if(Bg)return pr;Bg=1,Object.defineProperty(pr,"__esModule",{value:!0}),pr.validateKeywordUsage=pr.validSchemaType=pr.funcKeywordCode=pr.macroKeywordCode=void 0;const e=Pe(),t=an(),r=fr(),n=Ra();function o(p,f){const{gen:g,keyword:v,schema:y,parentSchema:w,it:_}=p,h=f.macro.call(_.self,y,w,_),T=c(g,v,h);_.opts.validateSchema!==!1&&_.self.validateSchema(h,!0);const k=g.name("valid");p.subschema({schema:h,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${v}`,topSchemaRef:T,compositeRule:!0},k),p.pass(k,()=>p.error(!0))}pr.macroKeywordCode=o;function s(p,f){var g;const{gen:v,keyword:y,schema:w,parentSchema:_,$data:h,it:T}=p;l(T,f);const k=!h&&f.compile?f.compile.call(T.self,w,_,T):f.validate,b=c(v,y,k),S=v.let("valid");p.block$data(S,x),p.ok((g=f.valid)!==null&&g!==void 0?g:S);function x(){if(f.errors===!1)$(),f.modifying&&a(p),O(()=>p.error());else{const A=f.async?I():L();f.modifying&&a(p),O(()=>i(p,A))}}function I(){const A=v.let("ruleErrs",null);return v.try(()=>$((0,e._)`await `),U=>v.assign(S,!1).if((0,e._)`${U} instanceof ${T.ValidationError}`,()=>v.assign(A,(0,e._)`${U}.errors`),()=>v.throw(U))),A}function L(){const A=(0,e._)`${b}.errors`;return v.assign(A,null),$(e.nil),A}function $(A=f.async?(0,e._)`await `:e.nil){const U=T.opts.passContext?t.default.this:t.default.self,Z=!("compile"in f&&!h||f.schema===!1);v.assign(S,(0,e._)`${A}${(0,r.callValidateCode)(p,b,U,Z)}`,f.modifying)}function O(A){var U;v.if((0,e.not)((U=f.valid)!==null&&U!==void 0?U:S),A)}}pr.funcKeywordCode=s;function a(p){const{gen:f,data:g,it:v}=p;f.if(v.parentData,()=>f.assign(g,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function i(p,f){const{gen:g}=p;g.if((0,e._)`Array.isArray(${f})`,()=>{g.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${f} : ${t.default.vErrors}.concat(${f})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},f){if(f.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,f,g){if(g===void 0)throw new Error(`keyword "${f}" failed to compile`);return p.scopeValue("keyword",typeof g=="function"?{ref:g}:{ref:g,code:(0,e.stringify)(g)})}function u(p,f,g=!1){return!f.length||f.some(v=>v==="array"?Array.isArray(p):v==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==v||g&&typeof p>"u")}pr.validSchemaType=u;function m({schema:p,opts:f,self:g,errSchemaPath:v},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const _=y.dependencies;if(_?.some(h=>!Object.prototype.hasOwnProperty.call(p,h)))throw new Error(`parent schema must have dependencies of ${w}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const T=`keyword "${w}" value is invalid at path "${v}": `+g.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")g.logger.error(T);else throw new Error(T)}}return pr.validateKeywordUsage=m,pr}var Dr={},Hg;function gx(){if(Hg)return Dr;Hg=1,Object.defineProperty(Dr,"__esModule",{value:!0}),Dr.extendSubschemaMode=Dr.extendSubschemaData=Dr.getSubschema=void 0;const e=Pe(),t=je();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:m}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const p=s.schema[a];return i===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:p[i],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||m===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:m,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Dr.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:m}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=a;if(i!==void 0){const{errorPath:g,dataPathArr:v,opts:y}=a,w=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);f(w),s.errorPath=(0,e.str)`${g}${(0,t.getErrorPath)(i,l,y.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[...v,s.parentDataProperty]}if(c!==void 0){const g=c instanceof e.Name?c:p.let("data",c,!0);f(g),m!==void 0&&(s.propertyName=m)}u&&(s.dataTypes=u);function f(g){s.data=g,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,g]}}Dr.extendSubschemaData=n;function o(s,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=a,s.jtdMetadata=i}return Dr.extendSubschemaMode=o,Dr}var jt={},Qc,Jg;function Gg(){return Jg||(Jg=1,Qc=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var a=s[o];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}),Qc}var Xc={exports:{}},Wg;function yx(){if(Wg)return Xc.exports;Wg=1;var e=Xc.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var a=typeof s=="function"?s:s.pre||function(){},i=s.post||function(){};t(o,a,i,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,a,i,l,c,u,m,p){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,m,p);for(var f in a){var g=a[f];if(Array.isArray(g)){if(f in e.arrayKeywords)for(var v=0;v<g.length;v++)t(n,o,s,g[v],i+"/"+f+"/"+v,l,i,f,a,v)}else if(f in e.propsKeywords){if(g&&typeof g=="object")for(var y in g)t(n,o,s,g[y],i+"/"+f+"/"+r(y),l,i,f,a,y)}else(f in e.keywords||n.allKeys&&!(f in e.skipKeywords))&&t(n,o,s,g,i+"/"+f,l,i,f,a)}s(a,i,l,c,u,m,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Xc.exports}var Kg;function Na(){if(Kg)return jt;Kg=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.getSchemaRefs=jt.resolveUrl=jt.normalizeId=jt._getFullPath=jt.getFullPath=jt.inlineRef=void 0;const e=je(),t=Gg(),r=yx(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(v,y=!0){return typeof v=="boolean"?!0:y===!0?!a(v):y?i(v)<=y:!1}jt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(v){for(const y in v){if(s.has(y))return!0;const w=v[y];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(v){let y=0;for(const w in v){if(w==="$ref")return 1/0;if(y++,!n.has(w)&&(typeof v[w]=="object"&&(0,e.eachItem)(v[w],_=>y+=i(_)),y===1/0))return 1/0}return y}function l(v,y="",w){w!==!1&&(y=m(y));const _=v.parse(y);return c(v,_)}jt.getFullPath=l;function c(v,y){return v.serialize(y).split("#")[0]+"#"}jt._getFullPath=c;const u=/#\/?$/;function m(v){return v?v.replace(u,""):""}jt.normalizeId=m;function p(v,y,w){return w=m(w),v.resolve(y,w)}jt.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function g(v,y){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:_}=this.opts,h=m(v[w]||y),T={"":h},k=l(_,h,!1),b={},S=new Set;return r(v,{allKeys:!0},(L,$,O,A)=>{if(A===void 0)return;const U=k+$;let Z=T[A];typeof L[w]=="string"&&(Z=Y.call(this,L[w])),ye.call(this,L.$anchor),ye.call(this,L.$dynamicAnchor),T[$]=Z;function Y(X){const he=this.opts.uriResolver.resolve;if(X=m(Z?he(Z,X):X),S.has(X))throw I(X);S.add(X);let B=this.refs[X];return typeof B=="string"&&(B=this.refs[B]),typeof B=="object"?x(L,B.schema,X):X!==m(U)&&(X[0]==="#"?(x(L,b[X],X),b[X]=L):this.refs[X]=U),X}function ye(X){if(typeof X=="string"){if(!f.test(X))throw new Error(`invalid anchor "${X}"`);Y.call(this,`#${X}`)}}}),b;function x(L,$,O){if($!==void 0&&!t(L,$))throw I(O)}function I(L){return new Error(`reference "${L}" resolves to more than one schema`)}}return jt.getSchemaRefs=g,jt}var Yg;function Ma(){if(Yg)return Lr;Yg=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.getData=Lr.KeywordCxt=Lr.validateFunctionCode=void 0;const e=fx(),t=Pa(),r=zg(),n=Pa(),o=hx(),s=mx(),a=gx(),i=Pe(),l=an(),c=Na(),u=je(),m=Ra();function p(z){if(k(z)&&(S(z),T(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Lr.validateFunctionCode=p;function f({gen:z,validateName:V,schema:W,schemaEnv:Q,opts:ie},_e){ie.code.es5?z.func(V,(0,i._)`${l.default.data}, ${l.default.valCxt}`,Q.$async,()=>{z.code((0,i._)`"use strict"; ${_(W,ie)}`),v(z,ie),z.code(_e)}):z.func(V,(0,i._)`${l.default.data}, ${g(ie)}`,Q.$async,()=>z.code(_(W,ie)).code(_e))}function g(z){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${z.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function v(z,V){z.if(l.default.valCxt,()=>{z.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),z.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),z.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),z.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{z.var(l.default.instancePath,(0,i._)`""`),z.var(l.default.parentData,(0,i._)`undefined`),z.var(l.default.parentDataProperty,(0,i._)`undefined`),z.var(l.default.rootData,l.default.data),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function y(z){const{schema:V,opts:W,gen:Q}=z;f(z,()=>{W.$comment&&V.$comment&&A(z),L(z),Q.let(l.default.vErrors,null),Q.let(l.default.errors,0),W.unevaluated&&w(z),x(z),U(z)})}function w(z){const{gen:V,validateName:W}=z;z.evaluated=V.const("evaluated",(0,i._)`${W}.evaluated`),V.if((0,i._)`${z.evaluated}.dynamicProps`,()=>V.assign((0,i._)`${z.evaluated}.props`,(0,i._)`undefined`)),V.if((0,i._)`${z.evaluated}.dynamicItems`,()=>V.assign((0,i._)`${z.evaluated}.items`,(0,i._)`undefined`))}function _(z,V){const W=typeof z=="object"&&z[V.schemaId];return W&&(V.code.source||V.code.process)?(0,i._)`/*# sourceURL=${W} */`:i.nil}function h(z,V){if(k(z)&&(S(z),T(z))){b(z,V);return}(0,e.boolOrEmptySchema)(z,V)}function T({schema:z,self:V}){if(typeof z=="boolean")return!z;for(const W in z)if(V.RULES.all[W])return!0;return!1}function k(z){return typeof z.schema!="boolean"}function b(z,V){const{schema:W,gen:Q,opts:ie}=z;ie.$comment&&W.$comment&&A(z),$(z),O(z);const _e=Q.const("_errs",l.default.errors);x(z,_e),Q.var(V,(0,i._)`${_e} === ${l.default.errors}`)}function S(z){(0,u.checkUnknownRules)(z),I(z)}function x(z,V){if(z.opts.jtd)return Y(z,[],!1,V);const W=(0,t.getSchemaTypes)(z.schema),Q=(0,t.coerceAndCheckDataType)(z,W);Y(z,W,!Q,V)}function I(z){const{schema:V,errSchemaPath:W,opts:Q,self:ie}=z;V.$ref&&Q.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(V,ie.RULES)&&ie.logger.warn(`$ref: keywords ignored in schema at path "${W}"`)}function L(z){const{schema:V,opts:W}=z;V.default!==void 0&&W.useDefaults&&W.strictSchema&&(0,u.checkStrictMode)(z,"default is ignored in the schema root")}function $(z){const V=z.schema[z.opts.schemaId];V&&(z.baseId=(0,c.resolveUrl)(z.opts.uriResolver,z.baseId,V))}function O(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function A({gen:z,schemaEnv:V,schema:W,errSchemaPath:Q,opts:ie}){const _e=W.$comment;if(ie.$comment===!0)z.code((0,i._)`${l.default.self}.logger.log(${_e})`);else if(typeof ie.$comment=="function"){const Ye=(0,i.str)`${Q}/$comment`,ct=z.scopeValue("root",{ref:V.root});z.code((0,i._)`${l.default.self}.opts.$comment(${_e}, ${Ye}, ${ct}.schema)`)}}function U(z){const{gen:V,schemaEnv:W,validateName:Q,ValidationError:ie,opts:_e}=z;W.$async?V.if((0,i._)`${l.default.errors} === 0`,()=>V.return(l.default.data),()=>V.throw((0,i._)`new ${ie}(${l.default.vErrors})`)):(V.assign((0,i._)`${Q}.errors`,l.default.vErrors),_e.unevaluated&&Z(z),V.return((0,i._)`${l.default.errors} === 0`))}function Z({gen:z,evaluated:V,props:W,items:Q}){W instanceof i.Name&&z.assign((0,i._)`${V}.props`,W),Q instanceof i.Name&&z.assign((0,i._)`${V}.items`,Q)}function Y(z,V,W,Q){const{gen:ie,schema:_e,data:Ye,allErrors:ct,opts:pt,self:rt}=z,{RULES:P}=rt;if(_e.$ref&&(pt.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(_e,P))){ie.block(()=>G(z,"$ref",P.all.$ref.definition));return}pt.jtd||X(z,V),ie.block(()=>{for(const Re of P.rules)re(Re);re(P.post)});function re(Re){(0,r.shouldUseGroup)(_e,Re)&&(Re.type?(ie.if((0,n.checkDataType)(Re.type,Ye,pt.strictNumbers)),ye(z,Re),V.length===1&&V[0]===Re.type&&W&&(ie.else(),(0,n.reportTypeError)(z)),ie.endIf()):ye(z,Re),ct||ie.if((0,i._)`${l.default.errors} === ${Q||0}`))}}function ye(z,V){const{gen:W,schema:Q,opts:{useDefaults:ie}}=z;ie&&(0,o.assignDefaults)(z,V.type),W.block(()=>{for(const _e of V.rules)(0,r.shouldUseRule)(Q,_e)&&G(z,_e.keyword,_e.definition,V.type)})}function X(z,V){z.schemaEnv.meta||!z.opts.strictTypes||(he(z,V),z.opts.allowUnionTypes||B(z,V),N(z,z.dataTypes))}function he(z,V){if(V.length){if(!z.dataTypes.length){z.dataTypes=V;return}V.forEach(W=>{F(z.dataTypes,W)||M(z,`type "${W}" not allowed by context "${z.dataTypes.join(",")}"`)}),E(z,V)}}function B(z,V){V.length>1&&!(V.length===2&&V.includes("null"))&&M(z,"use allowUnionTypes to allow union type keyword")}function N(z,V){const W=z.self.RULES.all;for(const Q in W){const ie=W[Q];if(typeof ie=="object"&&(0,r.shouldUseRule)(z.schema,ie)){const{type:_e}=ie.definition;_e.length&&!_e.some(Ye=>H(V,Ye))&&M(z,`missing type "${_e.join(",")}" for keyword "${Q}"`)}}}function H(z,V){return z.includes(V)||V==="number"&&z.includes("integer")}function F(z,V){return z.includes(V)||V==="integer"&&z.includes("number")}function E(z,V){const W=[];for(const Q of z.dataTypes)F(V,Q)?W.push(Q):V.includes("integer")&&Q==="number"&&W.push("integer");z.dataTypes=W}function M(z,V){const W=z.schemaEnv.baseId+z.errSchemaPath;V+=` at "${W}" (strictTypes)`,(0,u.checkStrictMode)(z,V,z.opts.strictTypes)}class D{constructor(V,W,Q){if((0,s.validateKeywordUsage)(V,W,Q),this.gen=V.gen,this.allErrors=V.allErrors,this.keyword=Q,this.data=V.data,this.schema=V.schema[Q],this.$data=W.$data&&V.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(V,this.schema,Q,this.$data),this.schemaType=W.schemaType,this.parentSchema=V.schema,this.params={},this.it=V,this.def=W,this.$data)this.schemaCode=V.gen.const("vSchema",Te(this.$data,V));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,W.schemaType,W.allowUndefined))throw new Error(`${Q} value must be ${JSON.stringify(W.schemaType)}`);("code"in W?W.trackErrors:W.errors!==!1)&&(this.errsCount=V.gen.const("_errs",l.default.errors))}result(V,W,Q){this.failResult((0,i.not)(V),W,Q)}failResult(V,W,Q){this.gen.if(V),Q?Q():this.error(),W?(this.gen.else(),W(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(V,W){this.failResult((0,i.not)(V),void 0,W)}fail(V){if(V===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(V),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(V){if(!this.$data)return this.fail(V);const{schemaCode:W}=this;this.fail((0,i._)`${W} !== undefined && (${(0,i.or)(this.invalid$data(),V)})`)}error(V,W,Q){if(W){this.setParams(W),this._error(V,Q),this.setParams({});return}this._error(V,Q)}_error(V,W){(V?m.reportExtraError:m.reportError)(this,this.def.error,W)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(V){this.allErrors||this.gen.if(V)}setParams(V,W){W?Object.assign(this.params,V):this.params=V}block$data(V,W,Q=i.nil){this.gen.block(()=>{this.check$data(V,Q),W()})}check$data(V=i.nil,W=i.nil){if(!this.$data)return;const{gen:Q,schemaCode:ie,schemaType:_e,def:Ye}=this;Q.if((0,i.or)((0,i._)`${ie} === undefined`,W)),V!==i.nil&&Q.assign(V,!0),(_e.length||Ye.validateSchema)&&(Q.elseIf(this.invalid$data()),this.$dataError(),V!==i.nil&&Q.assign(V,!1)),Q.else()}invalid$data(){const{gen:V,schemaCode:W,schemaType:Q,def:ie,it:_e}=this;return(0,i.or)(Ye(),ct());function Ye(){if(Q.length){if(!(W instanceof i.Name))throw new Error("ajv implementation error");const pt=Array.isArray(Q)?Q:[Q];return(0,i._)`${(0,n.checkDataTypes)(pt,W,_e.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function ct(){if(ie.validateSchema){const pt=V.scopeValue("validate$data",{ref:ie.validateSchema});return(0,i._)`!${pt}(${W})`}return i.nil}}subschema(V,W){const Q=(0,a.getSubschema)(this.it,V);(0,a.extendSubschemaData)(Q,this.it,V),(0,a.extendSubschemaMode)(Q,V);const ie={...this.it,...Q,items:void 0,props:void 0};return h(ie,W),ie}mergeEvaluated(V,W){const{it:Q,gen:ie}=this;Q.opts.unevaluated&&(Q.props!==!0&&V.props!==void 0&&(Q.props=u.mergeEvaluated.props(ie,V.props,Q.props,W)),Q.items!==!0&&V.items!==void 0&&(Q.items=u.mergeEvaluated.items(ie,V.items,Q.items,W)))}mergeValidEvaluated(V,W){const{it:Q,gen:ie}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return ie.if(W,()=>this.mergeEvaluated(V,i.Name)),!0}}Lr.KeywordCxt=D;function G(z,V,W,Q){const ie=new D(z,W,V);"code"in W?W.code(ie,Q):ie.$data&&W.validate?(0,s.funcKeywordCode)(ie,W):"macro"in W?(0,s.macroKeywordCode)(ie,W):(W.compile||W.validate)&&(0,s.funcKeywordCode)(ie,W)}const te=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Te(z,{dataLevel:V,dataNames:W,dataPathArr:Q}){let ie,_e;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!te.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);ie=z,_e=l.default.rootData}else{const rt=se.exec(z);if(!rt)throw new Error(`Invalid JSON-pointer: ${z}`);const P=+rt[1];if(ie=rt[2],ie==="#"){if(P>=V)throw new Error(pt("property/index",P));return Q[V-P]}if(P>V)throw new Error(pt("data",P));if(_e=W[V-P],!ie)return _e}let Ye=_e;const ct=ie.split("/");for(const rt of ct)rt&&(_e=(0,i._)`${_e}${(0,i.getProperty)((0,u.unescapeJsonPointer)(rt))}`,Ye=(0,i._)`${Ye} && ${_e}`);return Ye;function pt(rt,P){return`Cannot access ${rt} ${P} levels up, current level is ${V}`}}return Lr.getData=Te,Lr}var Oa={},Qg;function eu(){if(Qg)return Oa;Qg=1,Object.defineProperty(Oa,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Oa.default=e,Oa}var Aa={},Xg;function qa(){if(Xg)return Aa;Xg=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=Na();class t extends Error{constructor(n,o,s,a){super(a||`can't resolve reference ${s} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return Aa.default=t,Aa}var Gt={},ey;function tu(){if(ey)return Gt;ey=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.resolveSchema=Gt.getCompilingSchema=Gt.resolveRef=Gt.compileSchema=Gt.SchemaEnv=void 0;const e=Pe(),t=eu(),r=an(),n=Na(),o=je(),s=Ma();class a{constructor(w){var _;this.refs={},this.dynamicAnchors={};let h;typeof w.schema=="object"&&(h=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(_=w.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(h?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=h?.$async,this.refs={}}}Gt.SchemaEnv=a;function i(y){const w=u.call(this,y);if(w)return w;const _=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:h,lines:T}=this.opts.code,{ownProperties:k}=this.opts,b=new e.CodeGen(this.scope,{es5:h,lines:T,ownProperties:k});let S;y.$async&&(S=b.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const x=b.scopeName("validate");y.validateName=x;const I={gen:b,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:b.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:x,ValidationError:S,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let L;try{this._compilations.add(y),(0,s.validateFunctionCode)(I),b.optimize(this.opts.code.optimize);const $=b.toString();L=`${b.scopeRefs(r.default.scope)}return ${$}`,this.opts.code.process&&(L=this.opts.code.process(L,y));const A=new Function(`${r.default.self}`,`${r.default.scope}`,L)(this,this.scope.get());if(this.scope.value(x,{ref:A}),A.errors=null,A.schema=y.schema,A.schemaEnv=y,y.$async&&(A.$async=!0),this.opts.code.source===!0&&(A.source={validateName:x,validateCode:$,scopeValues:b._values}),this.opts.unevaluated){const{props:U,items:Z}=I;A.evaluated={props:U instanceof e.Name?void 0:U,items:Z instanceof e.Name?void 0:Z,dynamicProps:U instanceof e.Name,dynamicItems:Z instanceof e.Name},A.source&&(A.source.evaluated=(0,e.stringify)(A.evaluated))}return y.validate=A,y}catch($){throw delete y.validate,delete y.validateName,L&&this.logger.error("Error compiling schema, function code:",L),$}finally{this._compilations.delete(y)}}Gt.compileSchema=i;function l(y,w,_){var h;_=(0,n.resolveUrl)(this.opts.uriResolver,w,_);const T=y.refs[_];if(T)return T;let k=p.call(this,y,_);if(k===void 0){const b=(h=y.localRefs)===null||h===void 0?void 0:h[_],{schemaId:S}=this.opts;b&&(k=new a({schema:b,schemaId:S,root:y,baseId:w}))}if(k!==void 0)return y.refs[_]=c.call(this,k)}Gt.resolveRef=l;function c(y){return(0,n.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:i.call(this,y)}function u(y){for(const w of this._compilations)if(m(w,y))return w}Gt.getCompilingSchema=u;function m(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let _;for(;typeof(_=this.refs[w])=="string";)w=_;return _||this.schemas[w]||f.call(this,y,w)}function f(y,w){const _=this.opts.uriResolver.parse(w),h=(0,n._getFullPath)(this.opts.uriResolver,_);let T=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&h===T)return v.call(this,_,y);const k=(0,n.normalizeId)(h),b=this.refs[k]||this.schemas[k];if(typeof b=="string"){const S=f.call(this,y,b);return typeof S?.schema!="object"?void 0:v.call(this,_,S)}if(typeof b?.schema=="object"){if(b.validate||i.call(this,b),k===(0,n.normalizeId)(w)){const{schema:S}=b,{schemaId:x}=this.opts,I=S[x];return I&&(T=(0,n.resolveUrl)(this.opts.uriResolver,T,I)),new a({schema:S,schemaId:x,root:y,baseId:T})}return v.call(this,_,b)}}Gt.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(y,{baseId:w,schema:_,root:h}){var T;if(((T=y.fragment)===null||T===void 0?void 0:T[0])!=="/")return;for(const S of y.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const x=_[(0,o.unescapeFragment)(S)];if(x===void 0)return;_=x;const I=typeof _=="object"&&_[this.opts.schemaId];!g.has(S)&&I&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,I))}let k;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const S=(0,n.resolveUrl)(this.opts.uriResolver,w,_.$ref);k=f.call(this,h,S)}const{schemaId:b}=this.opts;if(k=k||new a({schema:_,schemaId:b,root:h,baseId:w}),k.schema!==k.root.schema)return k}return Gt}const _x={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var La={},is={exports:{}},ru,ty;function ry(){if(ty)return ru;ty=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(p){let f="",g=0,v=0;for(v=0;v<p.length;v++)if(g=p[v].charCodeAt(0),g!==48){if(!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[v];break}for(v+=1;v<p.length;v++){if(g=p[v].charCodeAt(0),!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[v]}return f}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,f,g){if(p.length){const v=r(p);if(v!=="")f.push(v);else return g.error=!0,!1;p.length=0}return!0}function a(p){let f=0;const g={error:!1,address:"",zone:""},v=[],y=[];let w=!1,_=!1,h=s;for(let T=0;T<p.length;T++){const k=p[T];if(!(k==="["||k==="]"))if(k===":"){if(w===!0&&(_=!0),!h(y,v,g))break;if(++f>7){g.error=!0;break}T>0&&p[T-1]===":"&&(w=!0),v.push(":");continue}else if(k==="%"){if(!h(y,v,g))break;h=o}else{y.push(k);continue}}return y.length&&(h===o?g.zone=y.join(""):_?v.push(y.join("")):v.push(r(y))),g.address=v.join(""),g}function i(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const f=a(p);if(f.error)return{host:p,isIPV6:!1};{let g=f.address,v=f.address;return f.zone&&(g+="%"+f.zone,v+="%25"+f.zone),{host:g,isIPV6:!0,escapedHost:v}}}function l(p,f){let g=0;for(let v=0;v<p.length;v++)p[v]===f&&g++;return g}function c(p){let f=p;const g=[];let v=-1,y=0;for(;y=f.length;){if(y===1){if(f===".")break;if(f==="/"){g.push("/");break}else{g.push(f);break}}else if(y===2){if(f[0]==="."){if(f[1]===".")break;if(f[1]==="/"){f=f.slice(2);continue}}else if(f[0]==="/"&&(f[1]==="."||f[1]==="/")){g.push("/");break}}else if(y===3&&f==="/.."){g.length!==0&&g.pop(),g.push("/");break}if(f[0]==="."){if(f[1]==="."){if(f[2]==="/"){f=f.slice(3);continue}}else if(f[1]==="/"){f=f.slice(2);continue}}else if(f[0]==="/"&&f[1]==="."){if(f[2]==="/"){f=f.slice(2);continue}else if(f[2]==="."&&f[3]==="/"){f=f.slice(3),g.length!==0&&g.pop();continue}}if((v=f.indexOf("/",1))===-1){g.push(f);break}else g.push(f.slice(0,v)),f=f.slice(v)}return g.join("")}function u(p,f){const g=f!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=g(p.scheme)),p.userinfo!==void 0&&(p.userinfo=g(p.userinfo)),p.host!==void 0&&(p.host=g(p.host)),p.path!==void 0&&(p.path=g(p.path)),p.query!==void 0&&(p.query=g(p.query)),p.fragment!==void 0&&(p.fragment=g(p.fragment)),p}function m(p){const f=[];if(p.userinfo!==void 0&&(f.push(p.userinfo),f.push("@")),p.host!==void 0){let g=unescape(p.host);if(!t(g)){const v=i(g);v.isIPV6===!0?g=`[${v.escapedHost}]`:g=p.host}f.push(g)}return(typeof p.port=="number"||typeof p.port=="string")&&(f.push(":"),f.push(String(p.port))),f.length?f.join(""):void 0}return ru={nonSimpleDomain:n,recomposeAuthority:m,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},ru}var nu,ny;function vx(){if(ny)return nu;ny=1;const{isUUID:e}=ry(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function o(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function s(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const b=String(k.scheme).toLowerCase()==="https";return(k.port===(b?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=o(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function l(k){if((k.port===(o(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[b,S]=k.resourceName.split("?");k.path=b&&b!=="/"?b:void 0,k.query=S,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,b){if(!k.path)return k.error="URN can not be parsed",k;const S=k.path.match(t);if(S){const x=b.scheme||k.scheme||"urn";k.nid=S[1].toLowerCase(),k.nss=S[2];const I=`${x}:${b.nid||k.nid}`,L=T(I);k.path=void 0,L&&(k=L.parse(k,b))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,b){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=b.scheme||k.scheme||"urn",x=k.nid.toLowerCase(),I=`${S}:${b.nid||x}`,L=T(I);L&&(k=L.serialize(k,b));const $=k,O=k.nss;return $.path=`${x||b.nid}:${O}`,b.skipEscape=!0,$}function m(k,b){const S=k;return S.uuid=S.nss,S.nss=void 0,!b.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(k){const b=k;return b.nss=(k.uuid||"").toLowerCase(),b}const f={scheme:"http",domainHost:!0,parse:s,serialize:a},g={scheme:"https",domainHost:f.domainHost,parse:s,serialize:a},v={scheme:"ws",domainHost:!0,parse:i,serialize:l},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},h={http:f,https:g,ws:v,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:m,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(h,null);function T(k){return k&&(h[k]||h[k.toLowerCase()])||void 0}return nu={wsIsSecure:o,SCHEMES:h,isValidSchemeName:n,getSchemeHandler:T},nu}var oy;function wx(){if(oy)return is.exports;oy=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=ry(),{SCHEMES:a,getSchemeHandler:i}=vx();function l(y,w){return typeof y=="string"?y=p(g(y,w),w):typeof y=="object"&&(y=g(p(y,w),w)),y}function c(y,w,_){const h=_?Object.assign({scheme:"null"},_):{scheme:"null"},T=u(g(y,h),g(w,h),h,!0);return h.skipEscape=!0,p(T,h)}function u(y,w,_,h){const T={};return h||(y=g(p(y,_),_),w=g(p(w,_),_)),_=_||{},!_.tolerant&&w.scheme?(T.scheme=w.scheme,T.userinfo=w.userinfo,T.host=w.host,T.port=w.port,T.path=t(w.path||""),T.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(T.userinfo=w.userinfo,T.host=w.host,T.port=w.port,T.path=t(w.path||""),T.query=w.query):(w.path?(w.path[0]==="/"?T.path=t(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?T.path="/"+w.path:y.path?T.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:T.path=w.path,T.path=t(T.path)),T.query=w.query):(T.path=y.path,w.query!==void 0?T.query=w.query:T.query=y.query),T.userinfo=y.userinfo,T.host=y.host,T.port=y.port),T.scheme=y.scheme),T.fragment=w.fragment,T}function m(y,w,_){return typeof y=="string"?(y=unescape(y),y=p(n(g(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{..._,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(g(w,_),!0),{..._,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{..._,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const _={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},h=Object.assign({},w),T=[],k=i(h.scheme||_.scheme);k&&k.serialize&&k.serialize(_,h),_.path!==void 0&&(h.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),h.reference!=="suffix"&&_.scheme&&T.push(_.scheme,":");const b=r(_);if(b!==void 0&&(h.reference!=="suffix"&&T.push("//"),T.push(b),_.path&&_.path[0]!=="/"&&T.push("/")),_.path!==void 0){let S=_.path;!h.absolutePath&&(!k||!k.absolutePath)&&(S=t(S)),b===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),T.push(S)}return _.query!==void 0&&T.push("?",_.query),_.fragment!==void 0&&T.push("#",_.fragment),T.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(y,w){const _=Object.assign({},w),h={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let T=!1;_.reference==="suffix"&&(_.scheme?y=_.scheme+":"+y:y="//"+y);const k=y.match(f);if(k){if(h.scheme=k[1],h.userinfo=k[3],h.host=k[4],h.port=parseInt(k[5],10),h.path=k[6]||"",h.query=k[7],h.fragment=k[8],isNaN(h.port)&&(h.port=k[5]),h.host)if(o(h.host)===!1){const x=e(h.host);h.host=x.host.toLowerCase(),T=x.isIPV6}else T=!0;h.scheme===void 0&&h.userinfo===void 0&&h.host===void 0&&h.port===void 0&&h.query===void 0&&!h.path?h.reference="same-document":h.scheme===void 0?h.reference="relative":h.fragment===void 0?h.reference="absolute":h.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==h.reference&&(h.error=h.error||"URI is not a "+_.reference+" reference.");const b=i(_.scheme||h.scheme);if(!_.unicodeSupport&&(!b||!b.unicodeSupport)&&h.host&&(_.domainHost||b&&b.domainHost)&&T===!1&&s(h.host))try{h.host=URL.domainToASCII(h.host.toLowerCase())}catch(S){h.error=h.error||"Host's domain name can not be converted to ASCII: "+S}(!b||b&&!b.skipNormalize)&&(y.indexOf("%")!==-1&&(h.scheme!==void 0&&(h.scheme=unescape(h.scheme)),h.host!==void 0&&(h.host=unescape(h.host))),h.path&&(h.path=escape(unescape(h.path))),h.fragment&&(h.fragment=encodeURI(decodeURIComponent(h.fragment)))),b&&b.parse&&b.parse(h,_)}else h.error=h.error||"URI can not be parsed.";return h}const v={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:m,serialize:p,parse:g};return is.exports=v,is.exports.default=v,is.exports.fastUri=v,is.exports}var sy;function bx(){if(sy)return La;sy=1,Object.defineProperty(La,"__esModule",{value:!0});const e=wx();return e.code='require("ajv/dist/runtime/uri").default',La.default=e,La}var ay;function kx(){return ay||(ay=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Ma();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Pe();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=eu(),o=qa(),s=Dg(),a=tu(),i=Pe(),l=Na(),c=Pa(),u=je(),m=_x,p=bx(),f=(B,N)=>new RegExp(B,N);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function h(B){var N,H,F,E,M,D,G,te,se,Te,z,V,W,Q,ie,_e,Ye,ct,pt,rt,P,re,Re,Me,nr;const Qe=B.strict,Wt=(N=B.code)===null||N===void 0?void 0:N.optimize,Vr=Wt===!0||Wt===void 0?1:Wt||0,Xe=(F=(H=B.code)===null||H===void 0?void 0:H.regExp)!==null&&F!==void 0?F:f,Se=(E=B.uriResolver)!==null&&E!==void 0?E:p.default;return{strictSchema:(D=(M=B.strictSchema)!==null&&M!==void 0?M:Qe)!==null&&D!==void 0?D:!0,strictNumbers:(te=(G=B.strictNumbers)!==null&&G!==void 0?G:Qe)!==null&&te!==void 0?te:!0,strictTypes:(Te=(se=B.strictTypes)!==null&&se!==void 0?se:Qe)!==null&&Te!==void 0?Te:"log",strictTuples:(V=(z=B.strictTuples)!==null&&z!==void 0?z:Qe)!==null&&V!==void 0?V:"log",strictRequired:(Q=(W=B.strictRequired)!==null&&W!==void 0?W:Qe)!==null&&Q!==void 0?Q:!1,code:B.code?{...B.code,optimize:Vr,regExp:Xe}:{optimize:Vr,regExp:Xe},loopRequired:(ie=B.loopRequired)!==null&&ie!==void 0?ie:_,loopEnum:(_e=B.loopEnum)!==null&&_e!==void 0?_e:_,meta:(Ye=B.meta)!==null&&Ye!==void 0?Ye:!0,messages:(ct=B.messages)!==null&&ct!==void 0?ct:!0,inlineRefs:(pt=B.inlineRefs)!==null&&pt!==void 0?pt:!0,schemaId:(rt=B.schemaId)!==null&&rt!==void 0?rt:"$id",addUsedSchema:(P=B.addUsedSchema)!==null&&P!==void 0?P:!0,validateSchema:(re=B.validateSchema)!==null&&re!==void 0?re:!0,validateFormats:(Re=B.validateFormats)!==null&&Re!==void 0?Re:!0,unicodeRegExp:(Me=B.unicodeRegExp)!==null&&Me!==void 0?Me:!0,int32range:(nr=B.int32range)!==null&&nr!==void 0?nr:!0,uriResolver:Se}}class T{constructor(N={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,N=this.opts={...N,...h(N)};const{es5:H,lines:F}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:H,lines:F}),this.logger=O(N.logger);const E=N.validateFormats;N.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,y,N,"NOT SUPPORTED"),k.call(this,w,N,"DEPRECATED","warn"),this._metaOpts=L.call(this),N.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),N.keywords&&I.call(this,N.keywords),typeof N.meta=="object"&&this.addMetaSchema(N.meta),S.call(this),N.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:N,meta:H,schemaId:F}=this.opts;let E=m;F==="id"&&(E={...m},E.id=E.$id,delete E.$id),H&&N&&this.addMetaSchema(E,E[F],!1)}defaultMeta(){const{meta:N,schemaId:H}=this.opts;return this.opts.defaultMeta=typeof N=="object"?N[H]||N:void 0}validate(N,H){let F;if(typeof N=="string"){if(F=this.getSchema(N),!F)throw new Error(`no schema with key or ref "${N}"`)}else F=this.compile(N);const E=F(H);return"$async"in F||(this.errors=F.errors),E}compile(N,H){const F=this._addSchema(N,H);return F.validate||this._compileSchemaEnv(F)}compileAsync(N,H){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:F}=this.opts;return E.call(this,N,H);async function E(Te,z){await M.call(this,Te.$schema);const V=this._addSchema(Te,z);return V.validate||D.call(this,V)}async function M(Te){Te&&!this.getSchema(Te)&&await E.call(this,{$ref:Te},!0)}async function D(Te){try{return this._compileSchemaEnv(Te)}catch(z){if(!(z instanceof o.default))throw z;return G.call(this,z),await te.call(this,z.missingSchema),D.call(this,Te)}}function G({missingSchema:Te,missingRef:z}){if(this.refs[Te])throw new Error(`AnySchema ${Te} is loaded but ${z} cannot be resolved`)}async function te(Te){const z=await se.call(this,Te);this.refs[Te]||await M.call(this,z.$schema),this.refs[Te]||this.addSchema(z,Te,H)}async function se(Te){const z=this._loading[Te];if(z)return z;try{return await(this._loading[Te]=F(Te))}finally{delete this._loading[Te]}}}addSchema(N,H,F,E=this.opts.validateSchema){if(Array.isArray(N)){for(const D of N)this.addSchema(D,void 0,F,E);return this}let M;if(typeof N=="object"){const{schemaId:D}=this.opts;if(M=N[D],M!==void 0&&typeof M!="string")throw new Error(`schema ${D} must be string`)}return H=(0,l.normalizeId)(H||M),this._checkUnique(H),this.schemas[H]=this._addSchema(N,F,H,E,!0),this}addMetaSchema(N,H,F=this.opts.validateSchema){return this.addSchema(N,H,!0,F),this}validateSchema(N,H){if(typeof N=="boolean")return!0;let F;if(F=N.$schema,F!==void 0&&typeof F!="string")throw new Error("$schema must be a string");if(F=F||this.opts.defaultMeta||this.defaultMeta(),!F)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(F,N);if(!E&&H){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return E}getSchema(N){let H;for(;typeof(H=b.call(this,N))=="string";)N=H;if(H===void 0){const{schemaId:F}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:F});if(H=a.resolveSchema.call(this,E,N),!H)return;this.refs[N]=H}return H.validate||this._compileSchemaEnv(H)}removeSchema(N){if(N instanceof RegExp)return this._removeAllSchemas(this.schemas,N),this._removeAllSchemas(this.refs,N),this;switch(typeof N){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const H=b.call(this,N);return typeof H=="object"&&this._cache.delete(H.schema),delete this.schemas[N],delete this.refs[N],this}case"object":{const H=N;this._cache.delete(H);let F=N[this.opts.schemaId];return F&&(F=(0,l.normalizeId)(F),delete this.schemas[F],delete this.refs[F]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(N){for(const H of N)this.addKeyword(H);return this}addKeyword(N,H){let F;if(typeof N=="string")F=N,typeof H=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),H.keyword=F);else if(typeof N=="object"&&H===void 0){if(H=N,F=H.keyword,Array.isArray(F)&&!F.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,F,H),!H)return(0,u.eachItem)(F,M=>Z.call(this,M)),this;ye.call(this,H);const E={...H,type:(0,c.getJSONTypes)(H.type),schemaType:(0,c.getJSONTypes)(H.schemaType)};return(0,u.eachItem)(F,E.type.length===0?M=>Z.call(this,M,E):M=>E.type.forEach(D=>Z.call(this,M,E,D))),this}getKeyword(N){const H=this.RULES.all[N];return typeof H=="object"?H.definition:!!H}removeKeyword(N){const{RULES:H}=this;delete H.keywords[N],delete H.all[N];for(const F of H.rules){const E=F.rules.findIndex(M=>M.keyword===N);E>=0&&F.rules.splice(E,1)}return this}addFormat(N,H){return typeof H=="string"&&(H=new RegExp(H)),this.formats[N]=H,this}errorsText(N=this.errors,{separator:H=", ",dataVar:F="data"}={}){return!N||N.length===0?"No errors":N.map(E=>`${F}${E.instancePath} ${E.message}`).reduce((E,M)=>E+H+M)}$dataMetaSchema(N,H){const F=this.RULES.all;N=JSON.parse(JSON.stringify(N));for(const E of H){const M=E.split("/").slice(1);let D=N;for(const G of M)D=D[G];for(const G in F){const te=F[G];if(typeof te!="object")continue;const{$data:se}=te.definition,Te=D[G];se&&Te&&(D[G]=he(Te))}}return N}_removeAllSchemas(N,H){for(const F in N){const E=N[F];(!H||H.test(F))&&(typeof E=="string"?delete N[F]:E&&!E.meta&&(this._cache.delete(E.schema),delete N[F]))}}_addSchema(N,H,F,E=this.opts.validateSchema,M=this.opts.addUsedSchema){let D;const{schemaId:G}=this.opts;if(typeof N=="object")D=N[G];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof N!="boolean")throw new Error("schema must be object or boolean")}let te=this._cache.get(N);if(te!==void 0)return te;F=(0,l.normalizeId)(D||F);const se=l.getSchemaRefs.call(this,N,F);return te=new a.SchemaEnv({schema:N,schemaId:G,meta:H,baseId:F,localRefs:se}),this._cache.set(te.schema,te),M&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=te),E&&this.validateSchema(N,!0),te}_checkUnique(N){if(this.schemas[N]||this.refs[N])throw new Error(`schema with key or id "${N}" already exists`)}_compileSchemaEnv(N){if(N.meta?this._compileMetaSchema(N):a.compileSchema.call(this,N),!N.validate)throw new Error("ajv implementation error");return N.validate}_compileMetaSchema(N){const H=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,N)}finally{this.opts=H}}}T.ValidationError=n.default,T.MissingRefError=o.default,e.default=T;function k(B,N,H,F="error"){for(const E in B){const M=E;M in N&&this.logger[F](`${H}: option ${E}. ${B[M]}`)}}function b(B){return B=(0,l.normalizeId)(B),this.schemas[B]||this.refs[B]}function S(){const B=this.opts.schemas;if(B)if(Array.isArray(B))this.addSchema(B);else for(const N in B)this.addSchema(B[N],N)}function x(){for(const B in this.opts.formats){const N=this.opts.formats[B];N&&this.addFormat(B,N)}}function I(B){if(Array.isArray(B)){this.addVocabulary(B);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const N in B){const H=B[N];H.keyword||(H.keyword=N),this.addKeyword(H)}}function L(){const B={...this.opts};for(const N of g)delete B[N];return B}const $={log(){},warn(){},error(){}};function O(B){if(B===!1)return $;if(B===void 0)return console;if(B.log&&B.warn&&B.error)return B;throw new Error("logger must implement log, warn and error methods")}const A=/^[a-z_$][a-z0-9_$:-]*$/i;function U(B,N){const{RULES:H}=this;if((0,u.eachItem)(B,F=>{if(H.keywords[F])throw new Error(`Keyword ${F} is already defined`);if(!A.test(F))throw new Error(`Keyword ${F} has invalid name`)}),!!N&&N.$data&&!("code"in N||"validate"in N))throw new Error('$data keyword must have "code" or "validate" function')}function Z(B,N,H){var F;const E=N?.post;if(H&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:M}=this;let D=E?M.post:M.rules.find(({type:te})=>te===H);if(D||(D={type:H,rules:[]},M.rules.push(D)),M.keywords[B]=!0,!N)return;const G={keyword:B,definition:{...N,type:(0,c.getJSONTypes)(N.type),schemaType:(0,c.getJSONTypes)(N.schemaType)}};N.before?Y.call(this,D,G,N.before):D.rules.push(G),M.all[B]=G,(F=N.implements)===null||F===void 0||F.forEach(te=>this.addKeyword(te))}function Y(B,N,H){const F=B.rules.findIndex(E=>E.keyword===H);F>=0?B.rules.splice(F,0,N):(B.rules.push(N),this.logger.warn(`rule ${H} is not defined`))}function ye(B){let{metaSchema:N}=B;N!==void 0&&(B.$data&&this.opts.$data&&(N=he(N)),B.validateSchema=this.compile(N,!0))}const X={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function he(B){return{anyOf:[B,X]}}})(Jc)),Jc}var ja={},Da={},Ua={},iy;function Cx(){if(iy)return Ua;iy=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Ua.default=e,Ua}var ln={},ly;function Tx(){if(ly)return ln;ly=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.callRef=ln.getValidate=void 0;const e=qa(),t=fr(),r=Pe(),n=an(),o=tu(),s=je(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:m,it:p}=c,{baseId:f,schemaEnv:g,validateName:v,opts:y,self:w}=p,{root:_}=g;if((m==="#"||m==="#/")&&f===_.baseId)return T();const h=o.resolveRef.call(w,_,f,m);if(h===void 0)throw new e.default(p.opts.uriResolver,f,m);if(h instanceof o.SchemaEnv)return k(h);return b(h);function T(){if(g===_)return l(c,v,g,g.$async);const S=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${S}.validate`,_,_.$async)}function k(S){const x=i(c,S);l(c,x,S,S.$async)}function b(S){const x=u.scopeValue("schema",y.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),I=u.name("valid"),L=c.subschema({schema:S,dataTypes:[],schemaPath:r.nil,topSchemaRef:x,errSchemaPath:m},I);c.mergeEvaluated(L),c.ok(I)}}};function i(c,u){const{gen:m}=c;return u.validate?m.scopeValue("validate",{ref:u.validate}):(0,r._)`${m.scopeValue("wrapper",{ref:u})}.validate`}ln.getValidate=i;function l(c,u,m,p){const{gen:f,it:g}=c,{allErrors:v,schemaEnv:y,opts:w}=g,_=w.passContext?n.default.this:r.nil;p?h():T();function h(){if(!y.$async)throw new Error("async schema referenced by sync schema");const S=f.let("valid");f.try(()=>{f.code((0,r._)`await ${(0,t.callValidateCode)(c,u,_)}`),b(u),v||f.assign(S,!0)},x=>{f.if((0,r._)`!(${x} instanceof ${g.ValidationError})`,()=>f.throw(x)),k(x),v||f.assign(S,!1)}),c.ok(S)}function T(){c.result((0,t.callValidateCode)(c,u,_),()=>b(u),()=>k(u))}function k(S){const x=(0,r._)`${S}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${x} : ${n.default.vErrors}.concat(${x})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function b(S){var x;if(!g.opts.unevaluated)return;const I=(x=m?.validate)===null||x===void 0?void 0:x.evaluated;if(g.props!==!0)if(I&&!I.dynamicProps)I.props!==void 0&&(g.props=s.mergeEvaluated.props(f,I.props,g.props));else{const L=f.var("props",(0,r._)`${S}.evaluated.props`);g.props=s.mergeEvaluated.props(f,L,g.props,r.Name)}if(g.items!==!0)if(I&&!I.dynamicItems)I.items!==void 0&&(g.items=s.mergeEvaluated.items(f,I.items,g.items));else{const L=f.var("items",(0,r._)`${S}.evaluated.items`);g.items=s.mergeEvaluated.items(f,L,g.items,r.Name)}}}return ln.callRef=l,ln.default=a,ln}var cy;function Sx(){if(cy)return Da;cy=1,Object.defineProperty(Da,"__esModule",{value:!0});const e=Cx(),t=Tx(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Da.default=r,Da}var za={},Fa={},uy;function Ix(){if(uy)return Fa;uy=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=Pe(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:a})=>(0,e.str)`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${a}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:a,data:i,schemaCode:l}=s;s.fail$data((0,e._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return Fa.default=o,Fa}var Va={},dy;function xx(){if(dy)return Va;dy=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Pe(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${a} === 0 || (${c} = ${s}/${a}, ${u}))`)}};return Va.default=r,Va}var Za={},Ba={},py;function Ex(){if(py)return Ba;py=1,Object.defineProperty(Ba,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,s;for(;o<r;)n++,s=t.charCodeAt(o++),s>=55296&&s<=56319&&o<r&&(s=t.charCodeAt(o),(s&64512)===56320&&o++);return n}return Ba.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Ba}var fy;function $x(){if(fy)return Za;fy=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=Pe(),t=je(),r=Ex(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:a}){const i=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:a,data:i,schemaCode:l,it:c}=s,u=a==="maxLength"?e.operators.GT:e.operators.LT,m=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${m} ${u} ${l}`)}};return Za.default=o,Za}var Ha={},hy;function Rx(){if(hy)return Ha;hy=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=fr(),t=je(),r=Pe(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,r.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,r._)`{pattern: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:m}=s,p=m.opts.unicodeRegExp?"u":"";if(l){const{regExp:f}=m.opts.code,g=f.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(a,f),v=a.let("valid");a.try(()=>a.assign(v,(0,r._)`${g}(${u}, ${p}).test(${i})`),()=>a.assign(v,!1)),s.fail$data((0,r._)`!${v}`)}else{const f=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${f}.test(${i})`)}}};return Ha.default=o,Ha}var Ja={},my;function Px(){if(my)return Ja;my=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=Pe(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${i} ${a}`)}};return Ja.default=r,Ja}var Ga={},gy;function Nx(){if(gy)return Ga;gy=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=fr(),t=Pe(),r=je(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:m}=s,{opts:p}=m;if(!u&&i.length===0)return;const f=i.length>=p.loopRequired;if(m.allErrors?g():v(),p.strictRequired){const _=s.parentSchema.properties,{definedProperties:h}=s.it;for(const T of i)if(_?.[T]===void 0&&!h.has(T)){const k=m.schemaEnv.baseId+m.errSchemaPath,b=`required property "${T}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(m,b,m.opts.strictRequired)}}function g(){if(f||u)s.block$data(t.nil,y);else for(const _ of i)(0,e.checkReportMissingProp)(s,_)}function v(){const _=a.let("missing");if(f||u){const h=a.let("valid",!0);s.block$data(h,()=>w(_,h)),s.ok(h)}else a.if((0,e.checkMissingProp)(s,i,_)),(0,e.reportMissingProp)(s,_),a.else()}function y(){a.forOf("prop",l,_=>{s.setParams({missingProperty:_}),a.if((0,e.noPropertyInData)(a,c,_,p.ownProperties),()=>s.error())})}function w(_,h){s.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(h,(0,e.propertyInData)(a,c,_,p.ownProperties)),a.if((0,t.not)(h),()=>{s.error(),a.break()})},t.nil)}}};return Ga.default=o,Ga}var Wa={},yy;function Mx(){if(yy)return Wa;yy=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=Pe(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${i} ${a}`)}};return Wa.default=r,Wa}var Ka={},Ya={},_y;function ou(){if(_y)return Ya;_y=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=Gg();return e.code='require("ajv/dist/runtime/equal").default',Ya.default=e,Ya}var vy;function Ox(){if(vy)return Ka;vy=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Pa(),t=Pe(),r=je(),n=ou(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,t._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:m,schemaCode:p,it:f}=a;if(!c&&!u)return;const g=i.let("valid"),v=m.items?(0,e.getSchemaTypes)(m.items):[];a.block$data(g,y,(0,t._)`${p} === false`),a.ok(g);function y(){const T=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:T,j:k}),i.assign(g,!0),i.if((0,t._)`${T} > 1`,()=>(w()?_:h)(T,k))}function w(){return v.length>0&&!v.some(T=>T==="object"||T==="array")}function _(T,k){const b=i.name("item"),S=(0,e.checkDataTypes)(v,b,f.opts.strictNumbers,e.DataType.Wrong),x=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${T}--;`,()=>{i.let(b,(0,t._)`${l}[${T}]`),i.if(S,(0,t._)`continue`),v.length>1&&i.if((0,t._)`typeof ${b} == "string"`,(0,t._)`${b} += "_"`),i.if((0,t._)`typeof ${x}[${b}] == "number"`,()=>{i.assign(k,(0,t._)`${x}[${b}]`),a.error(),i.assign(g,!1).break()}).code((0,t._)`${x}[${b}] = ${T}`)})}function h(T,k){const b=(0,r.useFunc)(i,n.default),S=i.name("outer");i.label(S).for((0,t._)`;${T}--;`,()=>i.for((0,t._)`${k} = ${T}; ${k}--;`,()=>i.if((0,t._)`${b}(${l}[${T}], ${l}[${k}])`,()=>{a.error(),i.assign(g,!1).break(S)})))}}};return Ka.default=s,Ka}var Qa={},wy;function Ax(){if(wy)return Qa;wy=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=Pe(),t=je(),r=ou(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${i}, ${c})`):s.fail((0,e._)`${u} !== ${i}`)}};return Qa.default=o,Qa}var Xa={},by;function qx(){if(by)return Xa;by=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=Pe(),t=je(),r=ou(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:m}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=m.opts.loopEnum;let f;const g=()=>f??(f=(0,t.useFunc)(a,r.default));let v;if(p||l)v=a.let("valid"),s.block$data(v,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);v=(0,e.or)(...c.map((h,T)=>w(_,T)))}s.pass(v);function y(){a.assign(v,!1),a.forOf("v",u,_=>a.if((0,e._)`${g()}(${i}, ${_})`,()=>a.assign(v,!0).break()))}function w(_,h){const T=c[h];return typeof T=="object"&&T!==null?(0,e._)`${g()}(${i}, ${_}[${h}])`:(0,e._)`${i} === ${T}`}}};return Xa.default=o,Xa}var ky;function Lx(){if(ky)return za;ky=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Ix(),t=xx(),r=$x(),n=Rx(),o=Px(),s=Nx(),a=Mx(),i=Ox(),l=Ax(),c=qx(),u=[e.default,t.default,r.default,n.default,o.default,s.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return za.default=u,za}var ei={},lo={},Cy;function Ty(){if(Cy)return lo;Cy=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.validateAdditionalItems=void 0;const e=Pe(),t=je(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:a,it:i}=s,{items:l}=a;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,a){const{gen:i,schema:l,data:c,keyword:u,it:m}=s;m.items=!0;const p=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${p} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(m,l)){const g=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(g),()=>f(g)),s.ok(g)}function f(g){i.forRange("i",a.length,p,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},g),m.allErrors||i.if((0,e.not)(g),()=>i.break())})}}return lo.validateAdditionalItems=o,lo.default=n,lo}var ti={},co={},Sy;function Iy(){if(Sy)return co;Sy=1,Object.defineProperty(co,"__esModule",{value:!0}),co.validateTuple=void 0;const e=Pe(),t=je(),r=fr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:a,it:i}=s;if(Array.isArray(a))return o(s,"additionalItems",a);i.items=!0,!(0,t.alwaysValidSchema)(i,a)&&s.ok((0,r.validateArray)(s))}};function o(s,a,i=s.schema){const{gen:l,parentSchema:c,data:u,keyword:m,it:p}=s;v(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const f=l.name("valid"),g=l.const("len",(0,e._)`${u}.length`);i.forEach((y,w)=>{(0,t.alwaysValidSchema)(p,y)||(l.if((0,e._)`${g} > ${w}`,()=>s.subschema({keyword:m,schemaProp:w,dataProp:w},f)),s.ok(f))});function v(y){const{opts:w,errSchemaPath:_}=p,h=i.length,T=h===y.minItems&&(h===y.maxItems||y[a]===!1);if(w.strictTuples&&!T){const k=`"${m}" is ${h}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(p,k,w.strictTuples)}}}return co.validateTuple=o,co.default=n,co}var xy;function jx(){if(xy)return ti;xy=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Iy(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return ti.default=t,ti}var ri={},Ey;function Dx(){if(Ey)return ri;Ey=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=Pe(),t=je(),r=fr(),n=Ty(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return ri.default=s,ri}var ni={},$y;function Ux(){if($y)return ni;$y=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=Pe(),t=je(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:a,parentSchema:i,data:l,it:c}=o;let u,m;const{minContains:p,maxContains:f}=i;c.opts.next?(u=p===void 0?1:p,m=f):u=1;const g=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:m}),m===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(m!==void 0&&u>m){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let h=(0,e._)`${g} >= ${u}`;m!==void 0&&(h=(0,e._)`${h} && ${g} <= ${m}`),o.pass(h);return}c.items=!0;const v=s.name("valid");m===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),m!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(v,!1),y()),o.result(v,()=>o.reset());function y(){const h=s.name("_valid"),T=s.let("count",0);w(h,()=>s.if(h,()=>_(T)))}function w(h,T){s.forRange("i",0,g,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},h),T()})}function _(h){s.code((0,e._)`${h}++`),m===void 0?s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${h} > ${m}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0)))}}};return ni.default=n,ni}var su={},Ry;function zx(){return Ry||(Ry=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Pe(),r=je(),n=fr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const m=c===1?"property":"properties";return(0,t.str)`must have ${m} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:m}})=>(0,t._)`{property: ${l},
86
+ missingProperty: ${m},
87
87
  depsCount: ${c},
88
- deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const g in l){if(g==="__proto__")continue;const p=Array.isArray(l[g])?c:u;p[g]=l[g]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:g,it:p}=l;if(Object.keys(c).length===0)return;const h=u.let("missing");for(const y in c){const w=c[y];if(w.length===0)continue;const m=(0,n.propertyInData)(u,g,y,p.opts.ownProperties);l.setParams({property:y,depsCount:w.length,deps:w.join(", ")}),p.allErrors?u.if(m,()=>{for(const b of w)(0,n.checkReportMissingProp)(l,b)}):(u.if((0,t._)`${m} && (${(0,n.checkMissingProp)(l,w,h)})`),(0,n.reportMissingProp)(l,h),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:g,keyword:p,it:h}=l,y=u.name("valid");for(const w in c)(0,r.alwaysValidSchema)(h,c[w])||(u.if((0,n.propertyInData)(u,g,w,h.opts.ownProperties),()=>{const m=l.subschema({keyword:p,schemaProp:w},y);l.mergeValidEvaluated(m,y)},()=>u.var(y,!0)),l.ok(y))}e.validateSchemaDeps=i,e.default=o})(Dc)),Dc}var Za={},py;function k7(){if(py)return Za;py=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=Ne(),t=Fe(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:a,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,a))return;const c=s.name("valid");s.forIn("key",i,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return Za.default=n,Za}var Ba={},fy;function hy(){if(fy)return Ba;fy=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=or(),t=Ne(),r=Wr(),n=Fe(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,t._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:g,it:p}=a;if(!g)throw new Error("ajv implementation error");const{allErrors:h,opts:y}=p;if(p.props=!0,y.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const w=(0,e.allSchemaProperties)(c.properties),m=(0,e.allSchemaProperties)(c.patternProperties);b(),a.ok((0,t._)`${g} === ${r.default.errors}`);function b(){i.forIn("key",u,v=>{!w.length&&!m.length?C(v):i.if(_(v),()=>C(v))})}function _(v){let S;if(w.length>8){const $=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(i,$,v)}else w.length?S=(0,t.or)(...w.map($=>(0,t._)`${v} === ${$}`)):S=t.nil;return m.length&&(S=(0,t.or)(S,...m.map($=>(0,t._)`${(0,e.usePattern)(a,$)}.test(${v})`))),(0,t.not)(S)}function f(v){i.code((0,t._)`delete ${u}[${v}]`)}function C(v){if(y.removeAdditional==="all"||y.removeAdditional&&l===!1){f(v);return}if(l===!1){a.setParams({additionalProperty:v}),a.error(),h||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=i.name("valid");y.removeAdditional==="failing"?(k(v,S,!1),i.if((0,t.not)(S),()=>{a.reset(),f(v)})):(k(v,S),h||i.if((0,t.not)(S),()=>i.break()))}}function k(v,S,$){const E={keyword:"additionalProperties",dataProp:v,dataPropType:n.Type.Str};$===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(E,S)}}};return Ba.default=s,Ba}var Ha={},my;function C7(){if(my)return Ha;my=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=va(),t=or(),r=Fe(),n=hy(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const g=(0,t.allSchemaProperties)(i);for(const m of g)u.definedProperties.add(m);u.opts.unevaluated&&g.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(g),u.props));const p=g.filter(m=>!(0,r.alwaysValidSchema)(u,i[m]));if(p.length===0)return;const h=a.name("valid");for(const m of p)y(m)?w(m):(a.if((0,t.propertyInData)(a,c,m,u.opts.ownProperties)),w(m),u.allErrors||a.else().var(h,!0),a.endIf()),s.it.definedProperties.add(m),s.ok(h);function y(m){return u.opts.useDefaults&&!u.compositeRule&&i[m].default!==void 0}function w(m){s.subschema({keyword:"properties",schemaProp:m,dataProp:m},h)}}};return Ha.default=o,Ha}var Ja={},gy;function T7(){if(gy)return Ja;gy=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=or(),t=Ne(),r=Fe(),n=Fe(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:g}=u,p=(0,e.allSchemaProperties)(i),h=p.filter(C=>(0,r.alwaysValidSchema)(u,i[C]));if(p.length===0||h.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const y=g.strictSchema&&!g.allowMatchingProperties&&c.properties,w=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:m}=u;b();function b(){for(const C of p)y&&_(C),u.allErrors?f(C):(a.var(w,!0),f(C),a.if(w))}function _(C){for(const k in y)new RegExp(C).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${C} (use allowMatchingProperties)`)}function f(C){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,C)}.test(${k})`,()=>{const v=h.includes(C);v||s.subschema({keyword:"patternProperties",schemaProp:C,dataProp:k,dataPropType:n.Type.Str},w),u.opts.unevaluated&&m!==!0?a.assign((0,t._)`${m}[${k}]`,!0):!v&&!u.allErrors&&a.if((0,t.not)(w),()=>a.break())})})}}};return Ja.default=o,Ja}var Ga={},yy;function S7(){if(yy)return Ga;yy=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=Fe(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return Ga.default=t,Ga}var Wa={},_y;function I7(){if(_y)return Wa;_y=1,Object.defineProperty(Wa,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:or().validateUnion,error:{message:"must match a schema in anyOf"}};return Wa.default=t,Wa}var Ka={},vy;function x7(){if(vy)return Ka;vy=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Ne(),t=Fe(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:a,parentSchema:i,it:l}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=s.let("valid",!1),g=s.let("passing",null),p=s.name("_valid");o.setParams({passing:g}),s.block(h),o.result(u,()=>o.reset(),()=>o.error(!0));function h(){c.forEach((y,w)=>{let m;(0,t.alwaysValidSchema)(l,y)?s.var(p,!0):m=o.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},p),w>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(g,(0,e._)`[${g}, ${w}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(g,w),m&&o.mergeEvaluated(m,e.Name)})})}}};return Ka.default=n,Ka}var Ya={},wy;function E7(){if(wy)return Ya;wy=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=Fe(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const a=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(s,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return Ya.default=t,Ya}var Qa={},by;function $7(){if(by)return Qa;by=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=Ne(),t=Fe(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:a,parentSchema:i,it:l}=s;i.then===void 0&&i.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const g=a.let("valid",!0),p=a.name("_valid");if(h(),s.reset(),c&&u){const w=a.let("ifClause");s.setParams({ifClause:w}),a.if(p,y("then",w),y("else",w))}else c?a.if(p,y("then")):a.if((0,e.not)(p),y("else"));s.pass(g,()=>s.error(!0));function h(){const w=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(w)}function y(w,m){return()=>{const b=s.subschema({keyword:w},p);a.assign(g,p),s.mergeValidEvaluated(b,g),m?a.assign(m,(0,e._)`${w}`):s.setParams({ifClause:w})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return Qa.default=n,Qa}var Xa={},ky;function R7(){if(ky)return Xa;ky=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=Fe(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return Xa.default=t,Xa}var Cy;function P7(){if(Cy)return Da;Cy=1,Object.defineProperty(Da,"__esModule",{value:!0});const e=sy(),t=_7(),r=iy(),n=v7(),o=w7(),s=b7(),a=k7(),i=hy(),l=C7(),c=T7(),u=S7(),g=I7(),p=x7(),h=E7(),y=$7(),w=R7();function m(b=!1){const _=[u.default,g.default,p.default,h.default,y.default,w.default,a.default,i.default,s.default,l.default,c.default];return b?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return Da.default=m,Da}var ei={},ti={},Ty;function M7(){if(Ty)return ti;Ty=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Ne(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:g,errSchemaPath:p,schemaEnv:h,self:y}=u;if(!g.validateFormats)return;i?w():m();function w(){const b=s.scopeValue("formats",{ref:y.formats,code:g.code.formats}),_=s.const("fDef",(0,e._)`${b}[${c}]`),f=s.let("fType"),C=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(f,(0,e._)`${_}.type || "string"`).assign(C,(0,e._)`${_}.validate`),()=>s.assign(f,(0,e._)`"string"`).assign(C,_)),n.fail$data((0,e.or)(k(),v()));function k(){return g.strictSchema===!1?e.nil:(0,e._)`${c} && !${C}`}function v(){const S=h.$async?(0,e._)`(${_}.async ? await ${C}(${a}) : ${C}(${a}))`:(0,e._)`${C}(${a})`,$=(0,e._)`(typeof ${C} == "function" ? ${S} : ${C}.test(${a}))`;return(0,e._)`${C} && ${C} !== true && ${f} === ${o} && !${$}`}}function m(){const b=y.formats[l];if(!b){k();return}if(b===!0)return;const[_,f,C]=v(b);_===o&&n.pass(S());function k(){if(g.strictSchema===!1){y.logger.warn($());return}throw new Error($());function $(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function v($){const E=$ instanceof RegExp?(0,e.regexpCode)($):g.code.formats?(0,e._)`${g.code.formats}${(0,e.getProperty)(l)}`:void 0,D=s.scopeValue("formats",{key:l,ref:$,code:E});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,e._)`${D}.validate`]:["string",$,D]}function S(){if(typeof b=="object"&&!(b instanceof RegExp)&&b.async){if(!h.$async)throw new Error("async format in sync schema");return(0,e._)`await ${C}(${a})`}return typeof f=="function"?(0,e._)`${C}(${a})`:(0,e._)`${C}.test(${a})`}}}};return ti.default=r,ti}var Sy;function N7(){if(Sy)return ei;Sy=1,Object.defineProperty(ei,"__esModule",{value:!0});const t=[M7().default];return ei.default=t,ei}var In={},Iy;function O7(){return Iy||(Iy=1,Object.defineProperty(In,"__esModule",{value:!0}),In.contentVocabulary=In.metadataVocabulary=void 0,In.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],In.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),In}var xy;function A7(){if(xy)return Ta;xy=1,Object.defineProperty(Ta,"__esModule",{value:!0});const e=s7(),t=y7(),r=P7(),n=N7(),o=O7(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Ta.default=s,Ta}var ri={},es={},Ey;function q7(){if(Ey)return es;Ey=1,Object.defineProperty(es,"__esModule",{value:!0}),es.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(es.DiscrError=e={})),es}var $y;function L7(){if($y)return ri;$y=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=Ne(),t=q7(),r=qc(),n=ka(),o=Fe(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:g,it:p}=i,{oneOf:h}=g;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const y=u.propertyName;if(typeof y!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const w=l.let("valid",!1),m=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(y)}`);l.if((0,e._)`typeof ${m} == "string"`,()=>b(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:y})),i.ok(w);function b(){const C=f();l.if(!1);for(const k in C)l.elseIf((0,e._)`${m} === ${k}`),l.assign(w,_(C[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:y}),l.endIf()}function _(C){const k=l.name("valid"),v=i.subschema({keyword:"oneOf",schemaProp:C},k);return i.mergeEvaluated(v,e.Name),k}function f(){var C;const k={},v=$(g);let S=!0;for(let M=0;M<h.length;M++){let N=h[M];if(N?.$ref&&!(0,o.schemaHasRulesButRef)(N,p.self.RULES)){const L=N.$ref;if(N=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,L),N instanceof r.SchemaEnv&&(N=N.schema),N===void 0)throw new n.default(p.opts.uriResolver,p.baseId,L)}const O=(C=N?.properties)===null||C===void 0?void 0:C[y];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${y}"`);S=S&&(v||$(N)),E(O,M)}if(!S)throw new Error(`discriminator: "${y}" must be required`);return k;function $({required:M}){return Array.isArray(M)&&M.includes(y)}function E(M,N){if(M.const)D(M.const,N);else if(M.enum)for(const O of M.enum)D(O,N);else throw new Error(`discriminator: "properties/${y}" must have "const" or "enum"`)}function D(M,N){if(typeof M!="string"||M in k)throw new Error(`discriminator: "${y}" values must be unique strings`);k[M]=N}}}};return ri.default=a,ri}const j7={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var Ry;function Py(){return Ry||(Ry=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=r7(),n=A7(),o=L7(),s=j7,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(y=>this.addVocabulary(y)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const y=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(y,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=va();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Ne();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var g=Ac();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return g.default}});var p=ka();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(fa,fa.exports)),fa.exports}var U7=Py();const D7=Xi(U7);var ni={exports:{}},zc={},My;function z7(){return My||(My=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(M,N){return{validate:M,compare:N}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(p(!0),h),"iso-time":t(l(),u),"iso-date-time":t(p(),y),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:b,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:D,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:f,int32:{type:"number",validate:v},int64:{type:"number",validate:S},float:{type:"number",validate:$},double:{type:"number",validate:$},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,y),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(M){return M%4===0&&(M%100!==0||M%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(M){const N=n.exec(M);if(!N)return!1;const O=+N[1],L=+N[2],K=+N[3];return L>=1&&L<=12&&K>=1&&K<=(L===2&&r(O)?29:o[L])}function a(M,N){if(M&&N)return M>N?1:M<N?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(M){return function(O){const L=i.exec(O);if(!L)return!1;const K=+L[1],H=+L[2],le=+L[3],W=L[4],Ee=L[5]==="-"?-1:1,F=+(L[6]||0),A=+(L[7]||0);if(F>23||A>59||M&&!W)return!1;if(K<=23&&H<=59&&le<60)return!0;const B=H-A*Ee,z=K-F*Ee-(B<0?1:0);return(z===23||z===-1)&&(B===59||B===-1)&&le<61}}function c(M,N){if(!(M&&N))return;const O=new Date("2020-01-01T"+M).valueOf(),L=new Date("2020-01-01T"+N).valueOf();if(O&&L)return O-L}function u(M,N){if(!(M&&N))return;const O=i.exec(M),L=i.exec(N);if(O&&L)return M=O[1]+O[2]+O[3],N=L[1]+L[2]+L[3],M>N?1:M<N?-1:0}const g=/t|\s/i;function p(M){const N=l(M);return function(L){const K=L.split(g);return K.length===2&&s(K[0])&&N(K[1])}}function h(M,N){if(!(M&&N))return;const O=new Date(M).valueOf(),L=new Date(N).valueOf();if(O&&L)return O-L}function y(M,N){if(!(M&&N))return;const[O,L]=M.split(g),[K,H]=N.split(g),le=a(O,K);if(le!==void 0)return le||c(L,H)}const w=/\/|:/,m=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function b(M){return w.test(M)&&m.test(M)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function f(M){return _.lastIndex=0,_.test(M)}const C=-2147483648,k=2**31-1;function v(M){return Number.isInteger(M)&&M<=k&&M>=C}function S(M){return Number.isInteger(M)}function $(){return!0}const E=/[^\\]\\Z/;function D(M){if(E.test(M))return!1;try{return new RegExp(M),!0}catch{return!1}}})(zc)),zc}var Fc={},Ny;function F7(){return Ny||(Ny=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Py(),r=Ne(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:g,it:p}=i,{opts:h,self:y}=p;if(!h.validateFormats)return;const w=new t.KeywordCxt(p,y.RULES.all.format.definition,"format");w.$data?m():b();function m(){const f=l.scopeValue("formats",{ref:y.formats,code:h.code.formats}),C=l.const("fmt",(0,r._)`${f}[${w.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${C} != "object"`,(0,r._)`${C} instanceof RegExp`,(0,r._)`typeof ${C}.compare != "function"`,_(C)))}function b(){const f=w.schema,C=y.formats[f];if(!C||C===!0)return;if(typeof C!="object"||C instanceof RegExp||typeof C.compare!="function")throw new Error(`"${g}": format "${f}" does not define "compare" function`);const k=l.scopeValue("formats",{key:f,ref:C,code:h.code.formats?(0,r._)`${h.code.formats}${(0,r.getProperty)(f)}`:void 0});i.fail$data(_(k))}function _(f){return(0,r._)`${f}.compare(${c}, ${u}) ${o[g].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(Fc)),Fc}var Oy;function V7(){return Oy||(Oy=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=z7(),n=F7(),o=Ne(),s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[g,p]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],h=u.formats||r.formatNames;return l(c,h,g,p),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,g,p){var h,y;(h=(y=c.opts.code).formats)!==null&&h!==void 0||(y.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const w of u)c.addFormat(w,g[w])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(ni,ni.exports)),ni.exports}var Z7=V7();const B7=Xi(Z7);function H7(){const e=new D7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return B7(e),e}class J7{constructor(t){this._ajv=t??H7()}getValidator(t){const r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class G7{constructor(t){this._client=t}async*callToolStream(t,r=Go,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:t},r,s),i=o.getToolOutputValidator(t.name);for await(const l of a){if(l.type==="result"&&i){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new ke($e.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new ke($e.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ke){yield{type:"error",error:u};return}yield{type:"error",error:new ke($e.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function W7(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function K7(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function oi(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&oi(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&oi(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&oi(r,t)}}function Y7(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class si extends BI{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new J7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Xl,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ql,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Jl,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new G7(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=HI(this._capabilities,t)}setRequestHandler(t,r){const o=ig(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(pa(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const i=async(l,c)=>{const u=Gr(rc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new ke($e.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:g}=u.data;g.mode=g.mode??"form";const{supportsFormMode:p,supportsUrlMode:h}=Y7(this._capabilities.elicitation);if(g.mode==="form"&&!p)throw new ke($e.InvalidParams,"Client does not support form-mode elicitation requests");if(g.mode==="url"&&!h)throw new ke($e.InvalidParams,"Client does not support URL-mode elicitation requests");const y=await Promise.resolve(r(l,c));if(g.task){const _=Gr(Ho,y);if(!_.success){const f=_.error instanceof Error?_.error.message:String(_.error);throw new ke($e.InvalidParams,`Invalid task creation result: ${f}`)}return _.data}const w=Gr(nc,y);if(!w.success){const _=w.error instanceof Error?w.error.message:String(w.error);throw new ke($e.InvalidParams,`Invalid elicitation result: ${_}`)}const m=w.data,b=g.mode==="form"?g.requestedSchema:void 0;if(g.mode==="form"&&m.action==="accept"&&m.content&&b&&this._capabilities.elicitation?.form?.applyDefaults)try{oi(b,m.content)}catch{}return m};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=Gr(ec,l);if(!u.success){const m=u.error instanceof Error?u.error.message:String(u.error);throw new ke($e.InvalidParams,`Invalid sampling request: ${m}`)}const{params:g}=u.data,p=await Promise.resolve(r(l,c));if(g.task){const m=Gr(Ho,p);if(!m.success){const b=m.error instanceof Error?m.error.message:String(m.error);throw new ke($e.InvalidParams,`Invalid task creation result: ${b}`)}return m.data}const y=g.tools||g.toolChoice?Nm:tc,w=Gr(y,p);if(!w.success){const m=w.error instanceof Error?w.error.message:String(w.error);throw new ke($e.InvalidParams,`Invalid sampling result: ${m}`)}return w.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:Ks,capabilities:this._capabilities,clientInfo:this._clientInfo}},ym,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!_C.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){W7(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&K7(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},wn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Om,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},wn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Em,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},xm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Cm,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Tm,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Sm,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},wn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},wn,r)}async callTool(t,r=Go,n){if(this.isToolTaskRequired(t.name))throw new ke($e.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new ke($e.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new ke($e.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ke?a:new ke($e.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},Rm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=dT.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:l}=n,c=async()=>{if(!a){l(null,null);return}try{const g=await o();l(null,g)}catch(g){const p=g instanceof Error?g:new Error(String(g));l(p,null)}},u=()=>{if(i){const g=this._listChangedDebounceTimers.get(t);g&&clearTimeout(g);const p=setTimeout(c,i);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Ay extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(qy(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(qy(this),r)}}function Q7(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Vc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Vc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Vc(e.cause)}`:e.message:`${e}`}function qy(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Ly=e=>{throw TypeError(e)},Zc=(e,t,r)=>t.has(e)||Ly("Cannot "+r),qe=(e,t,r)=>(Zc(e,t,"read from private field"),r?r.call(e):t.get(e)),pt=(e,t,r)=>t.has(e)?Ly("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),tt=(e,t,r,n)=>(Zc(e,t,"write to private field"),t.set(e,r),r),Rr=(e,t,r)=>(Zc(e,t,"access private method"),r),Lt,xn,eo,ai,ii,ts,to,rs,Yr,ro,no,oo,ns,sr,Bc,Hc,Jc,jy,Gc,Wc,os,Kc,Yc;class li extends EventTarget{constructor(t,r){var n,o;super(),pt(this,sr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,pt(this,Lt),pt(this,xn),pt(this,eo),pt(this,ai),pt(this,ii),pt(this,ts),pt(this,to),pt(this,rs,null),pt(this,Yr),pt(this,ro),pt(this,no,null),pt(this,oo,null),pt(this,ns,null),pt(this,Hc,async s=>{var a;qe(this,ro).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){Rr(this,sr,os).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?tt(this,eo,new URL(s.url)):tt(this,eo,void 0),c!==200){Rr(this,sr,os).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Rr(this,sr,os).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(qe(this,Lt)===this.CLOSED)return;tt(this,Lt,this.OPEN);const g=new Event("open");if((a=qe(this,ns))==null||a.call(this,g),this.dispatchEvent(g),typeof i!="object"||!i||!("getReader"in i)){Rr(this,sr,os).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,h=i.getReader();let y=!0;do{const{done:w,value:m}=await h.read();m&&qe(this,ro).feed(p.decode(m,{stream:!w})),w&&(y=!1,qe(this,ro).reset(),Rr(this,sr,Kc).call(this))}while(y)}),pt(this,Jc,s=>{tt(this,Yr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Rr(this,sr,Kc).call(this,Vc(s))}),pt(this,Gc,s=>{typeof s.id=="string"&&tt(this,rs,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:qe(this,eo)?qe(this,eo).origin:qe(this,xn).origin,lastEventId:s.id||""});qe(this,oo)&&(!s.event||s.event==="message")&&qe(this,oo).call(this,a),this.dispatchEvent(a)}),pt(this,Wc,s=>{tt(this,ts,s)}),pt(this,Yc,()=>{tt(this,to,void 0),qe(this,Lt)===this.CONNECTING&&Rr(this,sr,Bc).call(this)});try{if(t instanceof URL)tt(this,xn,t);else if(typeof t=="string")tt(this,xn,new URL(t,X7()));else throw new Error("Invalid URL")}catch{throw Q7("An invalid or illegal string was specified")}tt(this,ro,Gp({onEvent:qe(this,Gc),onRetry:qe(this,Wc)})),tt(this,Lt,this.CONNECTING),tt(this,ts,3e3),tt(this,ii,(n=r?.fetch)!=null?n:globalThis.fetch),tt(this,ai,(o=r?.withCredentials)!=null?o:!1),Rr(this,sr,Bc).call(this)}get readyState(){return qe(this,Lt)}get url(){return qe(this,xn).href}get withCredentials(){return qe(this,ai)}get onerror(){return qe(this,no)}set onerror(t){tt(this,no,t)}get onmessage(){return qe(this,oo)}set onmessage(t){tt(this,oo,t)}get onopen(){return qe(this,ns)}set onopen(t){tt(this,ns,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){qe(this,to)&&clearTimeout(qe(this,to)),qe(this,Lt)!==this.CLOSED&&(qe(this,Yr)&&qe(this,Yr).abort(),tt(this,Lt,this.CLOSED),tt(this,Yr,void 0))}}Lt=new WeakMap,xn=new WeakMap,eo=new WeakMap,ai=new WeakMap,ii=new WeakMap,ts=new WeakMap,to=new WeakMap,rs=new WeakMap,Yr=new WeakMap,ro=new WeakMap,no=new WeakMap,oo=new WeakMap,ns=new WeakMap,sr=new WeakSet,Bc=function(){tt(this,Lt,this.CONNECTING),tt(this,Yr,new AbortController),qe(this,ii)(qe(this,xn),Rr(this,sr,jy).call(this)).then(qe(this,Hc)).catch(qe(this,Jc))},Hc=new WeakMap,Jc=new WeakMap,jy=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...qe(this,rs)?{"Last-Event-ID":qe(this,rs)}:void 0},cache:"no-store",signal:(e=qe(this,Yr))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Gc=new WeakMap,Wc=new WeakMap,os=function(e,t){var r;qe(this,Lt)!==this.CLOSED&&tt(this,Lt,this.CLOSED);const n=new Ay("error",{code:t,message:e});(r=qe(this,no))==null||r.call(this,n),this.dispatchEvent(n)},Kc=function(e,t){var r;if(qe(this,Lt)===this.CLOSED)return;tt(this,Lt,this.CONNECTING);const n=new Ay("error",{code:t,message:e});(r=qe(this,no))==null||r.call(this,n),this.dispatchEvent(n),tt(this,to,setTimeout(qe(this,Yc),qe(this,ts)))},Yc=new WeakMap,li.CONNECTING=0,li.OPEN=1,li.CLOSED=2;function X7(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class ex extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Qc{constructor(t,r){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=dm(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Wt("No auth provider");let t;try{t=await bn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Wt;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=Ws(this._requestInit?.headers);return new Headers({...t,...r})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new li(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await t(o,{...s,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=sa(i);this._resourceMetadataUrl=l,this._scope=c}return i}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new ex(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let a;try{a=vn.parse(JSON.parse(s.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new Wt("No auth provider");if(await bn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Wt("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=sa(o);if(this._resourceMetadataUrl=a,this._scope=i,await bn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Wt;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}const tx="mcp";class Uy{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._socket=new WebSocket(this._url,tx),this._socket.onerror=n=>{const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),this.onerror?.(o)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let o;try{o=vn.parse(JSON.parse(n.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(o)}})}async close(){this._socket?.close()}send(t){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(t)),r()})}}const so=ar;(function(e,t){const r=ar,n=ar,o=e();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ci,-118057+3521*-35+-2099*-233);const rx=()=>{const e=ar,t=ar,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[t(394)]=t(414),r.ktWqD=function(a,i){return a!==i},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let s=859*2+-3*-1039+-4835*1;for(;;){switch(o[s++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},nx=(e,t,r)=>{const n=ar,o=ar,s={};s.eOzBp=function(i,l){return i!==l},s.ooaJk="undefined",s[n(402)]=function(i,l){return i===l},s[n(421)]="function";const a=s;a[o(389)](typeof window,a.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&a.pTvSc(typeof e[o(423)],a[n(421)])&&e.postMessage(t,r)};class Dy{constructor(t){this._port=t}async[so(401)](){const t=so,r=so;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=vn.parse(n.data.message);(o=this.onmessage)==null||o.call(this,i,n[a(412)][a(428)])}catch(i){const l=new Error("MessageChannel failed to parse message: "+i);(s=this[a(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,a=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,a)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,s){return o instanceof s},cDUwk:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=ar,l=ar;try{const c={};c[i(404)]=r?.[i(404)];const u={};u[i(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[i(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(a=this.onerror)==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=so,o=so;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class ox extends Dy{constructor(t,r=rx()){const n=so,o={lSpBh:function(a,i,l,c){return a(i,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](nx,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function ci(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return ci=function(){return e},ci()}function ar(e,t){const r=ci();return ar=function(n,o){return n=n-(17227+1*-16844),r[n]},ar(e,t)}(function(e,t){const r=Je,n=Je,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ui,-411935*1+228107+208149*2);const sx=async(e,t,r)=>{var n;const o=Je,s=Je,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let g={};switch(c){case i.VRyiJ:g=await t.listTools(u);break;case i.VkPYu:g=await t.callTool(u);break;case i.fgMSD:g=await t.listResources(u);break;case i[s(466)]:g=await t.listResourceTemplates(u);break;case i.sthgI:g=await t[o(455)](u);break;case s(486):g=await t.subscribeResource(u);break;case o(410):g=await t.unsubscribeResource(u);break;case i[s(461)]:g=await t[s(414)](u);break;case i[o(412)]:g=await t[o(491)](u);break;case i[o(436)]:g=await t[o(478)]();break;case i.kkNqg:g=await t.complete(u);break;case o(464):g=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=g,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},ax=async(e,t,r)=>{var n;const o=Je,s=Je,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let g={};switch(c){case"roots/list":const h={};h.method=c,h[s(446)]=u,g=await t[o(469)](h,qm);break;case"sampling/createMessage":const y={};y[o(481)]=c,y[o(446)]=u,g=await t.request(y,tc);break;case i[o(487)]:const w={};w.method=c,w[s(446)]=u,g=await t.request(w,nc);break;case i.ypHTC:const m={};m.method=c,g=await t.request(m,wn);break}const p={};return p.result=g,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),g};function Je(e,t){const r=ui();return Je=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Je(e,t)}const ix=(e,t)=>{const r=Je,n=Je,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,g,p;const h=n,y=r,{id:w,method:m}=a;try{o[h(451)](m,o.DhPFX)?await s.call(e,a,i):await o[y(474)](sx,e,t,a)}catch(b){const{code:_,message:f,data:C}=b;try{if(_){const k={};k[y(485)]=_,k[h(422)]=f,k.data=C;const v={};v[y(448)]=k,v.jsonrpc=o[h(417)],v.id=w,await((l=e?.transport)==null?void 0:l[y(460)](v))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,b)}catch(k){(p=(g=e?.transport)==null?void 0:g.onerror)==null||p.call(g,k)}}}},lx=(e,t)=>{const r=Je,n=Je,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:g,params:p}=a;if(g!==s[c(476)]&&(s.QWYMz(g,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(h){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,h)}}},cx=(e,t)=>async r=>{var n,o,s,a,i;const l=Je,c=Je,u={TJhyV:function(g,p,h,y){return g(p,h,y)},MMNTY:l(465)};try{return await u.TJhyV(ax,e,t,r)}catch(g){const{code:p,message:h,data:y}=g;try{if(p){const w={};w.code=p,w[l(422)]=h,w[c(419)]=y;const m={};m[l(448)]=w,m[l(424)]=u.MMNTY,m.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](m))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,g)}catch(w){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,w)}}},ux=(e,t)=>async r=>{var n,o,s;const a=Je,i=Je,l={};l.xmcLM=function(p,h){return p!==h},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:g}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||g?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function ui(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return ui=function(){return e},ui()}const dx=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Je,u=Je,g={};g.kSvAZ=c(465);const p=g;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(h){const{code:y,message:w,data:m}=h;try{if(y){const b={};b.code=y,b.message=w,b.data=m;const _={};_.error=b,_[u(424)]=p.kSvAZ,_.id=r.id,await((o=e?.transport)==null?void 0:o.send(_))}else(a=(s=e?.transport)==null?void 0:s[c(480)])==null||a.call(s,h)}catch(b){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,b)}}},Xc=()=>{const e=Je,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Je;if(c){const g=[];for(const p of r)try{g.push(p(l,c))}catch{}for(const p of g)if(t.rgPZO(p,null))return p}else for(const g of r)try{t[u(427)](g,l)}catch{}},o=l=>{const c=Je,u=Je;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Je,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=Je;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},px=e=>{const t=Je,r=Je,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](Xc);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(489)](Xc);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=a,e.clearRequestListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n.jsmFN(Xc);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},fx=(e,{beforeInit:t,afterInit:r}={})=>{const n=Je,o=Je,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(px,e),e[o(438)](i=>{const l=n;e.originalOnResponse[l(440)](e,i)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](i=>{const l=o,{method:c}=i,u=a[l(483)](c);s[l(467)](typeof u,"function")&&u(i)})},hx=Pr;(function(e,t){const r=Pr,n=Pr,o=e();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(di,995159+-6*-266138+-1619768);const mx=()=>{const e=Pr,t=Pr,r={};r.svuxn=function(o,s){return o&s},r.ZUPdr=function(o,s){return o===s},r[e(227)]=function(o,s){return o===s},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const s=e,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?a:n[s(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},gx=e=>{const t=Pr,r=Pr,n=new Uint8Array(e);return crypto[t(221)](n),Array[r(218)](n,o=>o[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},Qr={};Qr[hx(211)]=mx,Qr.randomBytes=gx;function Pr(e,t){const r=di();return Pr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},Pr(e,t)}function di(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return di=function(){return e},di()}function Mr(e,t){const r=pi();return Mr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Mr(e,t)}const ir=Mr,ss=Mr;(function(e,t){const r=Mr,n=Mr,o=e();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(pi,-4*308317+753182*2+658196);const yx=(e,t)=>{const r=Mr,n=Mr,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[r(283)](ix,e,t),lx(e,t);const s=o[n(283)](cx,t,e),a=o[n(294)](dx,t,e),i=o[r(277)](ux,t,e);t.addRequestListener(s),t.addResponseListener(a),t[n(287)](i),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(a),t[c(252)](i)}},eu=(e,t,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,l){return a(i,l)}},o=()=>{var a;n.QhPqi(r,Qc)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Mr(295)])==null||i.close()})),n.Qalmc(yx,e,t)},s={};s.afterInit=o,n.Qalmc(fx,t,s)},zy=(e,t=Qr[ir(299)]())=>{const r=ir,n=ir,o={RVabx:function(u,g,p){return u(g,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const a=s,i={};i["sse-session-id"]=t;const l={};l.headers=i,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,g){const p=r,h=r,y=new Headers(g?.[p(268)]||{});Object.entries(a).forEach(([m,b])=>{y.set(m,b)});const w={...g};return w.headers=y,o[h(279)](fetch,u,w)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},Fy=(e,t=Qr[ir(299)]())=>{const r=ss,n=ir,o={};o[r(271)]="include";const s=o,a={};a["stream-session-id"]=t;const i={};i[n(268)]=a,i.credentials=s[r(271)];const l={};l.requestInit=i;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},tu=async(e,t,r)=>{const n=ir,o=ir,s={rRtFD:function(i){return i()},ToRAF:function(i,l){return i instanceof l}},a=s[n(276)](r);try{return await e[o(260)](a),a}catch(i){if(s[n(275)](i,Wt)){const l=await t();return await a[n(257)](l),await tu(e,t,r)}else throw i}},Vy=(e,t)=>{const r=ss,n=ss,o={};o[r(267)]=function(a,i){return a in i},o.timcZ="waitForOAuthCode",o[r(253)]=function(a,i){return a===i},o.ufiEQ=r(285),o[n(250)]=r(293);const s=o;if(s.oGmBG(s[r(258)],e))return e[n(278)];if(s[n(253)](typeof t,s.ufiEQ))return t;throw new Error(s.daYBw)};function pi(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return pi=function(){return e},pi()}const _x=async e=>{const t=ss,r=ir,n={GKDjq:function(E,D,M){return E(D,M)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(E){return E()},kdowC:function(E,D,M,N){return E(D,M,N)},KkViY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:g}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const h=p,y=i||Qr[r(299)](),w=n[t(289)](zy,a,y);if(c){const E={...w.requestInit,...c};E[r(268)]={...w[r(280)][t(268)],...c.headers},h.requestInit=E}else h.requestInit=w[t(280)];if(u){const E={...w[t(270)],...u};h.eventSourceInit=E}else h.eventSourceInit=w[t(270)];const m={};m[t(254)]=!0;const b={};b.roots=m,b[t(298)]={},b[r(303)]={};const _=b,f={};f.name=n[r(261)],f[t(288)]=n.mcbiU;const C={};C[t(251)]=_;const k=new si(f,C),v=()=>new Qc(new URL(s),h);let S=n[t(282)](v);if(l){const E=Vy(l,g);S=await n[t(263)](tu,k,E,v)}else await k.connect(S);eu(k,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const $={};return $.transport=S,$.sessionId=S[r(286)],$},vx=async e=>{const t=ss,r=ir,n={wfHUn:function(E,D,M){return E(D,M)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(E){return E()},PdsSn:function(E,D,M,N){return E(D,M,N)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:g}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const h=p,y=i||Qr.randomUUID(),w=n[r(272)](Fy,a,y);if(c){const E={...w[t(280)],...c};E.headers={...w.requestInit[t(268)],...c.headers},h.requestInit=E}else h[r(280)]=w[r(280)];const m={};m[r(254)]=!0;const b={};b.roots=m,b[t(298)]={},b[t(303)]={};const _=b,f={};f.name=n[t(262)],f.version=n.omKPe;const C={};C.capabilities=_;const k=new si(f,C),v=()=>new aa(new URL(s),h);let S=n.rSiEq(v);if(l){const E=n[t(272)](Vy,l,g);S=await n[t(296)](tu,k,E,v)}else await k[t(260)](S);n.PdsSn(eu,k,o,S);const $={};return $.transport=S,$[r(286)]=S[r(286)],$},wx=async e=>{const t=ir,r=ir,n={eZwNI:function(b,_,f,C){return b(_,f,C)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,g={};g.name="mcp-socket-proxy-client",g.version=r(248);const p={};p[r(251)]=u;const h=new si(g,p),y=i||Qr[r(299)](),w=new Uy(new URL(s+"?sessionId="+y+r(265)+a));await h.connect(w),n[t(259)](eu,h,o,w);const m={};return m.transport=w,m[r(286)]=y,m},Xr=lr,as=lr;(function(e,t){const r=lr,n=lr,o=e();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(fi,1297719+-42747*-22+-1289197);function lr(e,t){const r=fi();return lr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},lr(e,t)}const bx=()=>Qr.randomBytes(-8746+-382*-23);class bE{constructor(t){const r=lr,n=lr,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:a,redirectCallback:i,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||o.HbwOh(bx),this._redirectCallback=i||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=lr,c=lr,u={};u[l(198)]="GET";const g=await fetch(t,u);!g.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+g[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const h=await p.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,h.code)}async[Xr(191)](t,r){const n=Xr,o={};o.xAOmI="POST";const s=o,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(t,{method:s.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=lr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[Xr(206)]}get[as(190)](){return this._clientMetadata}[Xr(213)](){return this[Xr(197)]}[as(218)](){return this[as(200)]}[Xr(194)](t){this._clientInformation=t}tokens(){return this[as(210)]}saveTokens(t){const r=as;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[Xr(212)](){const t=Xr,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function fi(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return fi=function(){return e},fi()}(function(e,t){for(var r=mi,n=mi,o=e();;)try{var s=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(hi,262*-2438+1346066*-1+2*1373311);function hi(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return hi=function(){return e},hi()}function mi(e,t){var r=hi();return mi=function(n,o){n=n-287;var s=r[n];return s},mi(e,t)}class kx{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new si(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:a,onError:i}=t;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:o};let g;return await(async()=>{const{transport:h,sessionId:y}=s==="sse"?await _x(u):s==="socket"?await wx(u):await vx(u);h.onerror=async w=>{i?.(w)},g={transport:h,sessionId:y}})(),g}const l=new URL(r);let c;if(s==="channel"&&(c=new ox(r),await this.client.connect(c)),s==="sse"){const u=zy(n,o);c=new Qc(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Uy(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=Fy(n,o);c=new aa(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,Go,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(rc,t)}onCreateMessage(t){this.client.setRequestHandler(ec,t)}onListRoots(t){this.client.setRequestHandler(Am,t)}onToolListChanged(t){this.client.setNotificationHandler(Xl,t)}onPromptListChanged(t){this.client.setNotificationHandler(Ql,t)}onResourceListChanged(t){this.client.setNotificationHandler(Jl,t)}onResourceUpdated(t){this.client.setNotificationHandler(Im,t)}onLoggingMessage(t){this.client.setNotificationHandler(Mm,t)}async onPagehide(t){t.persisted||(Cx(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const Cx=e=>e instanceof aa,Zy=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const a=async(i,l)=>e.callTool({name:n,arguments:i},{signal:l?.abortSignal});t[n]=gf({description:o,inputSchema:Zn({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function Tx(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
88
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const m in l){if(m==="__proto__")continue;const p=Array.isArray(l[m])?c:u;p[m]=l[m]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:m,it:p}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const g in c){const v=c[g];if(v.length===0)continue;const y=(0,n.propertyInData)(u,m,g,p.opts.ownProperties);l.setParams({property:g,depsCount:v.length,deps:v.join(", ")}),p.allErrors?u.if(y,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${y} && (${(0,n.checkMissingProp)(l,v,f)})`),(0,n.reportMissingProp)(l,f),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:m,keyword:p,it:f}=l,g=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(f,c[v])||(u.if((0,n.propertyInData)(u,m,v,f.opts.ownProperties),()=>{const y=l.subschema({keyword:p,schemaProp:v},g);l.mergeValidEvaluated(y,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=i,e.default=o})(su)),su}var oi={},Py;function Fx(){if(Py)return oi;Py=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=Pe(),t=je(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:a,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,a))return;const c=s.name("valid");s.forIn("key",i,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return oi.default=n,oi}var si={},Ny;function My(){if(Ny)return si;Ny=1,Object.defineProperty(si,"__esModule",{value:!0});const e=fr(),t=Pe(),r=an(),n=je(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,t._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:m,it:p}=a;if(!m)throw new Error("ajv implementation error");const{allErrors:f,opts:g}=p;if(p.props=!0,g.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const v=(0,e.allSchemaProperties)(c.properties),y=(0,e.allSchemaProperties)(c.patternProperties);w(),a.ok((0,t._)`${m} === ${r.default.errors}`);function w(){i.forIn("key",u,b=>{!v.length&&!y.length?T(b):i.if(_(b),()=>T(b))})}function _(b){let S;if(v.length>8){const x=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(i,x,b)}else v.length?S=(0,t.or)(...v.map(x=>(0,t._)`${b} === ${x}`)):S=t.nil;return y.length&&(S=(0,t.or)(S,...y.map(x=>(0,t._)`${(0,e.usePattern)(a,x)}.test(${b})`))),(0,t.not)(S)}function h(b){i.code((0,t._)`delete ${u}[${b}]`)}function T(b){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){h(b);return}if(l===!1){a.setParams({additionalProperty:b}),a.error(),f||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=i.name("valid");g.removeAdditional==="failing"?(k(b,S,!1),i.if((0,t.not)(S),()=>{a.reset(),h(b)})):(k(b,S),f||i.if((0,t.not)(S),()=>i.break()))}}function k(b,S,x){const I={keyword:"additionalProperties",dataProp:b,dataPropType:n.Type.Str};x===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,S)}}};return si.default=s,si}var ai={},Oy;function Vx(){if(Oy)return ai;Oy=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=Ma(),t=fr(),r=je(),n=My(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const m=(0,t.allSchemaProperties)(i);for(const y of m)u.definedProperties.add(y);u.opts.unevaluated&&m.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(m),u.props));const p=m.filter(y=>!(0,r.alwaysValidSchema)(u,i[y]));if(p.length===0)return;const f=a.name("valid");for(const y of p)g(y)?v(y):(a.if((0,t.propertyInData)(a,c,y,u.opts.ownProperties)),v(y),u.allErrors||a.else().var(f,!0),a.endIf()),s.it.definedProperties.add(y),s.ok(f);function g(y){return u.opts.useDefaults&&!u.compositeRule&&i[y].default!==void 0}function v(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return ai.default=o,ai}var ii={},Ay;function Zx(){if(Ay)return ii;Ay=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=fr(),t=Pe(),r=je(),n=je(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:m}=u,p=(0,e.allSchemaProperties)(i),f=p.filter(T=>(0,r.alwaysValidSchema)(u,i[T]));if(p.length===0||f.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const g=m.strictSchema&&!m.allowMatchingProperties&&c.properties,v=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:y}=u;w();function w(){for(const T of p)g&&_(T),u.allErrors?h(T):(a.var(v,!0),h(T),a.if(v))}function _(T){for(const k in g)new RegExp(T).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${T} (use allowMatchingProperties)`)}function h(T){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,T)}.test(${k})`,()=>{const b=f.includes(T);b||s.subschema({keyword:"patternProperties",schemaProp:T,dataProp:k,dataPropType:n.Type.Str},v),u.opts.unevaluated&&y!==!0?a.assign((0,t._)`${y}[${k}]`,!0):!b&&!u.allErrors&&a.if((0,t.not)(v),()=>a.break())})})}}};return ii.default=o,ii}var li={},qy;function Bx(){if(qy)return li;qy=1,Object.defineProperty(li,"__esModule",{value:!0});const e=je(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return li.default=t,li}var ci={},Ly;function Hx(){if(Ly)return ci;Ly=1,Object.defineProperty(ci,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fr().validateUnion,error:{message:"must match a schema in anyOf"}};return ci.default=t,ci}var ui={},jy;function Jx(){if(jy)return ui;jy=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=Pe(),t=je(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:a,parentSchema:i,it:l}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=s.let("valid",!1),m=s.let("passing",null),p=s.name("_valid");o.setParams({passing:m}),s.block(f),o.result(u,()=>o.reset(),()=>o.error(!0));function f(){c.forEach((g,v)=>{let y;(0,t.alwaysValidSchema)(l,g)?s.var(p,!0):y=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},p),v>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(m,(0,e._)`[${m}, ${v}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(m,v),y&&o.mergeEvaluated(y,e.Name)})})}}};return ui.default=n,ui}var di={},Dy;function Gx(){if(Dy)return di;Dy=1,Object.defineProperty(di,"__esModule",{value:!0});const e=je(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const a=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(s,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return di.default=t,di}var pi={},Uy;function Wx(){if(Uy)return pi;Uy=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Pe(),t=je(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:a,parentSchema:i,it:l}=s;i.then===void 0&&i.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const m=a.let("valid",!0),p=a.name("_valid");if(f(),s.reset(),c&&u){const v=a.let("ifClause");s.setParams({ifClause:v}),a.if(p,g("then",v),g("else",v))}else c?a.if(p,g("then")):a.if((0,e.not)(p),g("else"));s.pass(m,()=>s.error(!0));function f(){const v=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(v)}function g(v,y){return()=>{const w=s.subschema({keyword:v},p);a.assign(m,p),s.mergeValidEvaluated(w,m),y?a.assign(y,(0,e._)`${v}`):s.setParams({ifClause:v})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return pi.default=n,pi}var fi={},zy;function Kx(){if(zy)return fi;zy=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=je(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return fi.default=t,fi}var Fy;function Yx(){if(Fy)return ei;Fy=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Ty(),t=jx(),r=Iy(),n=Dx(),o=Ux(),s=zx(),a=Fx(),i=My(),l=Vx(),c=Zx(),u=Bx(),m=Hx(),p=Jx(),f=Gx(),g=Wx(),v=Kx();function y(w=!1){const _=[u.default,m.default,p.default,f.default,g.default,v.default,a.default,i.default,s.default,l.default,c.default];return w?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return ei.default=y,ei}var hi={},mi={},Vy;function Qx(){if(Vy)return mi;Vy=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Pe(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:m,errSchemaPath:p,schemaEnv:f,self:g}=u;if(!m.validateFormats)return;i?v():y();function v(){const w=s.scopeValue("formats",{ref:g.formats,code:m.code.formats}),_=s.const("fDef",(0,e._)`${w}[${c}]`),h=s.let("fType"),T=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(h,(0,e._)`${_}.type || "string"`).assign(T,(0,e._)`${_}.validate`),()=>s.assign(h,(0,e._)`"string"`).assign(T,_)),n.fail$data((0,e.or)(k(),b()));function k(){return m.strictSchema===!1?e.nil:(0,e._)`${c} && !${T}`}function b(){const S=f.$async?(0,e._)`(${_}.async ? await ${T}(${a}) : ${T}(${a}))`:(0,e._)`${T}(${a})`,x=(0,e._)`(typeof ${T} == "function" ? ${S} : ${T}.test(${a}))`;return(0,e._)`${T} && ${T} !== true && ${h} === ${o} && !${x}`}}function y(){const w=g.formats[l];if(!w){k();return}if(w===!0)return;const[_,h,T]=b(w);_===o&&n.pass(S());function k(){if(m.strictSchema===!1){g.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function b(x){const I=x instanceof RegExp?(0,e.regexpCode)(x):m.code.formats?(0,e._)`${m.code.formats}${(0,e.getProperty)(l)}`:void 0,L=s.scopeValue("formats",{key:l,ref:x,code:I});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,e._)`${L}.validate`]:["string",x,L]}function S(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!f.$async)throw new Error("async format in sync schema");return(0,e._)`await ${T}(${a})`}return typeof h=="function"?(0,e._)`${T}(${a})`:(0,e._)`${T}.test(${a})`}}}};return mi.default=r,mi}var Zy;function Xx(){if(Zy)return hi;Zy=1,Object.defineProperty(hi,"__esModule",{value:!0});const t=[Qx().default];return hi.default=t,hi}var qn={},By;function e7(){return By||(By=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.contentVocabulary=qn.metadataVocabulary=void 0,qn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],qn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),qn}var Hy;function t7(){if(Hy)return ja;Hy=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=Sx(),t=Lx(),r=Yx(),n=Xx(),o=e7(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ja.default=s,ja}var gi={},ls={},Jy;function r7(){if(Jy)return ls;Jy=1,Object.defineProperty(ls,"__esModule",{value:!0}),ls.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(ls.DiscrError=e={})),ls}var Gy;function n7(){if(Gy)return gi;Gy=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=Pe(),t=r7(),r=tu(),n=qa(),o=je(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:m,it:p}=i,{oneOf:f}=m;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const g=u.propertyName;if(typeof g!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!f)throw new Error("discriminator: requires oneOf keyword");const v=l.let("valid",!1),y=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(g)}`);l.if((0,e._)`typeof ${y} == "string"`,()=>w(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:g})),i.ok(v);function w(){const T=h();l.if(!1);for(const k in T)l.elseIf((0,e._)`${y} === ${k}`),l.assign(v,_(T[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:g}),l.endIf()}function _(T){const k=l.name("valid"),b=i.subschema({keyword:"oneOf",schemaProp:T},k);return i.mergeEvaluated(b,e.Name),k}function h(){var T;const k={},b=x(m);let S=!0;for(let $=0;$<f.length;$++){let O=f[$];if(O?.$ref&&!(0,o.schemaHasRulesButRef)(O,p.self.RULES)){const U=O.$ref;if(O=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,U),O instanceof r.SchemaEnv&&(O=O.schema),O===void 0)throw new n.default(p.opts.uriResolver,p.baseId,U)}const A=(T=O?.properties)===null||T===void 0?void 0:T[g];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${g}"`);S=S&&(b||x(O)),I(A,$)}if(!S)throw new Error(`discriminator: "${g}" must be required`);return k;function x({required:$}){return Array.isArray($)&&$.includes(g)}function I($,O){if($.const)L($.const,O);else if($.enum)for(const A of $.enum)L(A,O);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function L($,O){if(typeof $!="string"||$ in k)throw new Error(`discriminator: "${g}" values must be unique strings`);k[$]=O}}}};return gi.default=a,gi}const o7={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};var Wy;function Ky(){return Wy||(Wy=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=kx(),n=t7(),o=n7(),s=o7,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(g=>this.addVocabulary(g)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const g=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(g,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=Ma();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Pe();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var m=eu();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return m.default}});var p=qa();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(xa,xa.exports)),xa.exports}var s7=Ky();const a7=yl(s7);var yi={exports:{}},au={},Yy;function i7(){return Yy||(Yy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t($,O){return{validate:$,compare:O}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(p(!0),f),"iso-time":t(l(),u),"iso-date-time":t(p(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:L,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:h,int32:{type:"number",validate:b},int64:{type:"number",validate:S},float:{type:"number",validate:x},double:{type:"number",validate:x},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r($){return $%4===0&&($%100!==0||$%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s($){const O=n.exec($);if(!O)return!1;const A=+O[1],U=+O[2],Z=+O[3];return U>=1&&U<=12&&Z>=1&&Z<=(U===2&&r(A)?29:o[U])}function a($,O){if($&&O)return $>O?1:$<O?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l($){return function(A){const U=i.exec(A);if(!U)return!1;const Z=+U[1],Y=+U[2],ye=+U[3],X=U[4],he=U[5]==="-"?-1:1,B=+(U[6]||0),N=+(U[7]||0);if(B>23||N>59||$&&!X)return!1;if(Z<=23&&Y<=59&&ye<60)return!0;const H=Y-N*he,F=Z-B*he-(H<0?1:0);return(F===23||F===-1)&&(H===59||H===-1)&&ye<61}}function c($,O){if(!($&&O))return;const A=new Date("2020-01-01T"+$).valueOf(),U=new Date("2020-01-01T"+O).valueOf();if(A&&U)return A-U}function u($,O){if(!($&&O))return;const A=i.exec($),U=i.exec(O);if(A&&U)return $=A[1]+A[2]+A[3],O=U[1]+U[2]+U[3],$>O?1:$<O?-1:0}const m=/t|\s/i;function p($){const O=l($);return function(U){const Z=U.split(m);return Z.length===2&&s(Z[0])&&O(Z[1])}}function f($,O){if(!($&&O))return;const A=new Date($).valueOf(),U=new Date(O).valueOf();if(A&&U)return A-U}function g($,O){if(!($&&O))return;const[A,U]=$.split(m),[Z,Y]=O.split(m),ye=a(A,Z);if(ye!==void 0)return ye||c(U,Y)}const v=/\/|:/,y=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function w($){return v.test($)&&y.test($)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function h($){return _.lastIndex=0,_.test($)}const T=-2147483648,k=2**31-1;function b($){return Number.isInteger($)&&$<=k&&$>=T}function S($){return Number.isInteger($)}function x(){return!0}const I=/[^\\]\\Z/;function L($){if(I.test($))return!1;try{return new RegExp($),!0}catch{return!1}}})(au)),au}var iu={},Qy;function l7(){return Qy||(Qy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Ky(),r=Pe(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:m,it:p}=i,{opts:f,self:g}=p;if(!f.validateFormats)return;const v=new t.KeywordCxt(p,g.RULES.all.format.definition,"format");v.$data?y():w();function y(){const h=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),T=l.const("fmt",(0,r._)`${h}[${v.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${T} != "object"`,(0,r._)`${T} instanceof RegExp`,(0,r._)`typeof ${T}.compare != "function"`,_(T)))}function w(){const h=v.schema,T=g.formats[h];if(!T||T===!0)return;if(typeof T!="object"||T instanceof RegExp||typeof T.compare!="function")throw new Error(`"${m}": format "${h}" does not define "compare" function`);const k=l.scopeValue("formats",{key:h,ref:T,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(h)}`:void 0});i.fail$data(_(k))}function _(h){return(0,r._)`${h}.compare(${c}, ${u}) ${o[m].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(iu)),iu}var Xy;function c7(){return Xy||(Xy=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=i7(),n=l7(),o=Pe(),s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[m,p]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],f=u.formats||r.formatNames;return l(c,f,m,p),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,m,p){var f,g;(f=(g=c.opts.code).formats)!==null&&f!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const v of u)c.addFormat(v,m[v])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(yi,yi.exports)),yi.exports}var u7=c7();const d7=yl(u7);function p7(){const e=new a7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return d7(e),e}class f7{constructor(t){this._ajv=t??p7()}getValidator(t){const r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class h7{constructor(t){this._client=t}async*callToolStream(t,r=rs,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:t},r,s),i=o.getToolOutputValidator(t.name);for await(const l of a){if(l.type==="result"&&i){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new ke(Ee.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new ke(Ee.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ke){yield{type:"error",error:u};return}yield{type:"error",error:new ke(Ee.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function m7(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function g7(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function _i(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&_i(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&_i(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&_i(r,t)}}function y7(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class vi extends dx{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new f7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",yc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",gc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",dc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new h7(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=px(this._capabilities,t)}setRequestHandler(t,r){const o=Ig(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ia(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const i=async(l,c)=>{const u=sn(wc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new ke(Ee.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:m}=u.data;m.mode=m.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=y7(this._capabilities.elicitation);if(m.mode==="form"&&!p)throw new ke(Ee.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!f)throw new ke(Ee.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(m.task){const _=sn(es,g);if(!_.success){const h=_.error instanceof Error?_.error.message:String(_.error);throw new ke(Ee.InvalidParams,`Invalid task creation result: ${h}`)}return _.data}const v=sn(bc,g);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new ke(Ee.InvalidParams,`Invalid elicitation result: ${_}`)}const y=v.data,w=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&y.action==="accept"&&y.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{_i(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=sn(_c,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new ke(Ee.InvalidParams,`Invalid sampling request: ${y}`)}const{params:m}=u.data,p=await Promise.resolve(r(l,c));if(m.task){const y=sn(es,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new ke(Ee.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const g=m.tools||m.toolChoice?Qm:vc,v=sn(g,p);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new ke(Ee.InvalidParams,`Invalid sampling result: ${y}`)}return v.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:ua,capabilities:this._capabilities,clientInfo:this._clientInfo}},qm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!OC.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){m7(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&g7(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Rn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Xm,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Rn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Jm,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Hm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Fm,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Vm,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Zm,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Rn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Rn,r)}async callTool(t,r=rs,n){if(this.isToolTaskRequired(t.name))throw new ke(Ee.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new ke(Ee.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new ke(Ee.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ke?a:new ke(Ee.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},Wm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=xT.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:l}=n,c=async()=>{if(!a){l(null,null);return}try{const m=await o();l(null,m)}catch(m){const p=m instanceof Error?m:new Error(String(m));l(p,null)}},u=()=>{if(i){const m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);const p=setTimeout(c,i);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class e_ extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(t_(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(t_(this),r)}}function _7(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function lu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(lu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${lu(e.cause)}`:e.message:`${e}`}function t_(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var r_=e=>{throw TypeError(e)},cu=(e,t,r)=>t.has(e)||r_("Cannot "+r),qe=(e,t,r)=>(cu(e,t,"read from private field"),r?r.call(e):t.get(e)),vt=(e,t,r)=>t.has(e)?r_("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),tt=(e,t,r,n)=>(cu(e,t,"write to private field"),t.set(e,r),r),Ur=(e,t,r)=>(cu(e,t,"access private method"),r),Vt,Ln,uo,wi,bi,cs,po,us,cn,fo,ho,mo,ds,hr,uu,du,pu,n_,fu,hu,ps,mu,gu;class ki extends EventTarget{constructor(t,r){var n,o;super(),vt(this,hr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,vt(this,Vt),vt(this,Ln),vt(this,uo),vt(this,wi),vt(this,bi),vt(this,cs),vt(this,po),vt(this,us,null),vt(this,cn),vt(this,fo),vt(this,ho,null),vt(this,mo,null),vt(this,ds,null),vt(this,du,async s=>{var a;qe(this,fo).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){Ur(this,hr,ps).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?tt(this,uo,new URL(s.url)):tt(this,uo,void 0),c!==200){Ur(this,hr,ps).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Ur(this,hr,ps).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(qe(this,Vt)===this.CLOSED)return;tt(this,Vt,this.OPEN);const m=new Event("open");if((a=qe(this,ds))==null||a.call(this,m),this.dispatchEvent(m),typeof i!="object"||!i||!("getReader"in i)){Ur(this,hr,ps).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,f=i.getReader();let g=!0;do{const{done:v,value:y}=await f.read();y&&qe(this,fo).feed(p.decode(y,{stream:!v})),v&&(g=!1,qe(this,fo).reset(),Ur(this,hr,mu).call(this))}while(g)}),vt(this,pu,s=>{tt(this,cn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Ur(this,hr,mu).call(this,lu(s))}),vt(this,fu,s=>{typeof s.id=="string"&&tt(this,us,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:qe(this,uo)?qe(this,uo).origin:qe(this,Ln).origin,lastEventId:s.id||""});qe(this,mo)&&(!s.event||s.event==="message")&&qe(this,mo).call(this,a),this.dispatchEvent(a)}),vt(this,hu,s=>{tt(this,cs,s)}),vt(this,gu,()=>{tt(this,po,void 0),qe(this,Vt)===this.CONNECTING&&Ur(this,hr,uu).call(this)});try{if(t instanceof URL)tt(this,Ln,t);else if(typeof t=="string")tt(this,Ln,new URL(t,v7()));else throw new Error("Invalid URL")}catch{throw _7("An invalid or illegal string was specified")}tt(this,fo,pf({onEvent:qe(this,fu),onRetry:qe(this,hu)})),tt(this,Vt,this.CONNECTING),tt(this,cs,3e3),tt(this,bi,(n=r?.fetch)!=null?n:globalThis.fetch),tt(this,wi,(o=r?.withCredentials)!=null?o:!1),Ur(this,hr,uu).call(this)}get readyState(){return qe(this,Vt)}get url(){return qe(this,Ln).href}get withCredentials(){return qe(this,wi)}get onerror(){return qe(this,ho)}set onerror(t){tt(this,ho,t)}get onmessage(){return qe(this,mo)}set onmessage(t){tt(this,mo,t)}get onopen(){return qe(this,ds)}set onopen(t){tt(this,ds,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){qe(this,po)&&clearTimeout(qe(this,po)),qe(this,Vt)!==this.CLOSED&&(qe(this,cn)&&qe(this,cn).abort(),tt(this,Vt,this.CLOSED),tt(this,cn,void 0))}}Vt=new WeakMap,Ln=new WeakMap,uo=new WeakMap,wi=new WeakMap,bi=new WeakMap,cs=new WeakMap,po=new WeakMap,us=new WeakMap,cn=new WeakMap,fo=new WeakMap,ho=new WeakMap,mo=new WeakMap,ds=new WeakMap,hr=new WeakSet,uu=function(){tt(this,Vt,this.CONNECTING),tt(this,cn,new AbortController),qe(this,bi)(qe(this,Ln),Ur(this,hr,n_).call(this)).then(qe(this,du)).catch(qe(this,pu))},du=new WeakMap,pu=new WeakMap,n_=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...qe(this,us)?{"Last-Event-ID":qe(this,us)}:void 0},cache:"no-store",signal:(e=qe(this,cn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},fu=new WeakMap,hu=new WeakMap,ps=function(e,t){var r;qe(this,Vt)!==this.CLOSED&&tt(this,Vt,this.CLOSED);const n=new e_("error",{code:t,message:e});(r=qe(this,ho))==null||r.call(this,n),this.dispatchEvent(n)},mu=function(e,t){var r;if(qe(this,Vt)===this.CLOSED)return;tt(this,Vt,this.CONNECTING);const n=new e_("error",{code:t,message:e});(r=qe(this,ho))==null||r.call(this,n),this.dispatchEvent(n),tt(this,po,setTimeout(qe(this,gu),qe(this,cs)))},gu=new WeakMap,ki.CONNECTING=0,ki.OPEN=1,ki.CLOSED=2;function v7(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class w7 extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class yu{constructor(t,r){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Rm(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new rr("No auth provider");let t;try{t=await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new rr;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=ca(this._requestInit?.headers);return new Headers({...t,...r})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new ki(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await t(o,{...s,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=va(i);this._resourceMetadataUrl=l,this._scope=c}return i}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new w7(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let a;try{a=$n.parse(JSON.parse(s.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new rr("No auth provider");if(await Pn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=va(o);if(this._resourceMetadataUrl=a,this._scope=i,await Pn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}const b7="mcp";class o_{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._socket=new WebSocket(this._url,b7),this._socket.onerror=n=>{const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),this.onerror?.(o)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let o;try{o=$n.parse(JSON.parse(n.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(o)}})}async close(){this._socket?.close()}send(t){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(t)),r()})}}const go=mr;(function(e,t){const r=mr,n=mr,o=e();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ci,-118057+3521*-35+-2099*-233);const k7=()=>{const e=mr,t=mr,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[t(394)]=t(414),r.ktWqD=function(a,i){return a!==i},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let s=859*2+-3*-1039+-4835*1;for(;;){switch(o[s++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},C7=(e,t,r)=>{const n=mr,o=mr,s={};s.eOzBp=function(i,l){return i!==l},s.ooaJk="undefined",s[n(402)]=function(i,l){return i===l},s[n(421)]="function";const a=s;a[o(389)](typeof window,a.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&a.pTvSc(typeof e[o(423)],a[n(421)])&&e.postMessage(t,r)};class s_{constructor(t){this._port=t}async[go(401)](){const t=go,r=go;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=$n.parse(n.data.message);(o=this.onmessage)==null||o.call(this,i,n[a(412)][a(428)])}catch(i){const l=new Error("MessageChannel failed to parse message: "+i);(s=this[a(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,a=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,a)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,s){return o instanceof s},cDUwk:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=mr,l=mr;try{const c={};c[i(404)]=r?.[i(404)];const u={};u[i(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[i(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(a=this.onerror)==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=go,o=go;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class T7 extends s_{constructor(t,r=k7()){const n=go,o={lSpBh:function(a,i,l,c){return a(i,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](C7,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function Ci(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return Ci=function(){return e},Ci()}function mr(e,t){const r=Ci();return mr=function(n,o){return n=n-(17227+1*-16844),r[n]},mr(e,t)}(function(e,t){const r=Be,n=Be,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ti,-411935*1+228107+208149*2);const S7=async(e,t,r)=>{var n;const o=Be,s=Be,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let m={};switch(c){case i.VRyiJ:m=await t.listTools(u);break;case i.VkPYu:m=await t.callTool(u);break;case i.fgMSD:m=await t.listResources(u);break;case i[s(466)]:m=await t.listResourceTemplates(u);break;case i.sthgI:m=await t[o(455)](u);break;case s(486):m=await t.subscribeResource(u);break;case o(410):m=await t.unsubscribeResource(u);break;case i[s(461)]:m=await t[s(414)](u);break;case i[o(412)]:m=await t[o(491)](u);break;case i[o(436)]:m=await t[o(478)]();break;case i.kkNqg:m=await t.complete(u);break;case o(464):m=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=m,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},I7=async(e,t,r)=>{var n;const o=Be,s=Be,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let m={};switch(c){case"roots/list":const f={};f.method=c,f[s(446)]=u,m=await t[o(469)](f,t2);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,m=await t.request(g,vc);break;case i[o(487)]:const v={};v.method=c,v[s(446)]=u,m=await t.request(v,bc);break;case i.ypHTC:const y={};y.method=c,m=await t.request(y,Rn);break}const p={};return p.result=m,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),m};function Be(e,t){const r=Ti();return Be=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Be(e,t)}const x7=(e,t)=>{const r=Be,n=Be,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,m,p;const f=n,g=r,{id:v,method:y}=a;try{o[f(451)](y,o.DhPFX)?await s.call(e,a,i):await o[g(474)](S7,e,t,a)}catch(w){const{code:_,message:h,data:T}=w;try{if(_){const k={};k[g(485)]=_,k[f(422)]=h,k.data=T;const b={};b[g(448)]=k,b.jsonrpc=o[f(417)],b.id=v,await((l=e?.transport)==null?void 0:l[g(460)](b))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(k){(p=(m=e?.transport)==null?void 0:m.onerror)==null||p.call(m,k)}}}},E7=(e,t)=>{const r=Be,n=Be,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:m,params:p}=a;if(m!==s[c(476)]&&(s.QWYMz(m,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(f){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,f)}}},$7=(e,t)=>async r=>{var n,o,s,a,i;const l=Be,c=Be,u={TJhyV:function(m,p,f,g){return m(p,f,g)},MMNTY:l(465)};try{return await u.TJhyV(I7,e,t,r)}catch(m){const{code:p,message:f,data:g}=m;try{if(p){const v={};v.code=p,v[l(422)]=f,v[c(419)]=g;const y={};y[l(448)]=v,y[l(424)]=u.MMNTY,y.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](y))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,m)}catch(v){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,v)}}},R7=(e,t)=>async r=>{var n,o,s;const a=Be,i=Be,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:m}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||m?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function Ti(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return Ti=function(){return e},Ti()}const P7=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Be,u=Be,m={};m.kSvAZ=c(465);const p=m;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(f){const{code:g,message:v,data:y}=f;try{if(g){const w={};w.code=g,w.message=v,w.data=y;const _={};_.error=w,_[u(424)]=p.kSvAZ,_.id=r.id,await((o=e?.transport)==null?void 0:o.send(_))}else(a=(s=e?.transport)==null?void 0:s[c(480)])==null||a.call(s,f)}catch(w){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,w)}}},_u=()=>{const e=Be,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Be;if(c){const m=[];for(const p of r)try{m.push(p(l,c))}catch{}for(const p of m)if(t.rgPZO(p,null))return p}else for(const m of r)try{t[u(427)](m,l)}catch{}},o=l=>{const c=Be,u=Be;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Be,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=Be;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},N7=e=>{const t=Be,r=Be,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](_u);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(489)](_u);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=a,e.clearRequestListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n.jsmFN(_u);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},M7=(e,{beforeInit:t,afterInit:r}={})=>{const n=Be,o=Be,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(N7,e),e[o(438)](i=>{const l=n;e.originalOnResponse[l(440)](e,i)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](i=>{const l=o,{method:c}=i,u=a[l(483)](c);s[l(467)](typeof u,"function")&&u(i)})},O7=zr;(function(e,t){const r=zr,n=zr,o=e();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Si,995159+-6*-266138+-1619768);const A7=()=>{const e=zr,t=zr,r={};r.svuxn=function(o,s){return o&s},r.ZUPdr=function(o,s){return o===s},r[e(227)]=function(o,s){return o===s},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const s=e,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?a:n[s(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},q7=e=>{const t=zr,r=zr,n=new Uint8Array(e);return crypto[t(221)](n),Array[r(218)](n,o=>o[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},un={};un[O7(211)]=A7,un.randomBytes=q7;function zr(e,t){const r=Si();return zr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},zr(e,t)}function Si(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Si=function(){return e},Si()}function Fr(e,t){const r=Ii();return Fr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Fr(e,t)}const gr=Fr,fs=Fr;(function(e,t){const r=Fr,n=Fr,o=e();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ii,-4*308317+753182*2+658196);const L7=(e,t)=>{const r=Fr,n=Fr,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[r(283)](x7,e,t),E7(e,t);const s=o[n(283)]($7,t,e),a=o[n(294)](P7,t,e),i=o[r(277)](R7,t,e);t.addRequestListener(s),t.addResponseListener(a),t[n(287)](i),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(a),t[c(252)](i)}},vu=(e,t,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,l){return a(i,l)}},o=()=>{var a;n.QhPqi(r,yu)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Fr(295)])==null||i.close()})),n.Qalmc(L7,e,t)},s={};s.afterInit=o,n.Qalmc(M7,t,s)},a_=(e,t=un[gr(299)]())=>{const r=gr,n=gr,o={RVabx:function(u,m,p){return u(m,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const a=s,i={};i["sse-session-id"]=t;const l={};l.headers=i,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,m){const p=r,f=r,g=new Headers(m?.[p(268)]||{});Object.entries(a).forEach(([y,w])=>{g.set(y,w)});const v={...m};return v.headers=g,o[f(279)](fetch,u,v)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},i_=(e,t=un[gr(299)]())=>{const r=fs,n=gr,o={};o[r(271)]="include";const s=o,a={};a["stream-session-id"]=t;const i={};i[n(268)]=a,i.credentials=s[r(271)];const l={};l.requestInit=i;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},wu=async(e,t,r)=>{const n=gr,o=gr,s={rRtFD:function(i){return i()},ToRAF:function(i,l){return i instanceof l}},a=s[n(276)](r);try{return await e[o(260)](a),a}catch(i){if(s[n(275)](i,rr)){const l=await t();return await a[n(257)](l),await wu(e,t,r)}else throw i}},l_=(e,t)=>{const r=fs,n=fs,o={};o[r(267)]=function(a,i){return a in i},o.timcZ="waitForOAuthCode",o[r(253)]=function(a,i){return a===i},o.ufiEQ=r(285),o[n(250)]=r(293);const s=o;if(s.oGmBG(s[r(258)],e))return e[n(278)];if(s[n(253)](typeof t,s.ufiEQ))return t;throw new Error(s.daYBw)};function Ii(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return Ii=function(){return e},Ii()}const j7=async e=>{const t=fs,r=gr,n={GKDjq:function(I,L,$){return I(L,$)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(I){return I()},kdowC:function(I,L,$,O){return I(L,$,O)},KkViY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:m}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const f=p,g=i||un[r(299)](),v=n[t(289)](a_,a,g);if(c){const I={...v.requestInit,...c};I[r(268)]={...v[r(280)][t(268)],...c.headers},f.requestInit=I}else f.requestInit=v[t(280)];if(u){const I={...v[t(270)],...u};f.eventSourceInit=I}else f.eventSourceInit=v[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const _=w,h={};h.name=n[r(261)],h[t(288)]=n.mcbiU;const T={};T[t(251)]=_;const k=new vi(h,T),b=()=>new yu(new URL(s),f);let S=n[t(282)](b);if(l){const I=l_(l,m);S=await n[t(263)](wu,k,I,b)}else await k.connect(S);vu(k,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const x={};return x.transport=S,x.sessionId=S[r(286)],x},D7=async e=>{const t=fs,r=gr,n={wfHUn:function(I,L,$){return I(L,$)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(I){return I()},PdsSn:function(I,L,$,O){return I(L,$,O)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:m}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const f=p,g=i||un.randomUUID(),v=n[r(272)](i_,a,g);if(c){const I={...v[t(280)],...c};I.headers={...v.requestInit[t(268)],...c.headers},f.requestInit=I}else f[r(280)]=v[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const _=w,h={};h.name=n[t(262)],h.version=n.omKPe;const T={};T.capabilities=_;const k=new vi(h,T),b=()=>new wa(new URL(s),f);let S=n.rSiEq(b);if(l){const I=n[t(272)](l_,l,m);S=await n[t(296)](wu,k,I,b)}else await k[t(260)](S);n.PdsSn(vu,k,o,S);const x={};return x.transport=S,x[r(286)]=S[r(286)],x},U7=async e=>{const t=gr,r=gr,n={eZwNI:function(w,_,h,T){return w(_,h,T)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,m={};m.name="mcp-socket-proxy-client",m.version=r(248);const p={};p[r(251)]=u;const f=new vi(m,p),g=i||un[r(299)](),v=new o_(new URL(s+"?sessionId="+g+r(265)+a));await f.connect(v),n[t(259)](vu,f,o,v);const y={};return y.transport=v,y[r(286)]=g,y},dn=yr,hs=yr;(function(e,t){const r=yr,n=yr,o=e();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(xi,1297719+-42747*-22+-1289197);function yr(e,t){const r=xi();return yr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},yr(e,t)}const z7=()=>un.randomBytes(-8746+-382*-23);class FE{constructor(t){const r=yr,n=yr,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:a,redirectCallback:i,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||o.HbwOh(z7),this._redirectCallback=i||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=yr,c=yr,u={};u[l(198)]="GET";const m=await fetch(t,u);!m.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+m[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const f=await p.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,f.code)}async[dn(191)](t,r){const n=dn,o={};o.xAOmI="POST";const s=o,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(t,{method:s.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=yr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[dn(206)]}get[hs(190)](){return this._clientMetadata}[dn(213)](){return this[dn(197)]}[hs(218)](){return this[hs(200)]}[dn(194)](t){this._clientInformation=t}tokens(){return this[hs(210)]}saveTokens(t){const r=hs;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[dn(212)](){const t=dn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function xi(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return xi=function(){return e},xi()}(function(e,t){for(var r=$i,n=$i,o=e();;)try{var s=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ei,262*-2438+1346066*-1+2*1373311);function Ei(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Ei=function(){return e},Ei()}function $i(e,t){var r=Ei();return $i=function(n,o){n=n-287;var s=r[n];return s},$i(e,t)}class F7{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new vi(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:a,onError:i}=t;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:o};let m;return await(async()=>{const{transport:f,sessionId:g}=s==="sse"?await j7(u):s==="socket"?await U7(u):await D7(u);f.onerror=async v=>{i?.(v)},m={transport:f,sessionId:g}})(),m}const l=new URL(r);let c;if(s==="channel"&&(c=new T7(r),await this.client.connect(c)),s==="sse"){const u=a_(n,o);c=new yu(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new o_(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=i_(n,o);c=new wa(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,rs,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(wc,t)}onCreateMessage(t){this.client.setRequestHandler(_c,t)}onListRoots(t){this.client.setRequestHandler(e2,t)}onToolListChanged(t){this.client.setNotificationHandler(yc,t)}onPromptListChanged(t){this.client.setNotificationHandler(gc,t)}onResourceListChanged(t){this.client.setNotificationHandler(dc,t)}onResourceUpdated(t){this.client.setNotificationHandler(Bm,t)}onLoggingMessage(t){this.client.setNotificationHandler(Ym,t)}async onPagehide(t){t.persisted||(V7(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const V7=e=>e instanceof wa,c_=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const a=async(i,l)=>e.callTool({name:n,arguments:i},{signal:l?.abortSignal});t[n]=Of({description:o,inputSchema:Xn({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function Z7(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
89
89
 
90
90
  # 工具调用
91
91
 
@@ -119,23 +119,23 @@ Error message: ${k2(r)}`,cause:r}),this[V2]=!0,this.value=t}static isInstance(t)
119
119
  `,r+=`- 必须严格按照 XML 格式调用工具
120
120
  `,r+=`- arguments 必须是有效的 JSON 格式
121
121
  `,r+=`- 如果不需要调用工具,直接给出最终答案即可
122
- `,r}function By(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,a=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:a}}catch{}return null}const Sx={openai:f2,deepseek:ag};class Ix{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=Sx[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?r=new aa(new URL(t.url)):"type"in t&&t.type==="extension"?r=new FI(t.sessionId):"transport"in t?r=t.transport:r=t,t.useAISdkClient??!1){const o=await gC({transport:r});return o.__transport__=r,o}else{const o=new kx({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof ia||r&&r instanceof Dy)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await Zy(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={}){const r=Object.values(this.mcpTools).reduce((n,o)=>({...n,...o}),{});return Object.assign(r,t),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(t,r,n){const o=Tx(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
123
- ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,a=s.execute||s.call;return typeof a!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},g=i[0]?.role==="system"?i:[u,...i];return t===Il?this._chatReActStream(g,s,l,n,o):this._chatReActNonStream(g,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(s<n)a.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return o.push(...a),o}async _chatReActNonStream(t,r,n,o,s){let a=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(i,l,u),{tools:h,...y}=s,m=(await O0({model:this.llm(n),messages:p,...y})).text,b={role:"assistant",content:m};l.push(b),a.push(b);const _=By(m,r);if(!_)return this.responseMessages=a,{text:m,response:{messages:a}};const f=await this._executeReActToolCall(_.toolName,_.arguments,r),v={role:"user",content:`<tool_response>
124
- ${f.success?JSON.stringify(f.result):`工具执行失败 - ${f.error}`}
125
- </tool_response>`};l.push(v),a.push(v)}return this.responseMessages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(t,r,n,o,s){const a=this,i=this.llm(n);let l,c;const u=new Promise((p,h)=>{l=p,c=h});return{fullStream:new ReadableStream({async start(p){let h=[...t];const y=t[0]?.role==="system"?t[0]:null,w=y?t.slice(1):[...t];let m=0,b="";const _=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;m<o;){m++;const f=a._buildMessagesForModel(y,w,_),{tools:C,...k}=s;delete k.system,delete k.onFinish;const v=await Il({...k,model:i,messages:f});let S="";for await(const H of v.fullStream)H.type==="text-delta"?(S+=H.text||"",p.enqueue({type:"text-delta",text:H.text})):H.type==="text-start"?p.enqueue({type:"text-start"}):H.type==="text-end"||H.type==="finish-step"||H.type==="finish"||H.type==="start"||H.type==="start-step"||p.enqueue(H);b+=S;const $={role:"assistant",content:b};w.push($),h.push($);const E=By(b,r);if(!E){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}if(E.toolName==="computer"&&E.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}const D=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:D,toolName:E.toolName});const M=JSON.stringify(E.arguments,null,2);p.enqueue({type:"tool-input-delta",id:D,delta:M}),p.enqueue({type:"tool-input-end",id:D}),p.enqueue({type:"tool-call",toolCallId:D,toolName:E.toolName,input:E.arguments});const N=await a._executeReActToolCall(E.toolName,E.arguments,r);let O,L=N.result;if(N.success&&N.result&&typeof N.result=="object"&&N.result.screenshot){O=N.result.screenshot;const{screenshot:H,...le}=N.result;L=le}let K="";if(N.success){L&&Array.isArray(L.content)&&L.content.length>0&&L.content[0].text?K=L.content[0].text:K=JSON.stringify(L);let H=`<tool_response>
126
- ${K}
127
- </tool_response>`;O&&(H+=`
128
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:D,result:H});const le=O?{role:"user",content:[{type:"text",text:H},{type:"image",image:O}]}:{role:"user",content:H};w.push(le),h.push(le),b=""}else K=`工具执行失败 - ${N.error}`,p.enqueue({type:"tool-error",toolCallId:D,input:E.arguments,error:{message:K}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h})}catch(f){p.error(f),c(f)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:Cl(n),...o,tools:this._tempMergeTools(o.tools)};let a=null;if(o.message&&!o.messages)a={role:"user",content:o.message},this.responseMessages.push(a),s.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const l=o.messages[o.messages.length-1];l.role==="user"&&(a=l)}const i=t(s);return i?.response?.then(l=>{const c=l.messages?.[0];a&&c?.role!=="user"&&this.responseMessages.push(a),this.responseMessages.push(...l.messages)}),i}async chat(t){return this._chat(O0,t)}async chatStream(t){return this._chat(Il,t)}}var ao={},ru,Hy;function xx(){return Hy||(Hy=1,ru=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ru}var nu={},en={},Jy;function En(){if(Jy)return en;Jy=1;let e;const t=[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];return en.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},en.getSymbolTotalCodewords=function(n){return t[n]},en.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},en.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},en.isKanjiModeEnabled=function(){return typeof e<"u"},en.toSJIS=function(n){return e(n)},en}var ou={},Gy;function su(){return Gy||(Gy=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.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: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(ou)),ou}var au,Wy;function Ex(){if(Wy)return au;Wy=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},au=e,au}var iu,Ky;function $x(){if(Ky)return iu;Ky=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},iu=e,iu}var lu={},Yy;function Rx(){return Yy||(Yy=1,(function(e){const t=En().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),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(n){const o=[],s=e.getRowColCoords(n),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}})(lu)),lu}var cu={},Qy;function Px(){if(Qy)return cu;Qy=1;const e=En().getSymbolSize,t=7;return cu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},cu}var uu={},Xy;function Mx(){return Xy||(Xy=1,(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,c=null,u=null;for(let g=0;g<s;g++){i=l=0,c=u=null;for(let p=0;p<s;p++){let h=o.get(g,p);h===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=h,i=1),h=o.get(p,g),h===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=h,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 c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=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 r(n,o,s){switch(n){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:"+n)}}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,r(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})(uu)),uu}var gi={},e_;function t_(){if(e_)return gi;e_=1;const e=su(),t=[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],r=[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];return gi.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},gi.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},gi}var du={},is={},r_;function Nx(){if(r_)return is;r_=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),is.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},is.exp=function(n){return e[n]},is.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},is}var n_;function Ox(){return n_||(n_=1,(function(e){const t=Nx();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(n[a],o[i]);return s},e.mod=function(n,o){let s=new Uint8Array(n);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(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(du)),du}var pu,o_;function Ax(){if(o_)return pu;o_=1;const e=Ox();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=e.mod(o,this.genPoly),a=this.degree-s.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(s,a),i}return s},pu=t,pu}var fu={},hu={},mu={},s_;function a_(){return s_||(s_=1,mu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),mu}var yr={},i_;function l_(){if(i_)return yr;i_=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
129
- ]))+`;yr.KANJI=new RegExp(r,"g"),yr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),yr.BYTE=new RegExp(n,"g"),yr.NUMERIC=new RegExp(e,"g"),yr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return yr.testKanji=function(l){return o.test(l)},yr.testNumeric=function(l){return s.test(l)},yr.testAlphanumeric=function(l){return a.test(l)},yr}var c_;function $n(){return c_||(c_=1,(function(e){const t=a_(),r=l_();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 r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.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 n(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 n(s)}catch{return a}}})(hu)),hu}var u_;function qx(){return u_||(u_=1,(function(e){const t=En(),r=t_(),n=su(),o=$n(),s=a_(),a=7973,i=t.getBCHDigit(a);function l(p,h,y){for(let w=1;w<=40;w++)if(h<=e.getCapacity(w,y,p))return w}function c(p,h){return o.getCharCountIndicator(p,h)+4}function u(p,h){let y=0;return p.forEach(function(w){const m=c(w.mode,h);y+=m+w.getBitsLength()}),y}function g(p,h){for(let y=1;y<=40;y++)if(u(p,y)<=e.getCapacity(y,h,o.MIXED))return y}e.from=function(h,y){return s.isValid(h)?parseInt(h,10):y},e.getCapacity=function(h,y,w){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof w>"u"&&(w=o.BYTE);const m=t.getSymbolTotalCodewords(h),b=r.getTotalCodewordsCount(h,y),_=(m-b)*8;if(w===o.MIXED)return _;const f=_-c(w,h);switch(w){case o.NUMERIC:return Math.floor(f/10*3);case o.ALPHANUMERIC:return Math.floor(f/11*2);case o.KANJI:return Math.floor(f/13);case o.BYTE:default:return Math.floor(f/8)}},e.getBestVersionForData=function(h,y){let w;const m=n.from(y,n.M);if(Array.isArray(h)){if(h.length>1)return g(h,m);if(h.length===0)return 1;w=h[0]}else w=h;return l(w.mode,w.getLength(),m)},e.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let y=h<<12;for(;t.getBCHDigit(y)-i>=0;)y^=a<<t.getBCHDigit(y)-i;return h<<12|y}})(fu)),fu}var gu={},d_;function Lx(){if(d_)return gu;d_=1;const e=En(),t=1335,r=21522,n=e.getBCHDigit(t);return gu.getEncodedBits=function(s,a){const i=s.bit<<3|a;let l=i<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(i<<10|l)^r},gu}var yu={},_u,p_;function jx(){if(p_)return _u;p_=1;const e=$n();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,a;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),a=parseInt(s,10),n.put(a,10);const i=this.data.length-o;i>0&&(s=this.data.substr(o),a=parseInt(s,10),n.put(a,i*3+1))},_u=t,_u}var vu,f_;function Ux(){if(f_)return vu;f_=1;const e=$n(),t=["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 r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let a=t.indexOf(this.data[s])*45;a+=t.indexOf(this.data[s+1]),o.put(a,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},vu=r,vu}var wu,h_;function Dx(){if(h_)return wu;h_=1;const e=$n();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},wu=t,wu}var bu,m_;function zx(){if(m_)return bu;m_=1;const e=$n(),t=En();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
130
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},bu=r,bu}var ku={exports:{}},g_;function Fx(){return g_||(g_=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},a={};a[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,g,p,h,y,w,m;!i.empty();){l=i.pop(),c=l.value,g=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(h=p[u],y=g+h,w=a[u],m=typeof a[u]>"u",(m||w>y)&&(a[u]=y,i.push(u,y),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var b=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(b)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};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})(ku)),ku.exports}var y_;function Vx(){return y_||(y_=1,(function(e){const t=$n(),r=jx(),n=Ux(),o=Dx(),s=zx(),a=l_(),i=En(),l=Fx();function c(b){return unescape(encodeURIComponent(b)).length}function u(b,_,f){const C=[];let k;for(;(k=b.exec(f))!==null;)C.push({data:k[0],index:k.index,mode:_,length:k[0].length});return C}function g(b){const _=u(a.NUMERIC,t.NUMERIC,b),f=u(a.ALPHANUMERIC,t.ALPHANUMERIC,b);let C,k;return i.isKanjiModeEnabled()?(C=u(a.BYTE,t.BYTE,b),k=u(a.KANJI,t.KANJI,b)):(C=u(a.BYTE_KANJI,t.BYTE,b),k=[]),_.concat(f,C,k).sort(function(S,$){return S.index-$.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.length}})}function p(b,_){switch(_){case t.NUMERIC:return r.getBitsLength(b);case t.ALPHANUMERIC:return n.getBitsLength(b);case t.KANJI:return s.getBitsLength(b);case t.BYTE:return o.getBitsLength(b)}}function h(b){return b.reduce(function(_,f){const C=_.length-1>=0?_[_.length-1]:null;return C&&C.mode===f.mode?(_[_.length-1].data+=f.data,_):(_.push(f),_)},[])}function y(b){const _=[];for(let f=0;f<b.length;f++){const C=b[f];switch(C.mode){case t.NUMERIC:_.push([C,{data:C.data,mode:t.ALPHANUMERIC,length:C.length},{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.ALPHANUMERIC:_.push([C,{data:C.data,mode:t.BYTE,length:C.length}]);break;case t.KANJI:_.push([C,{data:C.data,mode:t.BYTE,length:c(C.data)}]);break;case t.BYTE:_.push([{data:C.data,mode:t.BYTE,length:c(C.data)}])}}return _}function w(b,_){const f={},C={start:{}};let k=["start"];for(let v=0;v<b.length;v++){const S=b[v],$=[];for(let E=0;E<S.length;E++){const D=S[E],M=""+v+E;$.push(M),f[M]={node:D,lastCount:0},C[M]={};for(let N=0;N<k.length;N++){const O=k[N];f[O]&&f[O].node.mode===D.mode?(C[O][M]=p(f[O].lastCount+D.length,D.mode)-p(f[O].lastCount,D.mode),f[O].lastCount+=D.length):(f[O]&&(f[O].lastCount=D.length),C[O][M]=p(D.length,D.mode)+4+t.getCharCountIndicator(D.mode,_))}}k=$}for(let v=0;v<k.length;v++)C[k[v]].end=0;return{map:C,table:f}}function m(b,_){let f;const C=t.getBestModeForData(b);if(f=t.from(_,C),f!==t.BYTE&&f.bit<C.bit)throw new Error('"'+b+'" cannot be encoded with mode '+t.toString(f)+`.
131
- Suggested mode is: `+t.toString(C));switch(f===t.KANJI&&!i.isKanjiModeEnabled()&&(f=t.BYTE),f){case t.NUMERIC:return new r(b);case t.ALPHANUMERIC:return new n(b);case t.KANJI:return new s(b);case t.BYTE:return new o(b)}}e.fromArray=function(_){return _.reduce(function(f,C){return typeof C=="string"?f.push(m(C,null)):C.data&&f.push(m(C.data,C.mode)),f},[])},e.fromString=function(_,f){const C=g(_,i.isKanjiModeEnabled()),k=y(C),v=w(k,f),S=l.find_path(v.map,"start","end"),$=[];for(let E=1;E<S.length-1;E++)$.push(v.table[S[E]].node);return e.fromArray(h($))},e.rawSplit=function(_){return e.fromArray(g(_,i.isKanjiModeEnabled()))}})(yu)),yu}var __;function Zx(){if(__)return nu;__=1;const e=En(),t=su(),r=Ex(),n=$x(),o=Rx(),s=Px(),a=Mx(),i=t_(),l=Ax(),c=qx(),u=Lx(),g=$n(),p=Vx();function h(v,S){const $=v.size,E=s.getPositions(S);for(let D=0;D<E.length;D++){const M=E[D][0],N=E[D][1];for(let O=-1;O<=7;O++)if(!(M+O<=-1||$<=M+O))for(let L=-1;L<=7;L++)N+L<=-1||$<=N+L||(O>=0&&O<=6&&(L===0||L===6)||L>=0&&L<=6&&(O===0||O===6)||O>=2&&O<=4&&L>=2&&L<=4?v.set(M+O,N+L,!0,!0):v.set(M+O,N+L,!1,!0))}}function y(v){const S=v.size;for(let $=8;$<S-8;$++){const E=$%2===0;v.set($,6,E,!0),v.set(6,$,E,!0)}}function w(v,S){const $=o.getPositions(S);for(let E=0;E<$.length;E++){const D=$[E][0],M=$[E][1];for(let N=-2;N<=2;N++)for(let O=-2;O<=2;O++)N===-2||N===2||O===-2||O===2||N===0&&O===0?v.set(D+N,M+O,!0,!0):v.set(D+N,M+O,!1,!0)}}function m(v,S){const $=v.size,E=c.getEncodedBits(S);let D,M,N;for(let O=0;O<18;O++)D=Math.floor(O/3),M=O%3+$-8-3,N=(E>>O&1)===1,v.set(D,M,N,!0),v.set(M,D,N,!0)}function b(v,S,$){const E=v.size,D=u.getEncodedBits(S,$);let M,N;for(M=0;M<15;M++)N=(D>>M&1)===1,M<6?v.set(M,8,N,!0):M<8?v.set(M+1,8,N,!0):v.set(E-15+M,8,N,!0),M<8?v.set(8,E-M-1,N,!0):M<9?v.set(8,15-M-1+1,N,!0):v.set(8,15-M-1,N,!0);v.set(E-8,8,1,!0)}function _(v,S){const $=v.size;let E=-1,D=$-1,M=7,N=0;for(let O=$-1;O>0;O-=2)for(O===6&&O--;;){for(let L=0;L<2;L++)if(!v.isReserved(D,O-L)){let K=!1;N<S.length&&(K=(S[N]>>>M&1)===1),v.set(D,O-L,K),M--,M===-1&&(N++,M=7)}if(D+=E,D<0||$<=D){D-=E,E=-E;break}}}function f(v,S,$){const E=new r;$.forEach(function(L){E.put(L.mode.bit,4),E.put(L.getLength(),g.getCharCountIndicator(L.mode,v)),L.write(E)});const D=e.getSymbolTotalCodewords(v),M=i.getTotalCodewordsCount(v,S),N=(D-M)*8;for(E.getLengthInBits()+4<=N&&E.put(0,4);E.getLengthInBits()%8!==0;)E.putBit(0);const O=(N-E.getLengthInBits())/8;for(let L=0;L<O;L++)E.put(L%2?17:236,8);return C(E,v,S)}function C(v,S,$){const E=e.getSymbolTotalCodewords(S),D=i.getTotalCodewordsCount(S,$),M=E-D,N=i.getBlocksCount(S,$),O=E%N,L=N-O,K=Math.floor(E/N),H=Math.floor(M/N),le=H+1,W=K-H,Ee=new l(W);let F=0;const A=new Array(N),B=new Array(N);let z=0;const I=new Uint8Array(v.buffer);for(let ye=0;ye<N;ye++){const Ie=ye<L?H:le;A[ye]=I.slice(F,F+Ie),B[ye]=Ee.encode(A[ye]),F+=Ie,z=Math.max(z,Ie)}const x=new Uint8Array(E);let Z=0,ee,Y;for(ee=0;ee<z;ee++)for(Y=0;Y<N;Y++)ee<A[Y].length&&(x[Z++]=A[Y][ee]);for(ee=0;ee<W;ee++)for(Y=0;Y<N;Y++)x[Z++]=B[Y][ee];return x}function k(v,S,$,E){let D;if(Array.isArray(v))D=p.fromArray(v);else if(typeof v=="string"){let K=S;if(!K){const H=p.rawSplit(v);K=c.getBestVersionForData(H,$)}D=p.fromString(v,K||40)}else throw new Error("Invalid data");const M=c.getBestVersionForData(D,$);if(!M)throw new Error("The amount of data is too big to be stored in a QR Code");if(!S)S=M;else if(S<M)throw new Error(`
122
+ `,r}function u_(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,a=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:a}}catch{}return null}const B7={openai:N2,deepseek:Sg};class H7{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=B7[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?r=new wa(new URL(t.url)):"type"in t&&t.type==="extension"?r=new lx(t.sessionId):"transport"in t?r=t.transport:r=t,t.useAISdkClient??!1){const o=await NC({transport:r});return o.__transport__=r,o}else{const o=new F7({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof ba||r&&r instanceof s_)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await c_(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={}){const r=Object.values(this.mcpTools).reduce((n,o)=>({...n,...o}),{});return Object.assign(r,t),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(t,r,n){const o=Z7(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
123
+ ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,a=s.execute||s.call;return typeof a!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},m=i[0]?.role==="system"?i:[u,...i];return t===Zl?this._chatReActStream(m,s,l,n,o):this._chatReActNonStream(m,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(s<n)a.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return o.push(...a),o}async _chatReActNonStream(t,r,n,o,s){let a=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(i,l,u),{tools:f,...g}=s,y=(await Q0({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:y};l.push(w),a.push(w);const _=u_(y,r);if(!_)return this.responseMessages=a,{text:y,response:{messages:a}};const h=await this._executeReActToolCall(_.toolName,_.arguments,r),b={role:"user",content:`<tool_response>
124
+ ${h.success?JSON.stringify(h.result):`工具执行失败 - ${h.error}`}
125
+ </tool_response>`};l.push(b),a.push(b)}return this.responseMessages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(t,r,n,o,s){const a=this,i=this.llm(n);let l,c;const u=new Promise((p,f)=>{l=p,c=f});return{fullStream:new ReadableStream({async start(p){let f=[...t];const g=t[0]?.role==="system"?t[0]:null,v=g?t.slice(1):[...t];let y=0,w="";const _=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;y<o;){y++;const h=a._buildMessagesForModel(g,v,_),{tools:T,...k}=s;delete k.system,delete k.onFinish;const b=await Zl({...k,model:i,messages:h});let S="";for await(const Y of b.fullStream)Y.type==="text-delta"?(S+=Y.text||"",p.enqueue({type:"text-delta",text:Y.text})):Y.type==="text-start"?p.enqueue({type:"text-start"}):Y.type==="text-end"||Y.type==="finish-step"||Y.type==="finish"||Y.type==="start"||Y.type==="start-step"||p.enqueue(Y);w+=S;const x={role:"assistant",content:w};v.push(x),f.push(x);const I=u_(w,r);if(!I){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f});return}if(I.toolName==="computer"&&I.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f});return}const L=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:L,toolName:I.toolName});const $=JSON.stringify(I.arguments,null,2);p.enqueue({type:"tool-input-delta",id:L,delta:$}),p.enqueue({type:"tool-input-end",id:L}),p.enqueue({type:"tool-call",toolCallId:L,toolName:I.toolName,input:I.arguments});const O=await a._executeReActToolCall(I.toolName,I.arguments,r);let A,U=O.result;if(O.success&&O.result&&typeof O.result=="object"&&O.result.screenshot){A=O.result.screenshot;const{screenshot:Y,...ye}=O.result;U=ye}let Z="";if(O.success){U&&Array.isArray(U.content)&&U.content.length>0&&U.content[0].text?Z=U.content[0].text:Z=JSON.stringify(U);let Y=`<tool_response>
126
+ ${Z}
127
+ </tool_response>`;A&&(Y+=`
128
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:L,result:Y});const ye=A?{role:"user",content:[{type:"text",text:Y},{type:"image",image:A}]}:{role:"user",content:Y};v.push(ye),f.push(ye),w=""}else Z=`工具执行失败 - ${O.error}`,p.enqueue({type:"tool-error",toolCallId:L,input:I.arguments,error:{message:Z}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f})}catch(h){p.error(h),c(h)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:zl(n),...o,tools:this._tempMergeTools(o.tools)};let a=null;if(o.message&&!o.messages)a={role:"user",content:o.message},this.responseMessages.push(a),s.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const l=o.messages[o.messages.length-1];l.role==="user"&&(a=l)}const i=t(s);return i?.response?.then(l=>{const c=l.messages?.[0];a&&c?.role!=="user"&&this.responseMessages.push(a),this.responseMessages.push(...l.messages)}),i}async chat(t){return this._chat(Q0,t)}async chatStream(t){return this._chat(Zl,t)}}var yo={},bu,d_;function J7(){return d_||(d_=1,bu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),bu}var ku={},pn={},p_;function jn(){if(p_)return pn;p_=1;let e;const t=[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];return pn.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},pn.getSymbolTotalCodewords=function(n){return t[n]},pn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},pn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},pn.isKanjiModeEnabled=function(){return typeof e<"u"},pn.toSJIS=function(n){return e(n)},pn}var Cu={},f_;function Tu(){return f_||(f_=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.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: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(Cu)),Cu}var Su,h_;function G7(){if(h_)return Su;h_=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Su=e,Su}var Iu,m_;function W7(){if(m_)return Iu;m_=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},Iu=e,Iu}var xu={},g_;function K7(){return g_||(g_=1,(function(e){const t=jn().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),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(n){const o=[],s=e.getRowColCoords(n),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}})(xu)),xu}var Eu={},y_;function Y7(){if(y_)return Eu;y_=1;const e=jn().getSymbolSize,t=7;return Eu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Eu}var $u={},__;function Q7(){return __||(__=1,(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,c=null,u=null;for(let m=0;m<s;m++){i=l=0,c=u=null;for(let p=0;p<s;p++){let f=o.get(m,p);f===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=f,i=1),f=o.get(p,m),f===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=f,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 c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=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 r(n,o,s){switch(n){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:"+n)}}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,r(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})($u)),$u}var Ri={},v_;function w_(){if(v_)return Ri;v_=1;const e=Tu(),t=[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],r=[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];return Ri.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},Ri.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},Ri}var Ru={},ms={},b_;function X7(){if(b_)return ms;b_=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),ms.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},ms.exp=function(n){return e[n]},ms.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},ms}var k_;function eE(){return k_||(k_=1,(function(e){const t=X7();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(n[a],o[i]);return s},e.mod=function(n,o){let s=new Uint8Array(n);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(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(Ru)),Ru}var Pu,C_;function tE(){if(C_)return Pu;C_=1;const e=eE();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=e.mod(o,this.genPoly),a=this.degree-s.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(s,a),i}return s},Pu=t,Pu}var Nu={},Mu={},Ou={},T_;function S_(){return T_||(T_=1,Ou.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ou}var xr={},I_;function x_(){if(I_)return xr;I_=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
129
+ ]))+`;xr.KANJI=new RegExp(r,"g"),xr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),xr.BYTE=new RegExp(n,"g"),xr.NUMERIC=new RegExp(e,"g"),xr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return xr.testKanji=function(l){return o.test(l)},xr.testNumeric=function(l){return s.test(l)},xr.testAlphanumeric=function(l){return a.test(l)},xr}var E_;function Dn(){return E_||(E_=1,(function(e){const t=S_(),r=x_();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 r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.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 n(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 n(s)}catch{return a}}})(Mu)),Mu}var $_;function rE(){return $_||($_=1,(function(e){const t=jn(),r=w_(),n=Tu(),o=Dn(),s=S_(),a=7973,i=t.getBCHDigit(a);function l(p,f,g){for(let v=1;v<=40;v++)if(f<=e.getCapacity(v,g,p))return v}function c(p,f){return o.getCharCountIndicator(p,f)+4}function u(p,f){let g=0;return p.forEach(function(v){const y=c(v.mode,f);g+=y+v.getBitsLength()}),g}function m(p,f){for(let g=1;g<=40;g++)if(u(p,g)<=e.getCapacity(g,f,o.MIXED))return g}e.from=function(f,g){return s.isValid(f)?parseInt(f,10):g},e.getCapacity=function(f,g,v){if(!s.isValid(f))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const y=t.getSymbolTotalCodewords(f),w=r.getTotalCodewordsCount(f,g),_=(y-w)*8;if(v===o.MIXED)return _;const h=_-c(v,f);switch(v){case o.NUMERIC:return Math.floor(h/10*3);case o.ALPHANUMERIC:return Math.floor(h/11*2);case o.KANJI:return Math.floor(h/13);case o.BYTE:default:return Math.floor(h/8)}},e.getBestVersionForData=function(f,g){let v;const y=n.from(g,n.M);if(Array.isArray(f)){if(f.length>1)return m(f,y);if(f.length===0)return 1;v=f[0]}else v=f;return l(v.mode,v.getLength(),y)},e.getEncodedBits=function(f){if(!s.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-i>=0;)g^=a<<t.getBCHDigit(g)-i;return f<<12|g}})(Nu)),Nu}var Au={},R_;function nE(){if(R_)return Au;R_=1;const e=jn(),t=1335,r=21522,n=e.getBCHDigit(t);return Au.getEncodedBits=function(s,a){const i=s.bit<<3|a;let l=i<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(i<<10|l)^r},Au}var qu={},Lu,P_;function oE(){if(P_)return Lu;P_=1;const e=Dn();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,a;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),a=parseInt(s,10),n.put(a,10);const i=this.data.length-o;i>0&&(s=this.data.substr(o),a=parseInt(s,10),n.put(a,i*3+1))},Lu=t,Lu}var ju,N_;function sE(){if(N_)return ju;N_=1;const e=Dn(),t=["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 r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let a=t.indexOf(this.data[s])*45;a+=t.indexOf(this.data[s+1]),o.put(a,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},ju=r,ju}var Du,M_;function aE(){if(M_)return Du;M_=1;const e=Dn();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},Du=t,Du}var Uu,O_;function iE(){if(O_)return Uu;O_=1;const e=Dn(),t=jn();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
130
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},Uu=r,Uu}var zu={exports:{}},A_;function lE(){return A_||(A_=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},a={};a[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,m,p,f,g,v,y;!i.empty();){l=i.pop(),c=l.value,m=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],g=m+f,v=a[u],y=typeof a[u]>"u",(y||v>g)&&(a[u]=g,i.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};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})(zu)),zu.exports}var q_;function cE(){return q_||(q_=1,(function(e){const t=Dn(),r=oE(),n=sE(),o=aE(),s=iE(),a=x_(),i=jn(),l=lE();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,_,h){const T=[];let k;for(;(k=w.exec(h))!==null;)T.push({data:k[0],index:k.index,mode:_,length:k[0].length});return T}function m(w){const _=u(a.NUMERIC,t.NUMERIC,w),h=u(a.ALPHANUMERIC,t.ALPHANUMERIC,w);let T,k;return i.isKanjiModeEnabled()?(T=u(a.BYTE,t.BYTE,w),k=u(a.KANJI,t.KANJI,w)):(T=u(a.BYTE_KANJI,t.BYTE,w),k=[]),_.concat(h,T,k).sort(function(S,x){return S.index-x.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.length}})}function p(w,_){switch(_){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function f(w){return w.reduce(function(_,h){const T=_.length-1>=0?_[_.length-1]:null;return T&&T.mode===h.mode?(_[_.length-1].data+=h.data,_):(_.push(h),_)},[])}function g(w){const _=[];for(let h=0;h<w.length;h++){const T=w[h];switch(T.mode){case t.NUMERIC:_.push([T,{data:T.data,mode:t.ALPHANUMERIC,length:T.length},{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.ALPHANUMERIC:_.push([T,{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.KANJI:_.push([T,{data:T.data,mode:t.BYTE,length:c(T.data)}]);break;case t.BYTE:_.push([{data:T.data,mode:t.BYTE,length:c(T.data)}])}}return _}function v(w,_){const h={},T={start:{}};let k=["start"];for(let b=0;b<w.length;b++){const S=w[b],x=[];for(let I=0;I<S.length;I++){const L=S[I],$=""+b+I;x.push($),h[$]={node:L,lastCount:0},T[$]={};for(let O=0;O<k.length;O++){const A=k[O];h[A]&&h[A].node.mode===L.mode?(T[A][$]=p(h[A].lastCount+L.length,L.mode)-p(h[A].lastCount,L.mode),h[A].lastCount+=L.length):(h[A]&&(h[A].lastCount=L.length),T[A][$]=p(L.length,L.mode)+4+t.getCharCountIndicator(L.mode,_))}}k=x}for(let b=0;b<k.length;b++)T[k[b]].end=0;return{map:T,table:h}}function y(w,_){let h;const T=t.getBestModeForData(w);if(h=t.from(_,T),h!==t.BYTE&&h.bit<T.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(h)+`.
131
+ Suggested mode is: `+t.toString(T));switch(h===t.KANJI&&!i.isKanjiModeEnabled()&&(h=t.BYTE),h){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(_){return _.reduce(function(h,T){return typeof T=="string"?h.push(y(T,null)):T.data&&h.push(y(T.data,T.mode)),h},[])},e.fromString=function(_,h){const T=m(_,i.isKanjiModeEnabled()),k=g(T),b=v(k,h),S=l.find_path(b.map,"start","end"),x=[];for(let I=1;I<S.length-1;I++)x.push(b.table[S[I]].node);return e.fromArray(f(x))},e.rawSplit=function(_){return e.fromArray(m(_,i.isKanjiModeEnabled()))}})(qu)),qu}var L_;function uE(){if(L_)return ku;L_=1;const e=jn(),t=Tu(),r=G7(),n=W7(),o=K7(),s=Y7(),a=Q7(),i=w_(),l=tE(),c=rE(),u=nE(),m=Dn(),p=cE();function f(b,S){const x=b.size,I=s.getPositions(S);for(let L=0;L<I.length;L++){const $=I[L][0],O=I[L][1];for(let A=-1;A<=7;A++)if(!($+A<=-1||x<=$+A))for(let U=-1;U<=7;U++)O+U<=-1||x<=O+U||(A>=0&&A<=6&&(U===0||U===6)||U>=0&&U<=6&&(A===0||A===6)||A>=2&&A<=4&&U>=2&&U<=4?b.set($+A,O+U,!0,!0):b.set($+A,O+U,!1,!0))}}function g(b){const S=b.size;for(let x=8;x<S-8;x++){const I=x%2===0;b.set(x,6,I,!0),b.set(6,x,I,!0)}}function v(b,S){const x=o.getPositions(S);for(let I=0;I<x.length;I++){const L=x[I][0],$=x[I][1];for(let O=-2;O<=2;O++)for(let A=-2;A<=2;A++)O===-2||O===2||A===-2||A===2||O===0&&A===0?b.set(L+O,$+A,!0,!0):b.set(L+O,$+A,!1,!0)}}function y(b,S){const x=b.size,I=c.getEncodedBits(S);let L,$,O;for(let A=0;A<18;A++)L=Math.floor(A/3),$=A%3+x-8-3,O=(I>>A&1)===1,b.set(L,$,O,!0),b.set($,L,O,!0)}function w(b,S,x){const I=b.size,L=u.getEncodedBits(S,x);let $,O;for($=0;$<15;$++)O=(L>>$&1)===1,$<6?b.set($,8,O,!0):$<8?b.set($+1,8,O,!0):b.set(I-15+$,8,O,!0),$<8?b.set(8,I-$-1,O,!0):$<9?b.set(8,15-$-1+1,O,!0):b.set(8,15-$-1,O,!0);b.set(I-8,8,1,!0)}function _(b,S){const x=b.size;let I=-1,L=x-1,$=7,O=0;for(let A=x-1;A>0;A-=2)for(A===6&&A--;;){for(let U=0;U<2;U++)if(!b.isReserved(L,A-U)){let Z=!1;O<S.length&&(Z=(S[O]>>>$&1)===1),b.set(L,A-U,Z),$--,$===-1&&(O++,$=7)}if(L+=I,L<0||x<=L){L-=I,I=-I;break}}}function h(b,S,x){const I=new r;x.forEach(function(U){I.put(U.mode.bit,4),I.put(U.getLength(),m.getCharCountIndicator(U.mode,b)),U.write(I)});const L=e.getSymbolTotalCodewords(b),$=i.getTotalCodewordsCount(b,S),O=(L-$)*8;for(I.getLengthInBits()+4<=O&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const A=(O-I.getLengthInBits())/8;for(let U=0;U<A;U++)I.put(U%2?17:236,8);return T(I,b,S)}function T(b,S,x){const I=e.getSymbolTotalCodewords(S),L=i.getTotalCodewordsCount(S,x),$=I-L,O=i.getBlocksCount(S,x),A=I%O,U=O-A,Z=Math.floor(I/O),Y=Math.floor($/O),ye=Y+1,X=Z-Y,he=new l(X);let B=0;const N=new Array(O),H=new Array(O);let F=0;const E=new Uint8Array(b.buffer);for(let se=0;se<O;se++){const Te=se<U?Y:ye;N[se]=E.slice(B,B+Te),H[se]=he.encode(N[se]),B+=Te,F=Math.max(F,Te)}const M=new Uint8Array(I);let D=0,G,te;for(G=0;G<F;G++)for(te=0;te<O;te++)G<N[te].length&&(M[D++]=N[te][G]);for(G=0;G<X;G++)for(te=0;te<O;te++)M[D++]=H[te][G];return M}function k(b,S,x,I){let L;if(Array.isArray(b))L=p.fromArray(b);else if(typeof b=="string"){let Z=S;if(!Z){const Y=p.rawSplit(b);Z=c.getBestVersionForData(Y,x)}L=p.fromString(b,Z||40)}else throw new Error("Invalid data");const $=c.getBestVersionForData(L,x);if(!$)throw new Error("The amount of data is too big to be stored in a QR Code");if(!S)S=$;else if(S<$)throw new Error(`
132
132
  The chosen QR Code version cannot contain this amount of data.
133
- Minimum version required to store current data is: `+M+`.
134
- `);const N=f(S,$,D),O=e.getSymbolSize(S),L=new n(O);return h(L,S),y(L),w(L,S),b(L,$,0),S>=7&&m(L,S),_(L,N),isNaN(E)&&(E=a.getBestMask(L,b.bind(null,L,$))),a.applyMask(E,L),b(L,$,E),{modules:L,version:S,errorCorrectionLevel:$,maskPattern:E,segments:D}}return nu.create=function(S,$){if(typeof S>"u"||S==="")throw new Error("No input text");let E=t.M,D,M;return typeof $<"u"&&(E=t.from($.errorCorrectionLevel,t.M),D=c.from($.version),M=a.from($.maskPattern),$.toSJISFunc&&e.setToSJISFunction($.toSJISFunc)),k(S,D,E,M)},nu}var Cu={},Tu={},v_;function w_(){return v_||(v_=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,g=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let h=0;h<c;h++){let y=(p*c+h)*4,w=s.color.light;if(p>=u&&h>=u&&p<c-u&&h<c-u){const m=Math.floor((p-u)/l),b=Math.floor((h-u)/l);w=g[i[m*a+b]?1:0]}n[y++]=w.r,n[y++]=w.g,n[y++]=w.b,n[y]=w.a}}})(Tu)),Tu}var b_;function Bx(){return b_||(b_=1,(function(e){const t=w_();function r(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 n(){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,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),g=c.getContext("2d"),p=g.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(g,c,u),g.putImageData(p,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",g=l.rendererOpts||{};return c.toDataURL(u,g.quality)}})(Cu)),Cu}var Su={},k_;function Hx(){if(k_)return Su;k_=1;const e=w_();function t(o,s){const a=o.a/255,i=s+'="'+o.hex+'"';return a<1?i+" "+s+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(o,s,a){let i=o+s;return typeof a<"u"&&(i+=" "+a),i}function n(o,s,a){let i="",l=0,c=!1,u=0;for(let g=0;g<o.length;g++){const p=Math.floor(g%s),h=Math.floor(g/s);!p&&!c&&(c=!0),o[g]?(u++,g>0&&p>0&&o[g-1]||(i+=c?r("M",p+a,.5+h+a):r("m",l,0),l=0,c=!1),p+1<s&&o[g+1]||(i+=r("h",u),u=0)):l++}return i}return Su.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,g=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+g+"v"+g+'H0z"/>':"",h="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',y='viewBox="0 0 '+g+" "+g+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+y+' shape-rendering="crispEdges">'+p+h+`</svg>
135
- `;return typeof i=="function"&&i(null,m),m},Su}var C_;function Jx(){if(C_)return ao;C_=1;const e=xx(),t=Zx(),r=Bx(),n=Hx();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),g=u.length,p=typeof u[g-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(g<2)throw new Error("Too few arguments provided");g===2?(c=i,i=a,a=l=void 0):g===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(g<1)throw new Error("Too few arguments provided");return g===1?(i=a,a=l=void 0):g===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(h,y){try{const w=t.create(i,l);h(s(w,a,l))}catch(w){y(w)}})}try{const h=t.create(i,l);c(null,s(h,a,l))}catch(h){c(h)}}return ao.create=t.create,ao.toCanvas=o.bind(null,r.render),ao.toDataURL=o.bind(null,r.renderToDataURL),ao.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),ao}var Gx=Jx();const T_=Xi(Gx);class S_{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,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 T_.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return T_.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const Wx={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class Kx{constructor(t,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...Wx,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
133
+ Minimum version required to store current data is: `+$+`.
134
+ `);const O=h(S,x,L),A=e.getSymbolSize(S),U=new n(A);return f(U,S),g(U),v(U,S),w(U,x,0),S>=7&&y(U,S),_(U,O),isNaN(I)&&(I=a.getBestMask(U,w.bind(null,U,x))),a.applyMask(I,U),w(U,x,I),{modules:U,version:S,errorCorrectionLevel:x,maskPattern:I,segments:L}}return ku.create=function(S,x){if(typeof S>"u"||S==="")throw new Error("No input text");let I=t.M,L,$;return typeof x<"u"&&(I=t.from(x.errorCorrectionLevel,t.M),L=c.from(x.version),$=a.from(x.maskPattern),x.toSJISFunc&&e.setToSJISFunction(x.toSJISFunc)),k(S,L,I,$)},ku}var Fu={},Vu={},j_;function D_(){return j_||(j_=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,m=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let f=0;f<c;f++){let g=(p*c+f)*4,v=s.color.light;if(p>=u&&f>=u&&p<c-u&&f<c-u){const y=Math.floor((p-u)/l),w=Math.floor((f-u)/l);v=m[i[y*a+w]?1:0]}n[g++]=v.r,n[g++]=v.g,n[g++]=v.b,n[g]=v.a}}})(Vu)),Vu}var U_;function dE(){return U_||(U_=1,(function(e){const t=D_();function r(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 n(){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,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),m=c.getContext("2d"),p=m.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(m,c,u),m.putImageData(p,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",m=l.rendererOpts||{};return c.toDataURL(u,m.quality)}})(Fu)),Fu}var Zu={},z_;function pE(){if(z_)return Zu;z_=1;const e=D_();function t(o,s){const a=o.a/255,i=s+'="'+o.hex+'"';return a<1?i+" "+s+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(o,s,a){let i=o+s;return typeof a<"u"&&(i+=" "+a),i}function n(o,s,a){let i="",l=0,c=!1,u=0;for(let m=0;m<o.length;m++){const p=Math.floor(m%s),f=Math.floor(m/s);!p&&!c&&(c=!0),o[m]?(u++,m>0&&p>0&&o[m-1]||(i+=c?r("M",p+a,.5+f+a):r("m",l,0),l=0,c=!1),p+1<s&&o[m+1]||(i+=r("h",u),u=0)):l++}return i}return Zu.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,m=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+m+"v"+m+'H0z"/>':"",f="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',g='viewBox="0 0 '+m+" "+m+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+g+' shape-rendering="crispEdges">'+p+f+`</svg>
135
+ `;return typeof i=="function"&&i(null,y),y},Zu}var F_;function fE(){if(F_)return yo;F_=1;const e=J7(),t=uE(),r=dE(),n=pE();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),m=u.length,p=typeof u[m-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(m<2)throw new Error("Too few arguments provided");m===2?(c=i,i=a,a=l=void 0):m===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(m<1)throw new Error("Too few arguments provided");return m===1?(i=a,a=l=void 0):m===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(f,g){try{const v=t.create(i,l);f(s(v,a,l))}catch(v){g(v)}})}try{const f=t.create(i,l);c(null,s(f,a,l))}catch(f){c(f)}}return yo.create=t.create,yo.toCanvas=o.bind(null,r.render),yo.toDataURL=o.bind(null,r.renderToDataURL),yo.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),yo}var hE=fE();const V_=yl(hE);class Z_{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,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 V_.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return V_.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const mE={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class gE{constructor(t,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...mE,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
136
136
  <div class="${this.opts.className}__arrow"></div>
137
137
  <div class="${this.opts.className}__inner">${t}</div>
138
- `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-a:i==="bottom"?c=r.bottom+o+a:i==="left"?u=r.left+s-n.width-a:i==="right"&&(u=r.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+a.width<=o-5&&t+a.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const I_="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(I_))return;const e=document.createElement("style");e.id=I_,e.textContent=`
138
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-a:i==="bottom"?c=r.bottom+o+a:i==="left"?u=r.left+s-n.width-a:i==="right"&&(u=r.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+a.width<=o-5&&t+a.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const B_="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(B_))return;const e=document.createElement("style");e.id=B_,e.textContent=`
139
139
  .tiny-remoter-native-tooltip {
140
140
  position: absolute;
141
141
  z-index: 9999;
@@ -182,7 +182,7 @@ Minimum version required to store current data is: `+M+`.
182
182
  transform: translateY(-50%);
183
183
  border-right-color: rgba(0,0,0,.75);
184
184
  }
185
- `,document.head.appendChild(e)})();const Yx="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",Qx="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",Xx="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",eE="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",tE="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",rE="https://chat.opentiny.design",nE="https://ai.opentiny.design/next-remoter",oE="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",x_=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:eE},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:Yx},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:Xx},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:Qx}];class sE{constructor(t){if(this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new Kx(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||nE,remoteUrl:t.remoteUrl||rE,logoUrl:t.logoUrl||oE},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?x_(this.options).map(r=>{const n=t.find(o=>o.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):x_(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=`
185
+ `,document.head.appendChild(e)})();const yE="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",_E="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",vE="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",wE="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",bE="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",kE="https://chat.opentiny.design",CE="https://ai.opentiny.design/next-remoter",TE="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",H_=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:wE},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:yE},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:vE},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:_E}];class SE{constructor(t){if(this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new gE(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||CE,remoteUrl:t.remoteUrl||kE,logoUrl:t.logoUrl||TE},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?H_(this.options).map(r=>{const n=t.find(o=>o.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):H_(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=`
186
186
  <div class="tiny-remoter-floating-block__icon">
187
187
  <img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
188
188
  </div>
@@ -197,14 +197,14 @@ Minimum version required to store current data is: `+M+`.
197
197
  <div>
198
198
  ${r.showCopyIcon?`
199
199
  <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
200
- <img src="${tE}"/>
200
+ <img src="${bE}"/>
201
201
  </div>
202
202
  `:""}
203
203
  </div>
204
204
  </div>
205
205
  </div>
206
206
  </div>
207
- `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}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 r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new S_((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
207
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}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 r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new Z_((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
208
208
  <div style="text-align: center; padding: 32px;">
209
209
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
210
210
  <div style="
@@ -630,4 +630,4 @@ Minimum version required to store current data is: `+M+`.
630
630
  color: white;
631
631
  }
632
632
  }
633
- `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const aE=(e={})=>new sE(e);br.AgentModelProvider=Ix,br.QrCode=S_,br.createRemoter=aE,br.getAISDKTools=Zy,Object.defineProperty(br,Symbol.toStringTag,{value:"Module"})}));
633
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const IE=(e={})=>new SE(e);Pr.AgentModelProvider=H7,Pr.QrCode=Z_,Pr.createRemoter=IE,Pr.getAISDKTools=c_,Object.defineProperty(Pr,Symbol.toStringTag,{value:"Module"})}));