@opentiny/next-sdk 0.1.15-beta.4 → 0.1.15-beta.5

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,88 +1,90 @@
1
- (function(Jt,Zr){typeof exports=="object"&&typeof module<"u"?Zr(exports):typeof define=="function"&&define.amd?define(["exports"],Zr):(Jt=typeof globalThis<"u"?globalThis:Jt||self,Zr(Jt.WebAgent={}))})(this,(function(Jt){"use strict";var Zr="vercel.ai.error",I2=Symbol.for(Zr),ac,x2=class T2 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[ac]=!0,this.name=t,this.cause=n}static isInstance(t){return T2.hasMarker(t,Zr)}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}};ac=I2;var ue=x2,ic="AI_APICallError",lc=`vercel.ai.error.${ic}`,R2=Symbol.for(lc),cc,Pe=class extends ue{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:ic,message:e,cause:a}),this[cc]=!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 ue.hasMarker(e,lc)}};cc=R2;var uc="AI_EmptyResponseBodyError",dc=`vercel.ai.error.${uc}`,P2=Symbol.for(dc),pc,fc=class extends ue{constructor({message:e="Empty response body"}={}){super({name:uc,message:e}),this[pc]=!0}static isInstance(e){return ue.hasMarker(e,dc)}};pc=P2;function Fr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var hc="AI_InvalidArgumentError",mc=`vercel.ai.error.${hc}`,O2=Symbol.for(mc),gc,io=class extends ue{constructor({message:t,cause:r,argument:n}){super({name:hc,message:t,cause:r}),this[gc]=!0,this.argument=n}static isInstance(t){return ue.hasMarker(t,mc)}};gc=O2;var vc="AI_InvalidPromptError",_c=`vercel.ai.error.${vc}`,M2=Symbol.for(_c),yc,br=class extends ue{constructor({prompt:e,message:t,cause:r}){super({name:vc,message:`Invalid prompt: ${t}`,cause:r}),this[yc]=!0,this.prompt=e}static isInstance(e){return ue.hasMarker(e,_c)}};yc=M2;var wc="AI_InvalidResponseDataError",bc=`vercel.ai.error.${wc}`,N2=Symbol.for(bc),kc,_n=class extends ue{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:wc,message:t}),this[kc]=!0,this.data=e}static isInstance(e){return ue.hasMarker(e,bc)}};kc=N2;var Sc="AI_JSONParseError",Cc=`vercel.ai.error.${Sc}`,A2=Symbol.for(Cc),Tc,sr=class extends ue{constructor({text:e,cause:t}){super({name:Sc,message:`JSON parsing failed: Text: ${e}.
2
- Error message: ${Fr(t)}`,cause:t}),this[Tc]=!0,this.text=e}static isInstance(e){return ue.hasMarker(e,Cc)}};Tc=A2;var $c="AI_LoadAPIKeyError",Ec=`vercel.ai.error.${$c}`,q2=Symbol.for(Ec),Ic,ar=class extends ue{constructor({message:e}){super({name:$c,message:e}),this[Ic]=!0}static isInstance(e){return ue.hasMarker(e,Ec)}};Ic=q2;var xc="AI_NoSuchModelError",Rc=`vercel.ai.error.${xc}`,L2=Symbol.for(Rc),Pc,Oc=class extends ue{constructor({errorName:e=xc,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Pc]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return ue.hasMarker(e,Rc)}};Pc=L2;var Mc="AI_TooManyEmbeddingValuesForCallError",Nc=`vercel.ai.error.${Mc}`,j2=Symbol.for(Nc),Ac,U2=class extends ue{constructor(e){super({name:Mc,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[Ac]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ue.hasMarker(e,Nc)}};Ac=j2;var qc="AI_TypeValidationError",Lc=`vercel.ai.error.${qc}`,z2=Symbol.for(Lc),jc,D2=class sc extends ue{constructor({value:t,cause:r}){super({name:qc,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
- Error message: ${Fr(r)}`,cause:r}),this[jc]=!0,this.value=t}static isInstance(t){return ue.hasMarker(t,Lc)}static wrap({value:t,cause:r}){return sc.isInstance(r)&&r.value===t?r:new sc({value:t,cause:r})}};jc=z2;var At=D2,Uc="AI_UnsupportedFunctionalityError",zc=`vercel.ai.error.${Uc}`,Z2=Symbol.for(zc),Dc,Ct=class extends ue{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Uc,message:t}),this[Dc]=!0,this.functionality=e}static isInstance(e){return ue.hasMarker(e,zc)}};Dc=Z2;class Zc 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 ca(e){}function Fc(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=ca,onError:r=ca,onRetry:n=ca,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(w){const m=a?w.replace(/^\xEF\xBB\xBF/,""):w,[y,_]=F2(`${s}${m}`);for(const f of y)g(f);s=_,a=!1}function g(w){if(w===""){d();return}if(w.startsWith(":")){o&&o(w.slice(w.startsWith(": ")?2:1));return}const m=w.indexOf(":");if(m!==-1){const y=w.slice(0,m),_=w[m+1]===" "?2:1,f=w.slice(m+_);h(y,f,w);return}h(w,"",w)}function h(w,m,y){switch(w){case"event":c=m;break;case"data":l=`${l}${m}
4
- `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):r(new Zc(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:y}));break;default:r(new Zc(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:m,line:y}));break}}function d(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
5
- `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function p(w={}){s&&w.consume&&g(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:p}}function F2(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
6
- `,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]===`
7
- `&&n++}}return[t,r]}class Vr extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=Fc({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)}})}}const Vc=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 yn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Hc={};function ir(e){return Hc}function Bc(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 V2(e,t){return typeof t=="bigint"?t.toString():t}function ua(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function da(e){return e==null}function pa(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function H2(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 Te(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 lo(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function wn(e){return JSON.stringify(e)}const Jc=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const B2=ua(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function uo(e){if(co(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(co(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const J2=new Set(["string","number","symbol"]);function bn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kr(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function re(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 G2(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const W2={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 K2(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 kr(e,{...e._zod.def,shape:r,checks:[]})}function Y2(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 kr(e,{...e._zod.def,shape:r,checks:[]})}function Q2(e,t){if(!uo(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 lo(this,"shape",n),n},checks:[]};return kr(e,r)}function X2(e,t){return kr(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return lo(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function eg(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 kr(t,{...t._zod.def,shape:o,checks:[]})}function tg(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 kr(t,{...t._zod.def,shape:o,checks:[]})}function kn(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Sr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function po(e){return typeof e=="string"?e:e?.message}function lr(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=po(e.inst?._zod.def?.error?.(e))??po(t?.error?.(e))??po(r.customError?.(e))??po(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function fa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Sn(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Gc=(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,V2,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Wc=J("$ZodError",Gc),Kc=J("$ZodError",Gc,{Parent:Error});function rg(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 ng(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 og=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 yn;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>lr(l,s,ir())));throw Jc(i,o?.callee),i}return a.value},sg=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,ir())));throw Jc(i,o?.callee),i}return a.value},Yc=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 yn;return s.issues.length?{success:!1,error:new(e??Wc)(s.issues.map(a=>lr(a,o,ir())))}:{success:!0,data:s.value}},Qc=Yc(Kc),Xc=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,ir())))}:{success:!0,data:s.value}},ag=Xc(Kc),ig=/^[cC][^\s-]{8,}$/,lg=/^[0-9a-z]+$/,cg=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ug=/^[0-9a-vA-V]{20}$/,dg=/^[A-Za-z0-9]{27}$/,pg=/^[a-zA-Z0-9_-]{21}$/,fg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,hg=/^([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})$/,eu=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)$/,mg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,gg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vg(){return new RegExp(gg,"u")}const _g=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,yg=/^(([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})$/,wg=/^((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])$/,bg=/^(([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])$/,kg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,tu=/^[A-Za-z0-9_-]*$/,Sg=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Cg=/^\+(?:[0-9]){6,14}[0-9]$/,ru="(?:(?:\\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])))",Tg=new RegExp(`^${ru}$`);function nu(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 $g(e){return new RegExp(`^${nu(e)}$`)}function Eg(e){const t=nu({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(`^${ru}T(?:${n})$`)}const Ig=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},xg=/^\d+$/,Rg=/^-?\d+(?:\.\d+)?/i,Pg=/true|false/i,Og=/null/i,Mg=/^[^A-Z]*$/,Ng=/^[^a-z]*$/,it=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ou={number:"number",bigint:"bigint",object:"date"},su=J("$ZodCheckLessThan",(e,t)=>{it.init(e,t);const r=ou[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})}}),au=J("$ZodCheckGreaterThan",(e,t)=>{it.init(e,t);const r=ou[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})}}),Ag=J("$ZodCheckMultipleOf",(e,t)=>{it.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):H2(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})}}),qg=J("$ZodCheckNumberFormat",(e,t)=>{it.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=W2[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=xg)}),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})}}),Lg=J("$ZodCheckMaxLength",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!da(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=fa(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),jg=J("$ZodCheckMinLength",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!da(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=fa(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ug=J("$ZodCheckLengthEquals",(e,t)=>{var r;it.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!da(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=fa(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})}}),fo=J("$ZodCheckStringFormat",(e,t)=>{var r,n;it.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(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=()=>{})}),zg=J("$ZodCheckRegex",(e,t)=>{fo.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})}}),Dg=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Mg),fo.init(e,t)}),Zg=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ng),fo.init(e,t)}),Fg=J("$ZodCheckIncludes",(e,t)=>{it.init(e,t);const r=bn(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})}}),Vg=J("$ZodCheckStartsWith",(e,t)=>{it.init(e,t);const r=new RegExp(`^${bn(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})}}),Hg=J("$ZodCheckEndsWith",(e,t)=>{it.init(e,t);const r=new RegExp(`.*${bn(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})}}),Bg=J("$ZodCheckOverwrite",(e,t)=>{it.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Jg{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(`
8
- `).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(`
9
- `))}}const Gg={major:4,minor:0,patch:0},Oe=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Gg;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=kn(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,h=u._zod.check(s);if(h instanceof Promise&&i?.async===!1)throw new yn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==g&&(l||(l=kn(s,g)))});else{if(s.issues.length===g)continue;l||(l=kn(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 yn;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=Qc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ag(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),ha=J("$ZodString",(e,t)=>{Oe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ig(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}}),Le=J("$ZodStringFormat",(e,t)=>{fo.init(e,t),ha.init(e,t)}),Wg=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=hg),Le.init(e,t)}),Kg=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=eu(n))}else t.pattern??(t.pattern=eu());Le.init(e,t)}),Yg=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=mg),Le.init(e,t)}),Qg=J("$ZodURL",(e,t)=>{Le.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:Sg.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})}}}),Xg=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=vg()),Le.init(e,t)}),e1=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pg),Le.init(e,t)}),t1=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ig),Le.init(e,t)}),r1=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=lg),Le.init(e,t)}),n1=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=cg),Le.init(e,t)}),o1=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ug),Le.init(e,t)}),s1=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=dg),Le.init(e,t)}),a1=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Eg(t)),Le.init(e,t)}),i1=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Tg),Le.init(e,t)}),l1=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=$g(t)),Le.init(e,t)}),c1=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fg),Le.init(e,t)}),u1=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=_g),Le.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),d1=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=yg),Le.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})}}}),p1=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=wg),Le.init(e,t)}),f1=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=bg),Le.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 iu(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const h1=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=kg),Le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{iu(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function m1(e){if(!tu.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return iu(r)}const g1=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=tu),Le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{m1(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),v1=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Cg),Le.init(e,t)});function _1(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 y1=J("$ZodJWT",(e,t)=>{Le.init(e,t),e._zod.check=r=>{_1(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),lu=J("$ZodNumber",(e,t)=>{Oe.init(e,t),e._zod.pattern=e._zod.bag.pattern??Rg,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}}),w1=J("$ZodNumber",(e,t)=>{qg.init(e,t),lu.init(e,t)}),b1=J("$ZodBoolean",(e,t)=>{Oe.init(e,t),e._zod.pattern=Pg,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}}),k1=J("$ZodNull",(e,t)=>{Oe.init(e,t),e._zod.pattern=Og,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}}),S1=J("$ZodAny",(e,t)=>{Oe.init(e,t),e._zod.parse=r=>r}),C1=J("$ZodUnknown",(e,t)=>{Oe.init(e,t),e._zod.parse=r=>r}),T1=J("$ZodNever",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function cu(e,t,r){e.issues.length&&t.issues.push(...Sr(r,e.issues)),t.value[r]=e.value}const $1=J("$ZodArray",(e,t)=>{Oe.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=>cu(c,r,a))):cu(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function ho(e,t,r){e.issues.length&&t.issues.push(...Sr(r,e.issues)),t.value[r]=e.value}function uu(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(...Sr(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const E1=J("$ZodObject",(e,t)=>{Oe.init(e,t);const r=ua(()=>{const g=Object.keys(t.shape);for(const d of g)if(!(t.shape[d]instanceof Oe))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const h=G2(t.shape);return{shape:t.shape,keys:g,keySet:new Set(g),numKeys:g.length,optionalKeys:new Set(h)}});Te(e._zod,"propValues",()=>{const g=t.shape,h={};for(const d in g){const p=g[d]._zod;if(p.values){h[d]??(h[d]=new Set);for(const w of p.values)h[d].add(w)}}return h});const n=g=>{const h=new Jg(["shape","payload","ctx"]),d=r.value,p=_=>{const f=wn(_);return`shape[${f}]._zod.run({ value: input[${f}], issues: [] }, ctx)`};h.write("const input = payload.value;");const w=Object.create(null);let m=0;for(const _ of d.keys)w[_]=`key_${m++}`;h.write("const newResult = {}");for(const _ of d.keys)if(d.optionalKeys.has(_)){const f=w[_];h.write(`const ${f} = ${p(_)};`);const b=wn(_);h.write(`
10
- if (${f}.issues.length) {
1
+ (function(rr,Qr){typeof exports=="object"&&typeof module<"u"?Qr(exports):typeof define=="function"&&define.amd?define(["exports"],Qr):(rr=typeof globalThis<"u"?globalThis:rr||self,Qr(rr.WebAgent={}))})(this,(function(rr){"use strict";var Qr="vercel.ai.error",k_=Symbol.for(Qr),Tu,E_=class w_ extends Error{constructor({name:t,message:r,cause:n}){super(r),this[Tu]=!0,this.name=t,this.cause=n}static isInstance(t){return w_.hasMarker(t,Qr)}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}};Tu=k_;var ge=E_,Iu="AI_APICallError",Ru=`vercel.ai.error.${Iu}`,T_=Symbol.for(Ru),xu,ot=class extends ge{constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:i,cause:a,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:Iu,message:t,cause:a}),this[xu]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=i,this.isRetryable=l,this.data=c}static isInstance(t){return ge.hasMarker(t,Ru)}};xu=T_;var Pu="AI_EmptyResponseBodyError",Ou=`vercel.ai.error.${Pu}`,I_=Symbol.for(Ou),Mu,R_=class extends ge{constructor({message:t="Empty response body"}={}){super({name:Pu,message:t}),this[Mu]=!0}static isInstance(t){return ge.hasMarker(t,Ou)}};Mu=I_;function Xr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Au="AI_InvalidArgumentError",Nu=`vercel.ai.error.${Au}`,x_=Symbol.for(Nu),qu,Lu=class extends ge{constructor({message:t,cause:r,argument:n}){super({name:Au,message:t,cause:r}),this[qu]=!0,this.argument=n}static isInstance(t){return ge.hasMarker(t,Nu)}};qu=x_;var Uu="AI_InvalidPromptError",ju=`vercel.ai.error.${Uu}`,P_=Symbol.for(ju),Du,en=class extends ge{constructor({prompt:t,message:r,cause:n}){super({name:Uu,message:`Invalid prompt: ${r}`,cause:n}),this[Du]=!0,this.prompt=t}static isInstance(t){return ge.hasMarker(t,ju)}};Du=P_;var zu="AI_InvalidResponseDataError",Zu=`vercel.ai.error.${zu}`,O_=Symbol.for(Zu),Fu,Vu=class extends ge{constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:zu,message:r}),this[Fu]=!0,this.data=t}static isInstance(t){return ge.hasMarker(t,Zu)}};Fu=O_;var Hu="AI_JSONParseError",Bu=`vercel.ai.error.${Hu}`,M_=Symbol.for(Bu),Ju,Oo=class extends ge{constructor({text:t,cause:r}){super({name:Hu,message:`JSON parsing failed: Text: ${t}.
2
+ Error message: ${Xr(r)}`,cause:r}),this[Ju]=!0,this.text=t}static isInstance(t){return ge.hasMarker(t,Bu)}};Ju=M_;var Wu="AI_LoadAPIKeyError",Gu=`vercel.ai.error.${Wu}`,A_=Symbol.for(Gu),Ku,Mo=class extends ge{constructor({message:t}){super({name:Wu,message:t}),this[Ku]=!0}static isInstance(t){return ge.hasMarker(t,Gu)}};Ku=A_;var Yu="AI_NoSuchModelError",Qu=`vercel.ai.error.${Yu}`,N_=Symbol.for(Qu),Xu,ed=class extends ge{constructor({errorName:e=Yu,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Xu]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return ge.hasMarker(e,Qu)}};Xu=N_;var td="AI_TypeValidationError",rd=`vercel.ai.error.${td}`,q_=Symbol.for(rd),nd,L_=class ku extends ge{constructor({value:t,cause:r}){super({name:td,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
+ Error message: ${Xr(r)}`,cause:r}),this[nd]=!0,this.value=t}static isInstance(t){return ge.hasMarker(t,rd)}static wrap({value:t,cause:r}){return ku.isInstance(r)&&r.value===t?r:new ku({value:t,cause:r})}};nd=q_;var Nn=L_,od="AI_UnsupportedFunctionalityError",sd=`vercel.ai.error.${od}`,U_=Symbol.for(sd),ad,id=class extends ge{constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:od,message:r}),this[ad]=!0,this.functionality=t}static isInstance(t){return ge.hasMarker(t,sd)}};ad=U_;class ld 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 Wa(e){}function cd(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=Wa,onError:r=Wa,onRetry:n=Wa,onComment:o}=e;let s="",i=!0,a,l="",c="";function u(v){const _=i?v.replace(/^\xEF\xBB\xBF/,""):v,[w,g]=j_(`${s}${_}`);for(const y of w)m(y);s=g,i=!1}function m(v){if(v===""){p();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const _=v.indexOf(":");if(_!==-1){const w=v.slice(0,_),g=v[_+1]===" "?2:1,y=v.slice(_+g);f(w,y,v);return}f(v,"",v)}function f(v,_,w){switch(v){case"event":c=_;break;case"data":l=`${l}${_}
4
+ `;break;case"id":a=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new ld(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:r(new ld(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:_,line:w}));break}}function p(){l.length>0&&t({id:a,event:c||void 0,data:l.endsWith(`
5
+ `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function h(v={}){s&&v.consume&&m(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:h}}function j_(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
6
+ `,n);let i=-1;if(o!==-1&&s!==-1?i=Math.min(o,s):o!==-1?o===e.length-1?i=-1:i=o:s!==-1&&(i=s),i===-1){r=e.slice(n);break}else{const a=e.slice(n,i);t.push(a),n=i+1,e[n-1]==="\r"&&e[n]===`
7
+ `&&n++}}return[t,r]}class Pr extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=cd({onEvent:i=>{s.enqueue(i)},onError(i){t==="terminate"?s.error(i):typeof t=="function"&&t(i)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}const Ga=Object.freeze({status:"aborted"});function J(e,t,r){function n(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(e),t(a,l);for(const u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var l;const c=r?.Parent?new s:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class qn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const ud={};function gr(e){return ud}function dd(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 D_(e,t){return typeof t=="bigint"?t.toString():t}function Ka(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ya(e){return e==null}function Qa(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function z_(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(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function Te(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 Ao(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ln(e){return JSON.stringify(e)}const pd=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function No(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Z_=Ka(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function qo(e){if(No(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(No(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const F_=new Set(["string","number","symbol"]);function Un(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Or(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function se(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 V_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const H_={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 B_(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 Or(e,{...e._zod.def,shape:r,checks:[]})}function J_(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 Or(e,{...e._zod.def,shape:r,checks:[]})}function W_(e,t){if(!qo(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 Ao(this,"shape",n),n},checks:[]};return Or(e,r)}function G_(e,t){return Or(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Ao(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function K_(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 Or(t,{...t._zod.def,shape:o,checks:[]})}function Y_(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 Or(t,{...t._zod.def,shape:o,checks:[]})}function jn(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Mr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Lo(e){return typeof e=="string"?e:e?.message}function _r(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Lo(e.inst?._zod.def?.error?.(e))??Lo(t?.error?.(e))??Lo(r.customError?.(e))??Lo(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Xa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Dn(...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,D_,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},fd=J("$ZodError",hd),md=J("$ZodError",hd,{Parent:Error});function Q_(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 X_(e,t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(e),n}const ev=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new qn;if(i.issues.length){const a=new(o?.Err??e)(i.issues.map(l=>_r(l,s,gr())));throw pd(a,o?.callee),a}return i.value},tv=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new(o?.Err??e)(i.issues.map(l=>_r(l,s,gr())));throw pd(a,o?.callee),a}return i.value},gd=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 qn;return s.issues.length?{success:!1,error:new(e??fd)(s.issues.map(i=>_r(i,o,gr())))}:{success:!0,data:s.value}},ei=gd(md),_d=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(i=>_r(i,o,gr())))}:{success:!0,data:s.value}},rv=_d(md),nv=/^[cC][^\s-]{8,}$/,ov=/^[0-9a-z]+$/,sv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,av=/^[0-9a-vA-V]{20}$/,iv=/^[A-Za-z0-9]{27}$/,lv=/^[a-zA-Z0-9_-]{21}$/,cv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,uv=/^([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})$/,vd=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)$/,dv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,pv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function hv(){return new RegExp(pv,"u")}const fv=/^(?:(?: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])$/,mv=/^(([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})$/,gv=/^((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])$/,_v=/^(([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])$/,vv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yd=/^[A-Za-z0-9_-]*$/,yv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,wv=/^\+(?:[0-9]){6,14}[0-9]$/,wd="(?:(?:\\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])))",bv=new RegExp(`^${wd}$`);function bd(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 Sv(e){return new RegExp(`^${bd(e)}$`)}function $v(e){const t=bd({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(`^${wd}T(?:${n})$`)}const Cv=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},kv=/^\d+$/,Ev=/^-?\d+(?:\.\d+)?/i,Tv=/true|false/i,Iv=/null/i,Rv=/^[^A-Z]*$/,xv=/^[^a-z]*$/,dt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Sd={number:"number",bigint:"bigint",object:"date"},$d=J("$ZodCheckLessThan",(e,t)=>{dt.init(e,t);const r=Sd[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})}}),Cd=J("$ZodCheckGreaterThan",(e,t)=>{dt.init(e,t);const r=Sd[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})}}),Pv=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):z_(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})}}),Ov=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]=H_[t.format];e._zod.onattach.push(i=>{const a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,r&&(a.pattern=kv)}),e._zod.check=i=>{const a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:a,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}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}}),Mv=J("$ZodCheckMaxLength",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ya(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 i=Xa(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Av=J("$ZodCheckMinLength",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ya(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 i=Xa(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Nv=J("$ZodCheckLengthEquals",(e,t)=>{var r;dt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ya(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 i=Xa(o),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Uo=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=()=>{})}),qv=J("$ZodCheckRegex",(e,t)=>{Uo.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})}}),Lv=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Rv),Uo.init(e,t)}),Uv=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=xv),Uo.init(e,t)}),jv=J("$ZodCheckIncludes",(e,t)=>{dt.init(e,t);const r=Un(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})}}),Dv=J("$ZodCheckStartsWith",(e,t)=>{dt.init(e,t);const r=new RegExp(`^${Un(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})}}),zv=J("$ZodCheckEndsWith",(e,t)=>{dt.init(e,t);const r=new RegExp(`.*${Un(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})}}),Zv=J("$ZodCheckOverwrite",(e,t)=>{dt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class Fv{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(`
8
+ `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
9
+ `))}}const Vv={major:4,minor:0,patch:0},Me=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Vv;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,i,a)=>{let l=jn(s),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const m=s.issues.length,f=u._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new qn;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,s.issues.length!==m&&(l||(l=jn(s,m)))});else{if(s.issues.length===m)continue;l||(l=jn(s,m))}}return c?c.then(()=>s):s};e._zod.run=(s,i)=>{const a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new qn;return a.then(l=>o(l,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{const s=ei(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return rv(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ti=J("$ZodString",(e,t)=>{Me.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Cv(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}}),Le=J("$ZodStringFormat",(e,t)=>{Uo.init(e,t),ti.init(e,t)}),Hv=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=uv),Le.init(e,t)}),Bv=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=vd(n))}else t.pattern??(t.pattern=vd());Le.init(e,t)}),Jv=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=dv),Le.init(e,t)}),Wv=J("$ZodURL",(e,t)=>{Le.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:yv.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})}}}),Gv=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=hv()),Le.init(e,t)}),Kv=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=lv),Le.init(e,t)}),Yv=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=nv),Le.init(e,t)}),Qv=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ov),Le.init(e,t)}),Xv=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=sv),Le.init(e,t)}),ey=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=av),Le.init(e,t)}),ty=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=iv),Le.init(e,t)}),ry=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=$v(t)),Le.init(e,t)}),ny=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=bv),Le.init(e,t)}),oy=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Sv(t)),Le.init(e,t)}),sy=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=cv),Le.init(e,t)}),ay=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=fv),Le.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),iy=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=mv),Le.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})}}}),ly=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=gv),Le.init(e,t)}),cy=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=_v),Le.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 kd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const uy=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=vv),Le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{kd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function dy(e){if(!yd.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return kd(r)}const py=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=yd),Le.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{dy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),hy=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=wv),Le.init(e,t)});function fy(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 my=J("$ZodJWT",(e,t)=>{Le.init(e,t),e._zod.check=r=>{fy(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Ed=J("$ZodNumber",(e,t)=>{Me.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ev,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}}),gy=J("$ZodNumber",(e,t)=>{Ov.init(e,t),Ed.init(e,t)}),_y=J("$ZodBoolean",(e,t)=>{Me.init(e,t),e._zod.pattern=Tv,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}}),vy=J("$ZodNull",(e,t)=>{Me.init(e,t),e._zod.pattern=Iv,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}}),yy=J("$ZodAny",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),wy=J("$ZodUnknown",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),by=J("$ZodNever",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Td(e,t,r){e.issues.length&&t.issues.push(...Mr(r,e.issues)),t.value[r]=e.value}const Sy=J("$ZodArray",(e,t)=>{Me.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 i=0;i<o.length;i++){const a=o[i],l=t.element._zod.run({value:a,issues:[]},n);l instanceof Promise?s.push(l.then(c=>Td(c,r,i))):Td(l,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function jo(e,t,r){e.issues.length&&t.issues.push(...Mr(r,e.issues)),t.value[r]=e.value}function Id(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(...Mr(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const $y=J("$ZodObject",(e,t)=>{Me.init(e,t);const r=Ka(()=>{const m=Object.keys(t.shape);for(const p of m)if(!(t.shape[p]instanceof Me))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);const f=V_(t.shape);return{shape:t.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set(f)}});Te(e._zod,"propValues",()=>{const m=t.shape,f={};for(const p in m){const h=m[p]._zod;if(h.values){f[p]??(f[p]=new Set);for(const v of h.values)f[p].add(v)}}return f});const n=m=>{const f=new Fv(["shape","payload","ctx"]),p=r.value,h=g=>{const y=Ln(g);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};f.write("const input = payload.value;");const v=Object.create(null);let _=0;for(const g of p.keys)v[g]=`key_${_++}`;f.write("const newResult = {}");for(const g of p.keys)if(p.optionalKeys.has(g)){const y=v[g];f.write(`const ${y} = ${h(g)};`);const b=Ln(g);f.write(`
10
+ if (${y}.issues.length) {
11
11
  if (input[${b}] === undefined) {
12
12
  if (${b} in input) {
13
13
  newResult[${b}] = undefined;
14
14
  }
15
15
  } else {
16
16
  payload.issues = payload.issues.concat(
17
- ${f}.issues.map((iss) => ({
17
+ ${y}.issues.map((iss) => ({
18
18
  ...iss,
19
19
  path: iss.path ? [${b}, ...iss.path] : [${b}],
20
20
  }))
21
21
  );
22
22
  }
23
- } else if (${f}.value === undefined) {
23
+ } else if (${y}.value === undefined) {
24
24
  if (${b} in input) newResult[${b}] = undefined;
25
25
  } else {
26
- newResult[${b}] = ${f}.value;
26
+ newResult[${b}] = ${y}.value;
27
27
  }
28
- `)}else{const f=w[_];h.write(`const ${f} = ${p(_)};`),h.write(`
29
- if (${f}.issues.length) payload.issues = payload.issues.concat(${f}.issues.map(iss => ({
28
+ `)}else{const y=v[g];f.write(`const ${y} = ${h(g)};`),f.write(`
29
+ if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
30
30
  ...iss,
31
- path: iss.path ? [${wn(_)}, ...iss.path] : [${wn(_)}]
32
- })));`),h.write(`newResult[${wn(_)}] = ${f}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const y=h.compile();return(_,f)=>y(g,_,f)};let o;const s=co,a=!Hc.jitless,l=a&&B2.value,c=t.catchall;let u;e._zod.parse=(g,h)=>{u??(u=r.value);const d=g.value;if(!s(d))return g.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),g;const p=[];if(a&&l&&h?.async===!1&&h.jitless!==!0)o||(o=n(t.shape)),g=o(g,h);else{g.value={};const f=u.shape;for(const b of u.keys){const k=f[b],S=k._zod.run({value:d[b],issues:[]},h),C=k._zod.optin==="optional"&&k._zod.optout==="optional";S instanceof Promise?p.push(S.then(I=>C?uu(I,g,b,d):ho(I,g,b))):C?uu(S,g,b,d):ho(S,g,b)}}if(!c)return p.length?Promise.all(p).then(()=>g):g;const w=[],m=u.keySet,y=c._zod,_=y.def.type;for(const f of Object.keys(d)){if(m.has(f))continue;if(_==="never"){w.push(f);continue}const b=y.run({value:d[f],issues:[]},h);b instanceof Promise?p.push(b.then(k=>ho(k,g,f))):ho(b,g,f)}return w.length&&g.issues.push({code:"unrecognized_keys",keys:w,input:d,inst:e}),p.length?Promise.all(p).then(()=>g):g}});function du(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,ir())))}),t}const pu=J("$ZodUnion",(e,t)=>{Oe.init(e,t),Te(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Te(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=>pa(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=>du(a,r,e,n)):du(s,r,e,n)}}),I1=J("$ZodDiscriminatedUnion",(e,t)=>{pu.init(e,t);const r=e._zod.parse;Te(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=ua(()=>{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(!co(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)}}),x1=J("$ZodIntersection",(e,t)=>{Oe.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])=>fu(r,l,c)):fu(r,s,a)}});function ma(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(uo(e)&&uo(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=ma(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=ma(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 fu(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),kn(e))return e;const n=ma(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 R1=J("$ZodRecord",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!uo(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(...Sr(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Sr(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,ir())),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(...Sr(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Sr(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),P1=J("$ZodEnum",(e,t)=>{Oe.init(e,t);const r=Bc(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>J2.has(typeof n)).map(n=>typeof n=="string"?bn(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}}),O1=J("$ZodLiteral",(e,t)=>{Oe.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?bn(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}}),M1=J("$ZodTransform",(e,t)=>{Oe.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 yn;return r.value=o,r}}),N1=J("$ZodOptional",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Te(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Te(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pa(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)}),A1=J("$ZodNullable",(e,t)=>{Oe.init(e,t),Te(e._zod,"optin",()=>t.innerType._zod.optin),Te(e._zod,"optout",()=>t.innerType._zod.optout),Te(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${pa(r.source)}|null)$`):void 0}),Te(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)}),q1=J("$ZodDefault",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Te(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=>hu(s,t)):hu(o,t)}});function hu(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const L1=J("$ZodPrefault",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Te(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))}),j1=J("$ZodNonOptional",(e,t)=>{Oe.init(e,t),Te(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=>mu(s,e)):mu(o,e)}});function mu(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 U1=J("$ZodCatch",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Te(e._zod,"optout",()=>t.innerType._zod.optout),Te(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,ir()))},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,ir()))},input:r.value}),r.issues=[]),r)}}),z1=J("$ZodPipe",(e,t)=>{Oe.init(e,t),Te(e._zod,"values",()=>t.in._zod.values),Te(e._zod,"optin",()=>t.in._zod.optin),Te(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=>gu(s,t,n)):gu(o,t,n)}});function gu(e,t,r){return kn(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const D1=J("$ZodReadonly",(e,t)=>{Oe.init(e,t),Te(e._zod,"propValues",()=>t.innerType._zod.propValues),Te(e._zod,"values",()=>t.innerType._zod.values),Te(e._zod,"optin",()=>t.innerType._zod.optin),Te(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(vu):vu(o)}});function vu(e){return e.value=Object.freeze(e.value),e}const Z1=J("$ZodLazy",(e,t)=>{Oe.init(e,t),Te(e._zod,"innerType",()=>t.getter()),Te(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Te(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Te(e._zod,"optin",()=>e._zod.innerType._zod.optin),Te(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),F1=J("$ZodCustom",(e,t)=>{it.init(e,t),Oe.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=>_u(s,r,n,e));_u(o,r,n,e)}});function _u(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(Sn(o))}}class yu{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 V1(){return new yu}const Cn=V1();function H1(e,t){return new e({type:"string",...re(t)})}function B1(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...re(t)})}function wu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...re(t)})}function J1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...re(t)})}function G1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(t)})}function W1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(t)})}function K1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(t)})}function bu(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function Y1(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...re(t)})}function Q1(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(t)})}function X1(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...re(t)})}function ev(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(t)})}function tv(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...re(t)})}function rv(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...re(t)})}function nv(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(t)})}function ov(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(t)})}function sv(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(t)})}function av(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(t)})}function iv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(t)})}function ku(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...re(t)})}function lv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...re(t)})}function cv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...re(t)})}function uv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...re(t)})}function dv(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(t)})}function pv(e,t){return new e({type:"string",format:"date",check:"string_format",...re(t)})}function fv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...re(t)})}function hv(e,t){return new e({type:"string",format:"duration",check:"string_format",...re(t)})}function mv(e,t){return new e({type:"number",checks:[],...re(t)})}function gv(e,t){return new e({type:"number",coerce:!0,checks:[],...re(t)})}function vv(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function _v(e,t){return new e({type:"boolean",...re(t)})}function yv(e,t){return new e({type:"null",...re(t)})}function wv(e){return new e({type:"any"})}function bv(e){return new e({type:"unknown"})}function kv(e,t){return new e({type:"never",...re(t)})}function Su(e,t){return new su({check:"less_than",...re(t),value:e,inclusive:!1})}function ga(e,t){return new su({check:"less_than",...re(t),value:e,inclusive:!0})}function Cu(e,t){return new au({check:"greater_than",...re(t),value:e,inclusive:!1})}function va(e,t){return new au({check:"greater_than",...re(t),value:e,inclusive:!0})}function Tu(e,t){return new Ag({check:"multiple_of",...re(t),value:e})}function $u(e,t){return new Lg({check:"max_length",...re(t),maximum:e})}function mo(e,t){return new jg({check:"min_length",...re(t),minimum:e})}function Eu(e,t){return new Ug({check:"length_equals",...re(t),length:e})}function Sv(e,t){return new zg({check:"string_format",format:"regex",...re(t),pattern:e})}function Cv(e){return new Dg({check:"string_format",format:"lowercase",...re(e)})}function Tv(e){return new Zg({check:"string_format",format:"uppercase",...re(e)})}function $v(e,t){return new Fg({check:"string_format",format:"includes",...re(t),includes:e})}function Ev(e,t){return new Vg({check:"string_format",format:"starts_with",...re(t),prefix:e})}function Iv(e,t){return new Hg({check:"string_format",format:"ends_with",...re(t),suffix:e})}function Tn(e){return new Bg({check:"overwrite",tx:e})}function xv(e){return Tn(t=>t.normalize(e))}function Rv(){return Tn(e=>e.trim())}function Pv(){return Tn(e=>e.toLowerCase())}function Ov(){return Tn(e=>e.toUpperCase())}function Mv(e,t,r){return new e({type:"array",element:t,...re(r)})}function Nv(e,t,r){const n=re(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Av(e,t,r){return new e({type:"custom",check:"custom",fn:t,...re(r)})}class Iu{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Cn,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},h=t._zod.parent;if(h)i.ref=h,this.process(h,g),this.seen.get(h).isParent=!0;else{const d=i.schema;switch(o.type){case"string":{const p=d;p.type="string";const{minimum:w,maximum:m,format:y,patterns:_,contentEncoding:f}=t._zod.bag;if(typeof w=="number"&&(p.minLength=w),typeof m=="number"&&(p.maxLength=m),y&&(p.format=s[y]??y,p.format===""&&delete p.format),f&&(p.contentEncoding=f),_&&_.size>0){const b=[..._];b.length===1?p.pattern=b[0].source:b.length>1&&(i.schema.allOf=[...b.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const p=d,{minimum:w,maximum:m,format:y,multipleOf:_,exclusiveMaximum:f,exclusiveMinimum:b}=t._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof w=="number"&&(p.minimum=w,typeof b=="number"&&(b>=w?delete p.minimum:delete p.exclusiveMinimum)),typeof f=="number"&&(p.exclusiveMaximum=f),typeof m=="number"&&(p.maximum=m,typeof f=="number"&&(f<=m?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{const p=d;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=d,{minimum:w,maximum:m}=t._zod.bag;typeof w=="number"&&(p.minItems=w),typeof m=="number"&&(p.maxItems=m),p.type="array",p.items=this.process(o.element,{...g,path:[...g.path,"items"]});break}case"object":{const p=d;p.type="object",p.properties={};const w=o.shape;for(const _ in w)p.properties[_]=this.process(w[_],{...g,path:[...g.path,"properties",_]});const m=new Set(Object.keys(w)),y=new Set([...m].filter(_=>{const f=o.shape[_]._zod;return this.io==="input"?f.optin===void 0:f.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...g,path:[...g.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=d;p.anyOf=o.options.map((w,m)=>this.process(w,{...g,path:[...g.path,"anyOf",m]}));break}case"intersection":{const p=d,w=this.process(o.left,{...g,path:[...g.path,"allOf",0]}),m=this.process(o.right,{...g,path:[...g.path,"allOf",1]}),y=f=>"allOf"in f&&Object.keys(f).length===1,_=[...y(w)?w.allOf:[w],...y(m)?m.allOf:[m]];p.allOf=_;break}case"tuple":{const p=d;p.type="array";const w=o.items.map((_,f)=>this.process(_,{...g,path:[...g.path,"prefixItems",f]}));if(this.target==="draft-2020-12"?p.prefixItems=w:p.items=w,o.rest){const _=this.process(o.rest,{...g,path:[...g.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}o.rest&&(p.items=this.process(o.rest,{...g,path:[...g.path,"items"]}));const{minimum:m,maximum:y}=t._zod.bag;typeof m=="number"&&(p.minItems=m),typeof y=="number"&&(p.maxItems=y);break}case"record":{const p=d;p.type="object",p.propertyNames=this.process(o.keyType,{...g,path:[...g.path,"propertyNames"]}),p.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 p=d,w=Bc(o.entries);w.every(m=>typeof m=="number")&&(p.type="number"),w.every(m=>typeof m=="string")&&(p.type="string"),p.enum=w;break}case"literal":{const p=d,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];p.type=m===null?"null":typeof m,p.const=m}else w.every(m=>typeof m=="number")&&(p.type="number"),w.every(m=>typeof m=="string")&&(p.type="string"),w.every(m=>typeof m=="boolean")&&(p.type="string"),w.every(m=>m===null)&&(p.type="null"),p.enum=w;break}case"file":{const p=d,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:m,maximum:y,mime:_}=t._zod.bag;m!==void 0&&(w.minLength=m),y!==void 0&&(w.maxLength=y),_?_.length===1?(w.contentMediaType=_[0],Object.assign(p,w)):p.anyOf=_.map(f=>({...w,contentMediaType:f})):Object.assign(p,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(o.innerType,g);d.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,g),i.ref=o.innerType;break}case"success":{const p=d;p.type="boolean";break}case"default":{this.process(o.innerType,g),i.ref=o.innerType,d.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,g),i.ref=o.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,g),i.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=d,w=t._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=w.source;break}case"pipe":{const p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,g),i.ref=p;break}case"readonly":{this.process(o.innerType,g),i.ref=o.innerType,d.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 p=t._zod.innerType;this.process(p,g),i.ref=p;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"&&De(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 y=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=y,{defId:y,ref:`${m("__shared")}#/${g}/${y}`}}if(u[1]===o)return{ref:"#"};const d=`#/${g}/`,p=u[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:d+p}},a=u=>{if(u[1].schema.$ref)return;const g=u[1],{ref:h,defId:d}=s(u);g.def={...g.schema},d&&(g.defId=d);const p=g.schema;for(const w in p)delete p[w];p.$ref=h};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>
31
+ path: iss.path ? [${Ln(g)}, ...iss.path] : [${Ln(g)}]
32
+ })));`),f.write(`newResult[${Ln(g)}] = ${y}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");const w=f.compile();return(g,y)=>w(m,g,y)};let o;const s=No,i=!ud.jitless,l=i&&Z_.value,c=t.catchall;let u;e._zod.parse=(m,f)=>{u??(u=r.value);const p=m.value;if(!s(p))return m.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),m;const h=[];if(i&&l&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),m=o(m,f);else{m.value={};const y=u.shape;for(const b of u.keys){const S=y[b],$=S._zod.run({value:p[b],issues:[]},f),k=S._zod.optin==="optional"&&S._zod.optout==="optional";$ instanceof Promise?h.push($.then(I=>k?Id(I,m,b,p):jo(I,m,b))):k?Id($,m,b,p):jo($,m,b)}}if(!c)return h.length?Promise.all(h).then(()=>m):m;const v=[],_=u.keySet,w=c._zod,g=w.def.type;for(const y of Object.keys(p)){if(_.has(y))continue;if(g==="never"){v.push(y);continue}const b=w.run({value:p[y],issues:[]},f);b instanceof Promise?h.push(b.then(S=>jo(S,m,y))):jo(b,m,y)}return v.length&&m.issues.push({code:"unrecognized_keys",keys:v,input:p,inst:e}),h.length?Promise.all(h).then(()=>m):m}});function Rd(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=>_r(s,n,gr())))}),t}const xd=J("$ZodUnion",(e,t)=>{Me.init(e,t),Te(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Te(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=>Qa(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const i of t.options){const a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Rd(i,r,e,n)):Rd(s,r,e,n)}}),Cy=J("$ZodDiscriminatedUnion",(e,t)=>{xd.init(e,t);const r=e._zod.parse;Te(e._zod,"propValues",()=>{const o={};for(const s of t.options){const i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[a,l]of Object.entries(i)){o[a]||(o[a]=new Set);for(const c of l)o[a].add(c)}}return o});const n=Ka(()=>{const o=t.options,s=new Map;for(const i of o){const a=i._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const l of a){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,i)}}return s});e._zod.parse=(o,s)=>{const i=o.value;if(!No(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;const a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),ky=J("$ZodIntersection",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>Pd(r,l,c)):Pd(r,s,i)}});function ri(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(qo(e)&&qo(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 i=ri(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.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],i=ri(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Pd(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),jn(e))return e;const n=ri(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 Ey=J("$ZodRecord",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!qo(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const i=t.keyType._zod.values;r.value={};for(const l of i)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(...Mr(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Mr(l,c.issues)),r.value[l]=c.value)}let a;for(const l in o)i.has(l)||(a=a??[],a.push(l));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(const i of Reflect.ownKeys(o)){if(i==="__proto__")continue;const a=t.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>_r(c,n,gr())),input:i,path:[i],inst:e}),r.value[a.value]=a.value;continue}const l=t.valueType._zod.run({value:o[i],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...Mr(i,c.issues)),r.value[a.value]=c.value})):(l.issues.length&&r.issues.push(...Mr(i,l.issues)),r.value[a.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Ty=J("$ZodEnum",(e,t)=>{Me.init(e,t);const r=dd(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>F_.has(typeof n)).map(n=>typeof n=="string"?Un(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}}),Iy=J("$ZodLiteral",(e,t)=>{Me.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Un(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}}),Ry=J("$ZodTransform",(e,t)=>{Me.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(i=>(r.value=i,r));if(o instanceof Promise)throw new qn;return r.value=o,r}}),xy=J("$ZodOptional",(e,t)=>{Me.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Te(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Te(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Qa(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)}),Py=J("$ZodNullable",(e,t)=>{Me.init(e,t),Te(e._zod,"optin",()=>t.innerType._zod.optin),Te(e._zod,"optout",()=>t.innerType._zod.optout),Te(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Qa(r.source)}|null)$`):void 0}),Te(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)}),Oy=J("$ZodDefault",(e,t)=>{Me.init(e,t),e._zod.optin="optional",Te(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=>Od(s,t)):Od(o,t)}});function Od(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const My=J("$ZodPrefault",(e,t)=>{Me.init(e,t),e._zod.optin="optional",Te(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))}),Ay=J("$ZodNonOptional",(e,t)=>{Me.init(e,t),Te(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=>Md(s,e)):Md(o,e)}});function Md(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 Ny=J("$ZodCatch",(e,t)=>{Me.init(e,t),e._zod.optin="optional",Te(e._zod,"optout",()=>t.innerType._zod.optout),Te(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(i=>_r(i,n,gr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>_r(s,n,gr()))},input:r.value}),r.issues=[]),r)}}),qy=J("$ZodPipe",(e,t)=>{Me.init(e,t),Te(e._zod,"values",()=>t.in._zod.values),Te(e._zod,"optin",()=>t.in._zod.optin),Te(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=>Ad(s,t,n)):Ad(o,t,n)}});function Ad(e,t,r){return jn(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Ly=J("$ZodReadonly",(e,t)=>{Me.init(e,t),Te(e._zod,"propValues",()=>t.innerType._zod.propValues),Te(e._zod,"values",()=>t.innerType._zod.values),Te(e._zod,"optin",()=>t.innerType._zod.optin),Te(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(Nd):Nd(o)}});function Nd(e){return e.value=Object.freeze(e.value),e}const Uy=J("$ZodLazy",(e,t)=>{Me.init(e,t),Te(e._zod,"innerType",()=>t.getter()),Te(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Te(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Te(e._zod,"optin",()=>e._zod.innerType._zod.optin),Te(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),jy=J("$ZodCustom",(e,t)=>{dt.init(e,t),Me.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=>qd(s,r,n,e));qd(o,r,n,e)}});function qd(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(Dn(o))}}class Ld{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 Dy(){return new Ld}const zn=Dy();function zy(e,t){return new e({type:"string",...se(t)})}function Zy(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...se(t)})}function Ud(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...se(t)})}function Fy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...se(t)})}function Vy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...se(t)})}function Hy(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...se(t)})}function By(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...se(t)})}function jd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...se(t)})}function Jy(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...se(t)})}function Wy(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...se(t)})}function Gy(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...se(t)})}function Ky(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...se(t)})}function Yy(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...se(t)})}function Qy(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...se(t)})}function Xy(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...se(t)})}function ew(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...se(t)})}function tw(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...se(t)})}function rw(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...se(t)})}function nw(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...se(t)})}function Dd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...se(t)})}function ow(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...se(t)})}function sw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...se(t)})}function aw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...se(t)})}function iw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...se(t)})}function lw(e,t){return new e({type:"string",format:"date",check:"string_format",...se(t)})}function cw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...se(t)})}function uw(e,t){return new e({type:"string",format:"duration",check:"string_format",...se(t)})}function dw(e,t){return new e({type:"number",checks:[],...se(t)})}function pw(e,t){return new e({type:"number",coerce:!0,checks:[],...se(t)})}function hw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...se(t)})}function fw(e,t){return new e({type:"boolean",...se(t)})}function mw(e,t){return new e({type:"null",...se(t)})}function gw(e){return new e({type:"any"})}function _w(e){return new e({type:"unknown"})}function vw(e,t){return new e({type:"never",...se(t)})}function zd(e,t){return new $d({check:"less_than",...se(t),value:e,inclusive:!1})}function ni(e,t){return new $d({check:"less_than",...se(t),value:e,inclusive:!0})}function Zd(e,t){return new Cd({check:"greater_than",...se(t),value:e,inclusive:!1})}function oi(e,t){return new Cd({check:"greater_than",...se(t),value:e,inclusive:!0})}function Fd(e,t){return new Pv({check:"multiple_of",...se(t),value:e})}function Vd(e,t){return new Mv({check:"max_length",...se(t),maximum:e})}function Do(e,t){return new Av({check:"min_length",...se(t),minimum:e})}function Hd(e,t){return new Nv({check:"length_equals",...se(t),length:e})}function yw(e,t){return new qv({check:"string_format",format:"regex",...se(t),pattern:e})}function ww(e){return new Lv({check:"string_format",format:"lowercase",...se(e)})}function bw(e){return new Uv({check:"string_format",format:"uppercase",...se(e)})}function Sw(e,t){return new jv({check:"string_format",format:"includes",...se(t),includes:e})}function $w(e,t){return new Dv({check:"string_format",format:"starts_with",...se(t),prefix:e})}function Cw(e,t){return new zv({check:"string_format",format:"ends_with",...se(t),suffix:e})}function Zn(e){return new Zv({check:"overwrite",tx:e})}function kw(e){return Zn(t=>t.normalize(e))}function Ew(){return Zn(e=>e.trim())}function Tw(){return Zn(e=>e.toLowerCase())}function Iw(){return Zn(e=>e.toUpperCase())}function Rw(e,t,r){return new e({type:"array",element:t,...se(r)})}function xw(e,t,r){const n=se(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Pw(e,t,r){return new e({type:"custom",check:"custom",fn:t,...se(r)})}class Bd{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??zn,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:""},i=this.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);const l=t._zod.toJSONSchema?.();if(l)a.schema=l;else{const m={...r,schemaPath:[...r.schemaPath,t],path:r.path},f=t._zod.parent;if(f)a.ref=f,this.process(f,m),this.seen.get(f).isParent=!0;else{const p=a.schema;switch(o.type){case"string":{const h=p;h.type="string";const{minimum:v,maximum:_,format:w,patterns:g,contentEncoding:y}=t._zod.bag;if(typeof v=="number"&&(h.minLength=v),typeof _=="number"&&(h.maxLength=_),w&&(h.format=s[w]??w,h.format===""&&delete h.format),y&&(h.contentEncoding=y),g&&g.size>0){const b=[...g];b.length===1?h.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{const h=p,{minimum:v,maximum:_,format:w,multipleOf:g,exclusiveMaximum:y,exclusiveMinimum:b}=t._zod.bag;typeof w=="string"&&w.includes("int")?h.type="integer":h.type="number",typeof b=="number"&&(h.exclusiveMinimum=b),typeof v=="number"&&(h.minimum=v,typeof b=="number"&&(b>=v?delete h.minimum:delete h.exclusiveMinimum)),typeof y=="number"&&(h.exclusiveMaximum=y),typeof _=="number"&&(h.maximum=_,typeof y=="number"&&(y<=_?delete h.maximum:delete h.exclusiveMaximum)),typeof g=="number"&&(h.multipleOf=g);break}case"boolean":{const h=p;h.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":{p.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":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const h=p,{minimum:v,maximum:_}=t._zod.bag;typeof v=="number"&&(h.minItems=v),typeof _=="number"&&(h.maxItems=_),h.type="array",h.items=this.process(o.element,{...m,path:[...m.path,"items"]});break}case"object":{const h=p;h.type="object",h.properties={};const v=o.shape;for(const g in v)h.properties[g]=this.process(v[g],{...m,path:[...m.path,"properties",g]});const _=new Set(Object.keys(v)),w=new Set([..._].filter(g=>{const y=o.shape[g]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));w.size>0&&(h.required=Array.from(w)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{const h=p;h.anyOf=o.options.map((v,_)=>this.process(v,{...m,path:[...m.path,"anyOf",_]}));break}case"intersection":{const h=p,v=this.process(o.left,{...m,path:[...m.path,"allOf",0]}),_=this.process(o.right,{...m,path:[...m.path,"allOf",1]}),w=y=>"allOf"in y&&Object.keys(y).length===1,g=[...w(v)?v.allOf:[v],...w(_)?_.allOf:[_]];h.allOf=g;break}case"tuple":{const h=p;h.type="array";const v=o.items.map((g,y)=>this.process(g,{...m,path:[...m.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?h.prefixItems=v:h.items=v,o.rest){const g=this.process(o.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?h.items=g:h.additionalItems=g}o.rest&&(h.items=this.process(o.rest,{...m,path:[...m.path,"items"]}));const{minimum:_,maximum:w}=t._zod.bag;typeof _=="number"&&(h.minItems=_),typeof w=="number"&&(h.maxItems=w);break}case"record":{const h=p;h.type="object",h.propertyNames=this.process(o.keyType,{...m,path:[...m.path,"propertyNames"]}),h.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 h=p,v=dd(o.entries);v.every(_=>typeof _=="number")&&(h.type="number"),v.every(_=>typeof _=="string")&&(h.type="string"),h.enum=v;break}case"literal":{const h=p,v=[];for(const _ of o.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(_))}else v.push(_);if(v.length!==0)if(v.length===1){const _=v[0];h.type=_===null?"null":typeof _,h.const=_}else v.every(_=>typeof _=="number")&&(h.type="number"),v.every(_=>typeof _=="string")&&(h.type="string"),v.every(_=>typeof _=="boolean")&&(h.type="string"),v.every(_=>_===null)&&(h.type="null"),h.enum=v;break}case"file":{const h=p,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:w,mime:g}=t._zod.bag;_!==void 0&&(v.minLength=_),w!==void 0&&(v.maxLength=w),g?g.length===1?(v.contentMediaType=g[0],Object.assign(h,v)):h.anyOf=g.map(y=>({...v,contentMediaType:y})):Object.assign(h,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const h=this.process(o.innerType,m);p.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,m),a.ref=o.innerType;break}case"success":{const h=p;h.type="boolean";break}case"default":{this.process(o.innerType,m),a.ref=o.innerType,p.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,m),a.ref=o.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,m),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const h=p,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=v.source;break}case"pipe":{const h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,m),a.ref=h;break}case"readonly":{this.process(o.innerType,m),a.ref=o.innerType,p.readOnly=!0;break}case"promise":{this.process(o.innerType,m),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,m),a.ref=o.innerType;break}case"lazy":{const h=t._zod.innerType;this.process(h,m),a.ref=h;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(a.schema,c),this.io==="input"&&Ze(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.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,_=n.external.uri??(g=>g);if(v)return{ref:_(v)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${_("__shared")}#/${m}/${w}`}}if(u[1]===o)return{ref:"#"};const p=`#/${m}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:p+h}},i=u=>{if(u[1].schema.$ref)return;const m=u[1],{ref:f,defId:p}=s(u);m.def={...m.schema},p&&(m.defId=p);const h=m.schema;for(const v in h)delete h[v];h.$ref=f};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>
33
33
 
34
- 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 d=n.external.registry.get(u[0])?.id;if(t!==u[0]&&d){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 h=this.seen.get(u),d=h.def??h.schema,p={...d};if(h.ref===null)return;const w=h.ref;if(h.ref=null,w){i(w,g);const m=this.seen.get(w).schema;m.$ref&&g.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(m)):(Object.assign(d,m),Object.assign(d,p))}h.isParent||this.override({zodSchema:u,jsonSchema:d,path:h.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 xu(e,t){if(e instanceof yu){const n=new Iu(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 Iu(t);return r.process(e),r.emit(e,t)}function De(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 De(o.element,r);case"object":{for(const s in o.shape)if(De(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(De(s,r))return!0;return!1}case"intersection":return De(o.left,r)||De(o.right,r);case"tuple":{for(const s of o.items)if(De(s,r))return!0;return!!(o.rest&&De(o.rest,r))}case"record":return De(o.keyType,r)||De(o.valueType,r);case"map":return De(o.keyType,r)||De(o.valueType,r);case"set":return De(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return De(o.innerType,r);case"lazy":return De(o.getter(),r);case"default":return De(o.innerType,r);case"prefault":return De(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return De(o.in,r)||De(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const qv=J("ZodISODateTime",(e,t)=>{a1.init(e,t),Ue.init(e,t)});function Ru(e){return dv(qv,e)}const Lv=J("ZodISODate",(e,t)=>{i1.init(e,t),Ue.init(e,t)});function jv(e){return pv(Lv,e)}const Uv=J("ZodISOTime",(e,t)=>{l1.init(e,t),Ue.init(e,t)});function zv(e){return fv(Uv,e)}const Dv=J("ZodISODuration",(e,t)=>{c1.init(e,t),Ue.init(e,t)});function Zv(e){return hv(Dv,e)}const go=J("ZodError",(e,t)=>{Wc.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ng(e,r)},flatten:{value:r=>rg(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}),Fv=og(go),Vv=sg(go),Hv=Yc(go),_a=Xc(go),Ae=J("ZodType",(e,t)=>(Oe.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)=>kr(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Fv(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Hv(e,r,n),e.parseAsync=async(r,n)=>Vv(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>_a(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(A_(r,n)),e.superRefine=r=>e.check(q_(r)),e.overwrite=r=>e.check(Tn(r)),e.optional=()=>K(e),e.nullable=()=>Du(e),e.nullish=()=>K(Du(e)),e.nonoptional=r=>E_(e,r),e.array=()=>A(e),e.or=r=>ne([e,r]),e.and=r=>ba(e,r),e.transform=r=>Sa(e,Uu(r)),e.default=r=>C_(e,r),e.prefault=r=>$_(e,r),e.catch=r=>x_(e,r),e.pipe=r=>Sa(e,r),e.readonly=()=>O_(e),e.describe=r=>{const n=e.clone();return Cn.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Cn.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Cn.get(e);const n=e.clone();return Cn.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Pu=J("_ZodString",(e,t)=>{ha.init(e,t),Ae.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(Sv(...n)),e.includes=(...n)=>e.check($v(...n)),e.startsWith=(...n)=>e.check(Ev(...n)),e.endsWith=(...n)=>e.check(Iv(...n)),e.min=(...n)=>e.check(mo(...n)),e.max=(...n)=>e.check($u(...n)),e.length=(...n)=>e.check(Eu(...n)),e.nonempty=(...n)=>e.check(mo(1,...n)),e.lowercase=n=>e.check(Cv(n)),e.uppercase=n=>e.check(Tv(n)),e.trim=()=>e.check(Rv()),e.normalize=(...n)=>e.check(xv(...n)),e.toLowerCase=()=>e.check(Pv()),e.toUpperCase=()=>e.check(Ov())}),Bv=J("ZodString",(e,t)=>{ha.init(e,t),Pu.init(e,t),e.email=r=>e.check(B1(Jv,r)),e.url=r=>e.check(bu(Mu,r)),e.jwt=r=>e.check(uv(l_,r)),e.emoji=r=>e.check(Y1(Wv,r)),e.guid=r=>e.check(wu(Ou,r)),e.uuid=r=>e.check(J1(vo,r)),e.uuidv4=r=>e.check(G1(vo,r)),e.uuidv6=r=>e.check(W1(vo,r)),e.uuidv7=r=>e.check(K1(vo,r)),e.nanoid=r=>e.check(Q1(Kv,r)),e.guid=r=>e.check(wu(Ou,r)),e.cuid=r=>e.check(X1(Yv,r)),e.cuid2=r=>e.check(ev(Qv,r)),e.ulid=r=>e.check(tv(Xv,r)),e.base64=r=>e.check(ku(Nu,r)),e.base64url=r=>e.check(lv(a_,r)),e.xid=r=>e.check(rv(e_,r)),e.ksuid=r=>e.check(nv(t_,r)),e.ipv4=r=>e.check(ov(r_,r)),e.ipv6=r=>e.check(sv(n_,r)),e.cidrv4=r=>e.check(av(o_,r)),e.cidrv6=r=>e.check(iv(s_,r)),e.e164=r=>e.check(cv(i_,r)),e.datetime=r=>e.check(Ru(r)),e.date=r=>e.check(jv(r)),e.time=r=>e.check(zv(r)),e.duration=r=>e.check(Zv(r))});function v(e){return H1(Bv,e)}const Ue=J("ZodStringFormat",(e,t)=>{Le.init(e,t),Pu.init(e,t)}),Jv=J("ZodEmail",(e,t)=>{Yg.init(e,t),Ue.init(e,t)}),Ou=J("ZodGUID",(e,t)=>{Wg.init(e,t),Ue.init(e,t)}),vo=J("ZodUUID",(e,t)=>{Kg.init(e,t),Ue.init(e,t)}),Mu=J("ZodURL",(e,t)=>{Qg.init(e,t),Ue.init(e,t)});function Gv(e){return bu(Mu,e)}const Wv=J("ZodEmoji",(e,t)=>{Xg.init(e,t),Ue.init(e,t)}),Kv=J("ZodNanoID",(e,t)=>{e1.init(e,t),Ue.init(e,t)}),Yv=J("ZodCUID",(e,t)=>{t1.init(e,t),Ue.init(e,t)}),Qv=J("ZodCUID2",(e,t)=>{r1.init(e,t),Ue.init(e,t)}),Xv=J("ZodULID",(e,t)=>{n1.init(e,t),Ue.init(e,t)}),e_=J("ZodXID",(e,t)=>{o1.init(e,t),Ue.init(e,t)}),t_=J("ZodKSUID",(e,t)=>{s1.init(e,t),Ue.init(e,t)}),r_=J("ZodIPv4",(e,t)=>{u1.init(e,t),Ue.init(e,t)}),n_=J("ZodIPv6",(e,t)=>{d1.init(e,t),Ue.init(e,t)}),o_=J("ZodCIDRv4",(e,t)=>{p1.init(e,t),Ue.init(e,t)}),s_=J("ZodCIDRv6",(e,t)=>{f1.init(e,t),Ue.init(e,t)}),Nu=J("ZodBase64",(e,t)=>{h1.init(e,t),Ue.init(e,t)});function Au(e){return ku(Nu,e)}const a_=J("ZodBase64URL",(e,t)=>{g1.init(e,t),Ue.init(e,t)}),i_=J("ZodE164",(e,t)=>{v1.init(e,t),Ue.init(e,t)}),l_=J("ZodJWT",(e,t)=>{y1.init(e,t),Ue.init(e,t)}),ya=J("ZodNumber",(e,t)=>{lu.init(e,t),Ae.init(e,t),e.gt=(n,o)=>e.check(Cu(n,o)),e.gte=(n,o)=>e.check(va(n,o)),e.min=(n,o)=>e.check(va(n,o)),e.lt=(n,o)=>e.check(Su(n,o)),e.lte=(n,o)=>e.check(ga(n,o)),e.max=(n,o)=>e.check(ga(n,o)),e.int=n=>e.check(qu(n)),e.safe=n=>e.check(qu(n)),e.positive=n=>e.check(Cu(0,n)),e.nonnegative=n=>e.check(va(0,n)),e.negative=n=>e.check(Su(0,n)),e.nonpositive=n=>e.check(ga(0,n)),e.multipleOf=(n,o)=>e.check(Tu(n,o)),e.step=(n,o)=>e.check(Tu(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 q(e){return mv(ya,e)}const c_=J("ZodNumberFormat",(e,t)=>{w1.init(e,t),ya.init(e,t)});function qu(e){return vv(c_,e)}const u_=J("ZodBoolean",(e,t)=>{b1.init(e,t),Ae.init(e,t)});function ce(e){return _v(u_,e)}const d_=J("ZodNull",(e,t)=>{k1.init(e,t),Ae.init(e,t)});function wa(e){return yv(d_,e)}const p_=J("ZodAny",(e,t)=>{S1.init(e,t),Ae.init(e,t)});function et(){return wv(p_)}const f_=J("ZodUnknown",(e,t)=>{C1.init(e,t),Ae.init(e,t)});function $e(){return bv(f_)}const h_=J("ZodNever",(e,t)=>{T1.init(e,t),Ae.init(e,t)});function m_(e){return kv(h_,e)}const g_=J("ZodArray",(e,t)=>{$1.init(e,t),Ae.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(mo(r,n)),e.nonempty=r=>e.check(mo(1,r)),e.max=(r,n)=>e.check($u(r,n)),e.length=(r,n)=>e.check(Eu(r,n)),e.unwrap=()=>e.element});function A(e,t){return Mv(g_,e,t)}const Lu=J("ZodObject",(e,t)=>{E1.init(e,t),Ae.init(e,t),Te(e,"shape",()=>t.shape),e.keyof=()=>_e(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:m_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Q2(e,r),e.merge=r=>X2(e,r),e.pick=r=>K2(e,r),e.omit=r=>Y2(e,r),e.partial=(...r)=>eg(zu,e,r[0]),e.required=(...r)=>tg(Zu,e,r[0])});function T(e,t){const r={type:"object",get shape(){return lo(this,"shape",{...e}),this.shape},...re(t)};return new Lu(r)}function ze(e,t){return new Lu({type:"object",get shape(){return lo(this,"shape",{...e}),this.shape},catchall:$e(),...re(t)})}const ju=J("ZodUnion",(e,t)=>{pu.init(e,t),Ae.init(e,t),e.options=t.options});function ne(e,t){return new ju({type:"union",options:e,...re(t)})}const v_=J("ZodDiscriminatedUnion",(e,t)=>{ju.init(e,t),I1.init(e,t)});function Ze(e,t,r){return new v_({type:"union",options:t,discriminator:e,...re(r)})}const __=J("ZodIntersection",(e,t)=>{x1.init(e,t),Ae.init(e,t)});function ba(e,t){return new __({type:"intersection",left:e,right:t})}const y_=J("ZodRecord",(e,t)=>{R1.init(e,t),Ae.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ve(e,t,r){return new y_({type:"record",keyType:e,valueType:t,...re(r)})}const ka=J("ZodEnum",(e,t)=>{P1.init(e,t),Ae.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 ka({...t,checks:[],...re(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 ka({...t,checks:[],...re(o),entries:s})}});function _e(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new ka({type:"enum",entries:r,...re(t)})}const w_=J("ZodLiteral",(e,t)=>{O1.init(e,t),Ae.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 L(e,t){return new w_({type:"literal",values:Array.isArray(e)?e:[e],...re(t)})}const b_=J("ZodTransform",(e,t)=>{M1.init(e,t),Ae.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Sn(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(Sn(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Uu(e){return new b_({type:"transform",transform:e})}const zu=J("ZodOptional",(e,t)=>{N1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K(e){return new zu({type:"optional",innerType:e})}const k_=J("ZodNullable",(e,t)=>{A1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Du(e){return new k_({type:"nullable",innerType:e})}const S_=J("ZodDefault",(e,t)=>{q1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function C_(e,t){return new S_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const T_=J("ZodPrefault",(e,t)=>{L1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function $_(e,t){return new T_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Zu=J("ZodNonOptional",(e,t)=>{j1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType});function E_(e,t){return new Zu({type:"nonoptional",innerType:e,...re(t)})}const I_=J("ZodCatch",(e,t)=>{U1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function x_(e,t){return new I_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const R_=J("ZodPipe",(e,t)=>{z1.init(e,t),Ae.init(e,t),e.in=t.in,e.out=t.out});function Sa(e,t){return new R_({type:"pipe",in:e,out:t})}const P_=J("ZodReadonly",(e,t)=>{D1.init(e,t),Ae.init(e,t)});function O_(e){return new P_({type:"readonly",innerType:e})}const M_=J("ZodLazy",(e,t)=>{Z1.init(e,t),Ae.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Fu(e){return new M_({type:"lazy",getter:e})}const Ca=J("ZodCustom",(e,t)=>{F1.init(e,t),Ae.init(e,t)});function N_(e){const t=new it({check:"custom"});return t._zod.check=e,t}function Vu(e,t){return Nv(Ca,e??(()=>!0),t)}function A_(e,t={}){return Av(Ca,e,t)}function q_(e){const t=N_(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Sn(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(Sn(o))}},e(r.value,r)));return t}function _o(e,t={error:`Input not instance of ${e.name}`}){const r=new Ca({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...re(t)});return r._zod.bag.Class=e,r}function Hu(e,t){return Sa(Uu(e),t)}const Bu={custom:"custom"};function Ju(e){return gv(ya,e)}var Q;(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"})(Q||(Q={}));function Hr(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}async function L_(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(Gu());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(Gu())};r?.addEventListener("abort",i)})}function Gu(){return new DOMException("Delay was aborted","AbortError")}var yo=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 $n(e){return Object.fromEntries([...e.headers])}var En=({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 io({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},In=En();function Ta(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Cr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var j_=["fetch failed","failed to fetch"];function Wu({error:e,url:t,requestBodyValues:r}){if(Cr(e))return e;if(e instanceof TypeError&&j_.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Pe({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function xn(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 U_(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 cr(e,...t){const r=new Headers(U_(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var Ku="3.0.18",z_=()=>globalThis.fetch,Yu=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=z_()})=>{try{const a=await s(e,{method:"GET",headers:cr(t,`ai-sdk/provider-utils/${Ku}`,xn()),signal:o}),i=$n(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw Cr(c)||Pe.isInstance(c)?c:new Pe({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&&(Cr(l)||Pe.isInstance(l))?l:new Pe({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw Wu({error:a,url:e,requestBodyValues:{}})}};function D_({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 Z_({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ar({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ar({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 ar({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ar({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function wo({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var F_=/"__proto__"\s*:/,V_=/"constructor"\s*:/;function Qu(e){const t=JSON.parse(e);return t===null||typeof t!="object"||F_.test(e)===!1&&V_.test(e)===!1?t:H_(t)}function H_(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 $a(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Qu(e)}try{return Qu(e)}finally{Error.stackTraceLimit=t}}var bo=Symbol.for("vercel.ai.validator");function B_(e){return{[bo]:!0,validate:e}}function J_(e){return typeof e=="object"&&e!==null&&bo in e&&e[bo]===!0&&"validate"in e}function Br(e){let t;return()=>(t==null&&(t=e()),t)}function G_(e){return J_(e)?e:typeof e=="function"?e():W_(e)}function W_(e){return B_(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new At({value:t,cause:r.issues})}})}async function Ea({value:e,schema:t}){const r=await Tt({value:e,schema:t});if(!r.success)throw At.wrap({value:e,cause:r.error});return r.value}async function Tt({value:e,schema:t}){const r=G_(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:At.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:At.wrap({value:e,cause:n}),rawValue:e}}}async function K_({text:e,schema:t}){try{const r=$a(e);return t==null?r:Ea({value:r,schema:t})}catch(r){throw sr.isInstance(r)||At.isInstance(r)?r:new sr({text:e,cause:r})}}async function Tr({text:e,schema:t}){try{const r=$a(e);return t==null?{success:!0,value:r,rawValue:r}:await Tt({value:r,schema:t})}catch(r){return{success:!1,error:sr.isInstance(r)?r:new sr({text:e,cause:r}),rawValue:void 0}}}function Xu(e){try{return $a(e),!0}catch{return!1}}function Y_({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Tr({text:r,schema:t}))}}))}async function ed({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Tt({value:t[e],schema:r});if(!n.success)throw new io({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Q_=()=>globalThis.fetch,Jr=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>X_({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),X_=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=Q_()})=>{try{const i=await a(e,{method:"POST",headers:cr(t,`ai-sdk/provider-utils/${Ku}`,xn()),body:r.content,signal:s}),l=$n(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Cr(u)||Pe.isInstance(u)?u:new Pe({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&&(Cr(c)||Pe.isInstance(c))?c:new Pe({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw Wu({error:i,url:e,requestBodyValues:r.values})}};function vC(e){return e}function td(e){return{...e,type:"dynamic"}}async function qt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var $r=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=$n(n);if(a.trim()==="")return{responseHeaders:i,value:new Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await K_({text:a,schema:e});return{responseHeaders:i,value:new Pe({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 Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},rd=e=>async({response:t})=>{const r=$n(t);if(t.body==null)throw new fc({});return{responseHeaders:r,value:Y_({stream:t.body,schema:e})}},Gr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Tr({text:o,schema:e}),a=$n(t);if(!s.success)throw new Pe({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}},ey=(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("/")},ty=Symbol("Let zodToJsonSchema decide on which parser to use"),nd={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"},ry=e=>typeof e=="string"?{...nd,name:e}:{...nd,...e};function ht(){return{}}function ny(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)!==Q.ZodAny&&(s.items=Ee(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 oy(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 sy(){return{type:"boolean"}}function od(e,t){return Ee(e.type._def,t)}var ay=(e,t)=>Ee(e.innerType._def,t);function sd(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>sd(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 iy(e)}}var iy=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 ly(e,t){return{...Ee(e.innerType._def,t),default:e.defaultValue()}}function cy(e,t){return t.effectStrategy==="input"?Ee(e.schema._def,t):ht()}function uy(e){return{type:"string",enum:Array.from(e.values)}}var dy=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function py(e,t){const r=[Ee(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ee(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(dy(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 fy(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 Ia=void 0,$t={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:()=>(Ia===void 0&&(Ia=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ia),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 ad(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":Et(r,"email",n.message,t);break;case"format:idn-email":Et(r,"idn-email",n.message,t);break;case"pattern:zod":tt(r,$t.email,n.message,t);break}break;case"url":Et(r,"uri",n.message,t);break;case"uuid":Et(r,"uuid",n.message,t);break;case"regex":tt(r,n.regex,n.message,t);break;case"cuid":tt(r,$t.cuid,n.message,t);break;case"cuid2":tt(r,$t.cuid2,n.message,t);break;case"startsWith":tt(r,RegExp(`^${xa(n.value,t)}`),n.message,t);break;case"endsWith":tt(r,RegExp(`${xa(n.value,t)}$`),n.message,t);break;case"datetime":Et(r,"date-time",n.message,t);break;case"date":Et(r,"date",n.message,t);break;case"time":Et(r,"time",n.message,t);break;case"duration":Et(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":{tt(r,RegExp(xa(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Et(r,"ipv4",n.message,t),n.version!=="v4"&&Et(r,"ipv6",n.message,t);break}case"base64url":tt(r,$t.base64url,n.message,t);break;case"jwt":tt(r,$t.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&tt(r,$t.ipv4Cidr,n.message,t),n.version!=="v4"&&tt(r,$t.ipv6Cidr,n.message,t);break}case"emoji":tt(r,$t.emoji(),n.message,t);break;case"ulid":{tt(r,$t.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Et(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{tt(r,$t.base64,n.message,t);break}}break}case"nanoid":tt(r,$t.nanoid,n.message,t)}return r}function xa(e,t){return t.patternStrategy==="escape"?my(e):e}var hy=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function my(e){let t="";for(let r=0;r<e.length;r++)hy.has(e[r])||(t+="\\"),t+=e[r];return t}function Et(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 tt(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:id(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=id(t,n)}function id(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
+ 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]){i(u);continue}if(n.external){const p=n.external.registry.get(u[0])?.id;if(t!==u[0]&&p){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(m.cycle){i(u);continue}if(m.count>1&&n.reused==="ref"){i(u);continue}}const a=(u,m)=>{const f=this.seen.get(u),p=f.def??f.schema,h={...p};if(f.ref===null)return;const v=f.ref;if(f.ref=null,v){a(v,m);const _=this.seen.get(v).schema;_.$ref&&m.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(_)):(Object.assign(p,_),Object.assign(p,h))}f.isParent||this.override({zodSchema:u,jsonSchema:p,path:f.path??[]})};for(const u of[...this.seen.entries()].reverse())a(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 Jd(e,t){if(e instanceof Ld){const n=new Bd(t),o={};for(const a of e._idmap.entries()){const[l,c]=a;n.process(c)}const s={},i={registry:e,uri:t?.uri,defs:o};for(const a of e._idmap.entries()){const[l,c]=a;s[l]=n.emit(c,{...t,external:i})}if(Object.keys(o).length>0){const a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}const r=new Bd(t);return r.process(e),r.emit(e,t)}function Ze(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 Ze(o.element,r);case"object":{for(const s in o.shape)if(Ze(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(Ze(s,r))return!0;return!1}case"intersection":return Ze(o.left,r)||Ze(o.right,r);case"tuple":{for(const s of o.items)if(Ze(s,r))return!0;return!!(o.rest&&Ze(o.rest,r))}case"record":return Ze(o.keyType,r)||Ze(o.valueType,r);case"map":return Ze(o.keyType,r)||Ze(o.valueType,r);case"set":return Ze(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ze(o.innerType,r);case"lazy":return Ze(o.getter(),r);case"default":return Ze(o.innerType,r);case"prefault":return Ze(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ze(o.in,r)||Ze(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const Ow=J("ZodISODateTime",(e,t)=>{ry.init(e,t),je.init(e,t)});function Wd(e){return iw(Ow,e)}const Mw=J("ZodISODate",(e,t)=>{ny.init(e,t),je.init(e,t)});function Aw(e){return lw(Mw,e)}const Nw=J("ZodISOTime",(e,t)=>{oy.init(e,t),je.init(e,t)});function qw(e){return cw(Nw,e)}const Lw=J("ZodISODuration",(e,t)=>{sy.init(e,t),je.init(e,t)});function Uw(e){return uw(Lw,e)}const zo=J("ZodError",(e,t)=>{fd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>X_(e,r)},flatten:{value:r=>Q_(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}),jw=ev(zo),Dw=tv(zo),zw=gd(zo),si=_d(zo),Ne=J("ZodType",(e,t)=>(Me.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)=>Or(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>jw(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>zw(e,r,n),e.parseAsync=async(r,n)=>Dw(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>si(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(xb(r,n)),e.superRefine=r=>e.check(Pb(r)),e.overwrite=r=>e.check(Zn(r)),e.optional=()=>K(e),e.nullable=()=>ap(e),e.nullish=()=>K(ap(e)),e.nonoptional=r=>Sb(e,r),e.array=()=>R(e),e.or=r=>X([e,r]),e.and=r=>Fn(e,r),e.transform=r=>ci(e,op(r)),e.default=r=>yb(e,r),e.prefault=r=>bb(e,r),e.catch=r=>Cb(e,r),e.pipe=r=>ci(e,r),e.readonly=()=>Tb(e),e.describe=r=>{const n=e.clone();return zn.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return zn.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return zn.get(e);const n=e.clone();return zn.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Gd=J("_ZodString",(e,t)=>{ti.init(e,t),Ne.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(yw(...n)),e.includes=(...n)=>e.check(Sw(...n)),e.startsWith=(...n)=>e.check($w(...n)),e.endsWith=(...n)=>e.check(Cw(...n)),e.min=(...n)=>e.check(Do(...n)),e.max=(...n)=>e.check(Vd(...n)),e.length=(...n)=>e.check(Hd(...n)),e.nonempty=(...n)=>e.check(Do(1,...n)),e.lowercase=n=>e.check(ww(n)),e.uppercase=n=>e.check(bw(n)),e.trim=()=>e.check(Ew()),e.normalize=(...n)=>e.check(kw(...n)),e.toLowerCase=()=>e.check(Tw()),e.toUpperCase=()=>e.check(Iw())}),Zw=J("ZodString",(e,t)=>{ti.init(e,t),Gd.init(e,t),e.email=r=>e.check(Zy(Fw,r)),e.url=r=>e.check(jd(Yd,r)),e.jwt=r=>e.check(aw(nb,r)),e.emoji=r=>e.check(Jy(Vw,r)),e.guid=r=>e.check(Ud(Kd,r)),e.uuid=r=>e.check(Fy(Zo,r)),e.uuidv4=r=>e.check(Vy(Zo,r)),e.uuidv6=r=>e.check(Hy(Zo,r)),e.uuidv7=r=>e.check(By(Zo,r)),e.nanoid=r=>e.check(Wy(Hw,r)),e.guid=r=>e.check(Ud(Kd,r)),e.cuid=r=>e.check(Gy(Bw,r)),e.cuid2=r=>e.check(Ky(Jw,r)),e.ulid=r=>e.check(Yy(Ww,r)),e.base64=r=>e.check(Dd(Xd,r)),e.base64url=r=>e.check(ow(tb,r)),e.xid=r=>e.check(Qy(Gw,r)),e.ksuid=r=>e.check(Xy(Kw,r)),e.ipv4=r=>e.check(ew(Yw,r)),e.ipv6=r=>e.check(tw(Qw,r)),e.cidrv4=r=>e.check(rw(Xw,r)),e.cidrv6=r=>e.check(nw(eb,r)),e.e164=r=>e.check(sw(rb,r)),e.datetime=r=>e.check(Wd(r)),e.date=r=>e.check(Aw(r)),e.time=r=>e.check(qw(r)),e.duration=r=>e.check(Uw(r))});function d(e){return zy(Zw,e)}const je=J("ZodStringFormat",(e,t)=>{Le.init(e,t),Gd.init(e,t)}),Fw=J("ZodEmail",(e,t)=>{Jv.init(e,t),je.init(e,t)}),Kd=J("ZodGUID",(e,t)=>{Hv.init(e,t),je.init(e,t)}),Zo=J("ZodUUID",(e,t)=>{Bv.init(e,t),je.init(e,t)}),Yd=J("ZodURL",(e,t)=>{Wv.init(e,t),je.init(e,t)});function Qd(e){return jd(Yd,e)}const Vw=J("ZodEmoji",(e,t)=>{Gv.init(e,t),je.init(e,t)}),Hw=J("ZodNanoID",(e,t)=>{Kv.init(e,t),je.init(e,t)}),Bw=J("ZodCUID",(e,t)=>{Yv.init(e,t),je.init(e,t)}),Jw=J("ZodCUID2",(e,t)=>{Qv.init(e,t),je.init(e,t)}),Ww=J("ZodULID",(e,t)=>{Xv.init(e,t),je.init(e,t)}),Gw=J("ZodXID",(e,t)=>{ey.init(e,t),je.init(e,t)}),Kw=J("ZodKSUID",(e,t)=>{ty.init(e,t),je.init(e,t)}),Yw=J("ZodIPv4",(e,t)=>{ay.init(e,t),je.init(e,t)}),Qw=J("ZodIPv6",(e,t)=>{iy.init(e,t),je.init(e,t)}),Xw=J("ZodCIDRv4",(e,t)=>{ly.init(e,t),je.init(e,t)}),eb=J("ZodCIDRv6",(e,t)=>{cy.init(e,t),je.init(e,t)}),Xd=J("ZodBase64",(e,t)=>{uy.init(e,t),je.init(e,t)});function ep(e){return Dd(Xd,e)}const tb=J("ZodBase64URL",(e,t)=>{py.init(e,t),je.init(e,t)}),rb=J("ZodE164",(e,t)=>{hy.init(e,t),je.init(e,t)}),nb=J("ZodJWT",(e,t)=>{my.init(e,t),je.init(e,t)}),ai=J("ZodNumber",(e,t)=>{Ed.init(e,t),Ne.init(e,t),e.gt=(n,o)=>e.check(Zd(n,o)),e.gte=(n,o)=>e.check(oi(n,o)),e.min=(n,o)=>e.check(oi(n,o)),e.lt=(n,o)=>e.check(zd(n,o)),e.lte=(n,o)=>e.check(ni(n,o)),e.max=(n,o)=>e.check(ni(n,o)),e.int=n=>e.check(tp(n)),e.safe=n=>e.check(tp(n)),e.positive=n=>e.check(Zd(0,n)),e.nonnegative=n=>e.check(oi(0,n)),e.negative=n=>e.check(zd(0,n)),e.nonpositive=n=>e.check(ni(0,n)),e.multipleOf=(n,o)=>e.check(Fd(n,o)),e.step=(n,o)=>e.check(Fd(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 A(e){return dw(ai,e)}const ob=J("ZodNumberFormat",(e,t)=>{gy.init(e,t),ai.init(e,t)});function tp(e){return hw(ob,e)}const sb=J("ZodBoolean",(e,t)=>{_y.init(e,t),Ne.init(e,t)});function te(e){return fw(sb,e)}const ab=J("ZodNull",(e,t)=>{vy.init(e,t),Ne.init(e,t)});function ii(e){return mw(ab,e)}const ib=J("ZodAny",(e,t)=>{yy.init(e,t),Ne.init(e,t)});function tt(){return gw(ib)}const lb=J("ZodUnknown",(e,t)=>{wy.init(e,t),Ne.init(e,t)});function ce(){return _w(lb)}const cb=J("ZodNever",(e,t)=>{by.init(e,t),Ne.init(e,t)});function ub(e){return vw(cb,e)}const db=J("ZodArray",(e,t)=>{Sy.init(e,t),Ne.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Do(r,n)),e.nonempty=r=>e.check(Do(1,r)),e.max=(r,n)=>e.check(Vd(r,n)),e.length=(r,n)=>e.check(Hd(r,n)),e.unwrap=()=>e.element});function R(e,t){return Rw(db,e,t)}const rp=J("ZodObject",(e,t)=>{$y.init(e,t),Ne.init(e,t),Te(e,"shape",()=>t.shape),e.keyof=()=>_e(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ce()}),e.loose=()=>e.clone({...e._zod.def,catchall:ce()}),e.strict=()=>e.clone({...e._zod.def,catchall:ub()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>W_(e,r),e.merge=r=>G_(e,r),e.pick=r=>B_(e,r),e.omit=r=>J_(e,r),e.partial=(...r)=>K_(sp,e,r[0]),e.required=(...r)=>Y_(ip,e,r[0])});function C(e,t){const r={type:"object",get shape(){return Ao(this,"shape",{...e}),this.shape},...se(t)};return new rp(r)}function Ce(e,t){return new rp({type:"object",get shape(){return Ao(this,"shape",{...e}),this.shape},catchall:ce(),...se(t)})}const np=J("ZodUnion",(e,t)=>{xd.init(e,t),Ne.init(e,t),e.options=t.options});function X(e,t){return new np({type:"union",options:e,...se(t)})}const pb=J("ZodDiscriminatedUnion",(e,t)=>{np.init(e,t),Cy.init(e,t)});function De(e,t,r){return new pb({type:"union",options:t,discriminator:e,...se(r)})}const hb=J("ZodIntersection",(e,t)=>{ky.init(e,t),Ne.init(e,t)});function Fn(e,t){return new hb({type:"intersection",left:e,right:t})}const fb=J("ZodRecord",(e,t)=>{Ey.init(e,t),Ne.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function oe(e,t,r){return new fb({type:"record",keyType:e,valueType:t,...se(r)})}const li=J("ZodEnum",(e,t)=>{Ty.init(e,t),Ne.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 i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new li({...t,checks:[],...se(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new li({...t,checks:[],...se(o),entries:s})}});function _e(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new li({type:"enum",entries:r,...se(t)})}const mb=J("ZodLiteral",(e,t)=>{Iy.init(e,t),Ne.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 O(e,t){return new mb({type:"literal",values:Array.isArray(e)?e:[e],...se(t)})}const gb=J("ZodTransform",(e,t)=>{Ry.init(e,t),Ne.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Dn(s,r.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(Dn(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function op(e){return new gb({type:"transform",transform:e})}const sp=J("ZodOptional",(e,t)=>{xy.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K(e){return new sp({type:"optional",innerType:e})}const _b=J("ZodNullable",(e,t)=>{Py.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ap(e){return new _b({type:"nullable",innerType:e})}const vb=J("ZodDefault",(e,t)=>{Oy.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function yb(e,t){return new vb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const wb=J("ZodPrefault",(e,t)=>{My.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function bb(e,t){return new wb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ip=J("ZodNonOptional",(e,t)=>{Ay.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Sb(e,t){return new ip({type:"nonoptional",innerType:e,...se(t)})}const $b=J("ZodCatch",(e,t)=>{Ny.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Cb(e,t){return new $b({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const kb=J("ZodPipe",(e,t)=>{qy.init(e,t),Ne.init(e,t),e.in=t.in,e.out=t.out});function ci(e,t){return new kb({type:"pipe",in:e,out:t})}const Eb=J("ZodReadonly",(e,t)=>{Ly.init(e,t),Ne.init(e,t)});function Tb(e){return new Eb({type:"readonly",innerType:e})}const Ib=J("ZodLazy",(e,t)=>{Uy.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.getter()});function lp(e){return new Ib({type:"lazy",getter:e})}const ui=J("ZodCustom",(e,t)=>{jy.init(e,t),Ne.init(e,t)});function Rb(e){const t=new dt({check:"custom"});return t._zod.check=e,t}function di(e,t){return xw(ui,e??(()=>!0),t)}function xb(e,t={}){return Pw(ui,e,t)}function Pb(e){const t=Rb(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Dn(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(Dn(o))}},e(r.value,r)));return t}function Fo(e,t={error:`Input not instance of ${e.name}`}){const r=new ui({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...se(t)});return r._zod.bag.Class=e,r}function pi(e,t){return ci(op(e),t)}const hi={custom:"custom"};function cp(e){return pw(ai,e)}var Q;(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"})(Q||(Q={}));function tn(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}async function Ob(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(up());return}const s=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(s),r?.removeEventListener("abort",a)},a=()=>{i(),o(up())};r?.addEventListener("abort",a)})}function up(){return new DOMException("Delay was aborted","AbortError")}var Vo=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 Vn(e){return Object.fromEntries([...e.headers])}var Hn=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,i=new Array(t);for(let a=0;a<t;a++)i[a]=r[Math.random()*s|0];return i.join("")};if(e==null)return o;if(r.includes(n))throw new Lu({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Bn=Hn();function fi(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Ar(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Mb=["fetch failed","failed to fetch"];function dp({error:e,url:t,requestBodyValues:r}){if(Ar(e))return e;if(e instanceof TypeError&&Mb.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ot({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function Jn(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 Ab(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 vr(e,...t){const r=new Headers(Ab(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var pp="3.0.18",Nb=()=>globalThis.fetch,hp=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=Nb()})=>{try{const i=await s(e,{method:"GET",headers:vr(t,`ai-sdk/provider-utils/${pp}`,Jn()),signal:o}),a=Vn(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw Ar(c)||ot.isInstance(c)?c:new ot({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Ar(l)||ot.isInstance(l))?l:new ot({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}}catch(i){throw dp({error:i,url:e,requestBodyValues:{}})}};function qb({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 Lb({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Mo({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Mo({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 Mo({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Mo({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Ho({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}var Ub=/"__proto__"\s*:/,jb=/"constructor"\s*:/;function fp(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Ub.test(e)===!1&&jb.test(e)===!1?t:Db(t)}function Db(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 mi(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return fp(e)}try{return fp(e)}finally{Error.stackTraceLimit=t}}var Bo=Symbol.for("vercel.ai.validator");function zb(e){return{[Bo]:!0,validate:e}}function Zb(e){return typeof e=="object"&&e!==null&&Bo in e&&e[Bo]===!0&&"validate"in e}function rn(e){let t;return()=>(t==null&&(t=e()),t)}function Fb(e){return Zb(e)?e:typeof e=="function"?e():Vb(e)}function Vb(e){return zb(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Nn({value:t,cause:r.issues})}})}async function gi({value:e,schema:t}){const r=await Pt({value:e,schema:t});if(!r.success)throw Nn.wrap({value:e,cause:r.error});return r.value}async function Pt({value:e,schema:t}){const r=Fb(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:Nn.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Nn.wrap({value:e,cause:n}),rawValue:e}}}async function Hb({text:e,schema:t}){try{const r=mi(e);return t==null?r:gi({value:r,schema:t})}catch(r){throw Oo.isInstance(r)||Nn.isInstance(r)?r:new Oo({text:e,cause:r})}}async function Nr({text:e,schema:t}){try{const r=mi(e);return t==null?{success:!0,value:r,rawValue:r}:await Pt({value:r,schema:t})}catch(r){return{success:!1,error:Oo.isInstance(r)?r:new Oo({text:e,cause:r}),rawValue:void 0}}}function mp(e){try{return mi(e),!0}catch{return!1}}function Bb({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Pr).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Nr({text:r,schema:t}))}}))}async function gp({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Pt({value:t[e],schema:r});if(!n.success)throw new Lu({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Jb=()=>globalThis.fetch,nn=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Wb({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Wb=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=Jb()})=>{try{const a=await i(e,{method:"POST",headers:vr(t,`ai-sdk/provider-utils/${pp}`,Jn()),body:r.content,signal:s}),l=Vn(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw Ar(u)||ot.isInstance(u)?u:new ot({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:a,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Ar(c)||ot.isInstance(c))?c:new ot({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw dp({error:a,url:e,requestBodyValues:r.values})}};function qR(e){return e}function _p(e){return{...e,type:"dynamic"}}async function Jt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var qr=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=Vn(n);if(i.trim()==="")return{responseHeaders:a,value:new ot({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await Hb({text:i,schema:e});return{responseHeaders:a,value:new ot({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:a,value:new ot({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},vp=e=>async({response:t})=>{const r=Vn(t);if(t.body==null)throw new R_({});return{responseHeaders:r,value:Bb({stream:t.body,schema:e})}},on=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Nr({text:o,schema:e}),i=Vn(t);if(!s.success)throw new ot({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}},Gb=(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("/")},Kb=Symbol("Let zodToJsonSchema decide on which parser to use"),yp={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"},Yb=e=>typeof e=="string"?{...yp,name:e}:{...yp,...e};function _t(){return{}}function Qb(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)!==Q.ZodAny&&(s.items=Ie(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 Xb(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 e3(){return{type:"boolean"}}function wp(e,t){return Ie(e.type._def,t)}var t3=(e,t)=>Ie(e.innerType._def,t);function bp(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>bp(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 r3(e)}}var r3=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 n3(e,t){return{...Ie(e.innerType._def,t),default:e.defaultValue()}}function o3(e,t){return t.effectStrategy==="input"?Ie(e.schema._def,t):_t()}function s3(e){return{type:"string",enum:Array.from(e.values)}}var a3=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function i3(e,t){const r=[Ie(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ie(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(a3(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...a}=o;s=a}n.push(s)}}),n.length?{allOf:n}:void 0}function l3(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 _i=void 0,Ot={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(_i===void 0&&(_i=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_i),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 Sp(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":Mt(r,"email",n.message,t);break;case"format:idn-email":Mt(r,"idn-email",n.message,t);break;case"pattern:zod":st(r,Ot.email,n.message,t);break}break;case"url":Mt(r,"uri",n.message,t);break;case"uuid":Mt(r,"uuid",n.message,t);break;case"regex":st(r,n.regex,n.message,t);break;case"cuid":st(r,Ot.cuid,n.message,t);break;case"cuid2":st(r,Ot.cuid2,n.message,t);break;case"startsWith":st(r,RegExp(`^${vi(n.value,t)}`),n.message,t);break;case"endsWith":st(r,RegExp(`${vi(n.value,t)}$`),n.message,t);break;case"datetime":Mt(r,"date-time",n.message,t);break;case"date":Mt(r,"date",n.message,t);break;case"time":Mt(r,"time",n.message,t);break;case"duration":Mt(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":{st(r,RegExp(vi(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Mt(r,"ipv4",n.message,t),n.version!=="v4"&&Mt(r,"ipv6",n.message,t);break}case"base64url":st(r,Ot.base64url,n.message,t);break;case"jwt":st(r,Ot.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&st(r,Ot.ipv4Cidr,n.message,t),n.version!=="v4"&&st(r,Ot.ipv6Cidr,n.message,t);break}case"emoji":st(r,Ot.emoji(),n.message,t);break;case"ulid":{st(r,Ot.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Mt(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{st(r,Ot.base64,n.message,t);break}}break}case"nanoid":st(r,Ot.nanoid,n.message,t)}return r}function vi(e,t){return t.patternStrategy==="escape"?u3(e):e}var c3=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function u3(e){let t="";for(let r=0;r<e.length;r++)c3.has(e[r])||(t+="\\"),t+=e[r];return t}function Mt(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 st(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:$p(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=$p(t,n)}function $p(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="",i=!1,a=!1,l=!1;for(let c=0;c<o.length;c++){if(i){s+=o[c],i=!1;continue}if(n.i){if(a){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
- ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
36
+ ]))`;continue}}if(n.s&&o[c]==="."){s+=a?`${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 ld(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Q.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=ad(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Q.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=od(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function gy(e,t){if(t.mapStrategy==="record")return ld(e,t);const r=Ee(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ht(),n=Ee(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ht();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function vy(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 _y(){return{not:ht()}}function yy(){return{type:"null"}}var Ra={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function wy(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ra&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Ra[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 by(e,t)}var by=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ee(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 ky(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ra[e.innerType._def.typeName],"null"]};const r=Ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Sy(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 Cy(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=$y(i),c=Ee(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=Ty(e,t);return s!==void 0&&(r.additionalProperties=s),r}function Ty(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ee(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function $y(e){try{return e.isOptional()}catch{return!0}}var Ey=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ee(e.innerType._def,t);const n=Ee(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ht()},n]}:ht()},Iy=(e,t)=>{if(t.pipeStrategy==="input")return Ee(e.in._def,t);if(t.pipeStrategy==="output")return Ee(e.out._def,t);const r=Ee(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ee(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function xy(e,t){return Ee(e.type._def,t)}function Ry(e,t){const n={type:"array",uniqueItems:!0,items:Ee(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 Py(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ee(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ee(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ee(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Oy(){return{not:ht()}}function My(){return ht()}var Ny=(e,t)=>Ee(e.innerType._def,t),Ay=(e,t,r)=>{switch(t){case Q.ZodString:return ad(e,r);case Q.ZodNumber:return Sy(e);case Q.ZodObject:return Cy(e,r);case Q.ZodBigInt:return oy(e);case Q.ZodBoolean:return sy();case Q.ZodDate:return sd(e,r);case Q.ZodUndefined:return Oy();case Q.ZodNull:return yy();case Q.ZodArray:return ny(e,r);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return wy(e,r);case Q.ZodIntersection:return py(e,r);case Q.ZodTuple:return Py(e,r);case Q.ZodRecord:return ld(e,r);case Q.ZodLiteral:return fy(e);case Q.ZodEnum:return uy(e);case Q.ZodNativeEnum:return vy(e);case Q.ZodNullable:return ky(e,r);case Q.ZodOptional:return Ey(e,r);case Q.ZodMap:return gy(e,r);case Q.ZodSet:return Ry(e,r);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return xy(e,r);case Q.ZodNaN:case Q.ZodNever:return _y();case Q.ZodEffects:return cy(e,r);case Q.ZodAny:return ht();case Q.ZodUnknown:return My();case Q.ZodDefault:return ly(e,r);case Q.ZodBranded:return od(e,r);case Q.ZodReadonly:return Ny(e,r);case Q.ZodCatch:return ay(e,r);case Q.ZodPipeline:return Iy(e,r);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(n=>{})()}};function Ee(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!==ty)return l}if(o&&!r){const l=qy(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=Ay(e,e.typeName,t),i=typeof a=="function"?Ee(a(),t):a;if(i&&Ly(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var qy=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ey(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`),ht()):t.$refStrategy==="seen"?ht():void 0}},Ly=(e,t,r)=>(e.description&&(r.description=e.description),r),jy=e=>{const t=ry(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}]))}},Uy=(e,t)=>{var r;const n=jy(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,g])=>{var h;return{...c,[u]:(h=Ee(g._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:ht()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Ee(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:ht(),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},zy=Uy;function Dy(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rn(()=>zy(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 Zy(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rn(()=>xu(e,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async o=>{const s=await _a(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Fy(e){return"_zod"in e}function Er(e,t){return Fy(e)?Zy(e):Dy(e)}var Pa=Symbol.for("vercel.ai.schema");function Rn(e,{validate:t}={}){return{[Pa]:!0,_type:void 0,[bo]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Vy(e){return typeof e=="object"&&e!==null&&Pa in e&&e[Pa]===!0&&"jsonSchema"in e&&"validate"in e}function ko(e){return e==null?Rn({properties:{},additionalProperties:!1}):Vy(e)?e:typeof e=="function"?e():Er(e)}var{btoa:Hy,atob:By}=globalThis;function Oa(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=By(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function So(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return Hy(t)}function Jy(e){return e instanceof Uint8Array?So(e):e}function cd(e){return e?.replace(/\/$/,"")}function Gy(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*ud({execute:e,input:t,options:r}){const n=e(t,r);if(Gy(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 dd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ma,pd;function Wy(){if(pd)return Ma;pd=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,g)=>{for(var h in g)e(u,h,{get:g[h],enumerable:!0})},s=(u,g,h,d)=>{if(g&&typeof g=="object"||typeof g=="function")for(let p of r(g))!n.call(u,p)&&p!==h&&e(u,p,{get:()=>g[p],enumerable:!(d=t(g,p))||d.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Ma=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Ma}var Na,fd;function Ky(){if(fd)return Na;fd=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(g,h)=>{for(var d in h)e(g,d,{get:h[d],enumerable:!0})},s=(g,h,d,p)=>{if(h&&typeof h=="object"||typeof h=="function")for(let w of r(h))!n.call(g,w)&&w!==d&&e(g,w,{get:()=>h[w],enumerable:!(p=t(h,w))||p.enumerable});return g},a=g=>s(e({},"__esModule",{value:!0}),g),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Na=a(i);var l=Wy();async function c(){return""}function u(){return""}return Na}var hd=Ky(),Yy="vercel.ai.gateway.error",Aa=Symbol.for(Yy),md,gd,mt=class $2 extends(gd=Error,md=Aa,gd){constructor({message:t,statusCode:r=500,cause:n}){super(t),this[md]=!0,this.statusCode=r,this.cause=n}static isInstance(t){return $2.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Aa in t&&t[Aa]===!0}},vd="GatewayAuthenticationError",Qy=`vercel.ai.gateway.error.${vd}`,_d=Symbol.for(Qy),yd,wd,qa=class E2 extends(wd=mt,yd=_d,wd){constructor({message:t="Authentication failed",statusCode:r=401,cause:n}={}){super({message:t,statusCode:r,cause:n}),this[yd]=!0,this.name=vd,this.type="authentication_error"}static isInstance(t){return mt.hasMarker(t)&&_d in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
38
+ ]`;continue}s+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!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 Cp(e,t){var r,n,o,s,i,a;const l={type:"object",additionalProperties:(r=Ie(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Q.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Sp(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Q.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=wp(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function d3(e,t){if(t.mapStrategy==="record")return Cp(e,t);const r=Ie(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||_t(),n=Ie(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||_t();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function p3(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 h3(){return{not:_t()}}function f3(){return{type:"null"}}var yi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function m3(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 i=yi[s._def.typeName];return i&&!o.includes(i)?[...o,i]: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 i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];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,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._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 g3(e,t)}var g3=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ie(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 _3(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=Ie(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function v3(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 y3(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const i in o){let a=o[i];if(a===void 0||a._def===void 0)continue;const l=b3(a),c=Ie(a._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,l||n.push(i))}n.length&&(r.required=n);const s=w3(e,t);return s!==void 0&&(r.additionalProperties=s),r}function w3(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ie(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 b3(e){try{return e.isOptional()}catch{return!0}}var S3=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ie(e.innerType._def,t);const n=Ie(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:_t()},n]}:_t()},$3=(e,t)=>{if(t.pipeStrategy==="input")return Ie(e.in._def,t);if(t.pipeStrategy==="output")return Ie(e.out._def,t);const r=Ie(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ie(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function C3(e,t){return Ie(e.type._def,t)}function k3(e,t){const n={type:"array",uniqueItems:!0,items:Ie(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 E3(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ie(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ie(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ie(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function T3(){return{not:_t()}}function I3(){return _t()}var R3=(e,t)=>Ie(e.innerType._def,t),x3=(e,t,r)=>{switch(t){case Q.ZodString:return Sp(e,r);case Q.ZodNumber:return v3(e);case Q.ZodObject:return y3(e,r);case Q.ZodBigInt:return Xb(e);case Q.ZodBoolean:return e3();case Q.ZodDate:return bp(e,r);case Q.ZodUndefined:return T3();case Q.ZodNull:return f3();case Q.ZodArray:return Qb(e,r);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return m3(e,r);case Q.ZodIntersection:return i3(e,r);case Q.ZodTuple:return E3(e,r);case Q.ZodRecord:return Cp(e,r);case Q.ZodLiteral:return l3(e);case Q.ZodEnum:return s3(e);case Q.ZodNativeEnum:return p3(e);case Q.ZodNullable:return _3(e,r);case Q.ZodOptional:return S3(e,r);case Q.ZodMap:return d3(e,r);case Q.ZodSet:return k3(e,r);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return C3(e,r);case Q.ZodNaN:case Q.ZodNever:return h3();case Q.ZodEffects:return o3(e,r);case Q.ZodAny:return _t();case Q.ZodUnknown:return I3();case Q.ZodDefault:return n3(e,r);case Q.ZodBranded:return wp(e,r);case Q.ZodReadonly:return R3(e,r);case Q.ZodCatch:return t3(e,r);case Q.ZodPipeline:return $3(e,r);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(n=>{})()}};function Ie(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!==Kb)return l}if(o&&!r){const l=P3(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=x3(e,e.typeName,t),a=typeof i=="function"?Ie(i(),t):i;if(a&&O3(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var P3=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Gb(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`),_t()):t.$refStrategy==="seen"?_t():void 0}},O3=(e,t,r)=>(e.description&&(r.description=e.description),r),M3=e=>{const t=Yb(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}]))}},A3=(e,t)=>{var r;const n=M3(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,m])=>{var f;return{...c,[u]:(f=Ie(m._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?f:_t()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Ie(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:_t(),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a);const l=s===void 0?o?{...i,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},N3=A3;function q3(e,t){var r;const n=(r=void 0)!=null?r:!1;return Wn(()=>N3(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 L3(e,t){var r;const n=(r=void 0)!=null?r:!1;return Wn(()=>Jd(e,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async o=>{const s=await si(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function U3(e){return"_zod"in e}function Lr(e,t){return U3(e)?L3(e):q3(e)}var wi=Symbol.for("vercel.ai.schema");function Wn(e,{validate:t}={}){return{[wi]:!0,_type:void 0,[Bo]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function j3(e){return typeof e=="object"&&e!==null&&wi in e&&e[wi]===!0&&"jsonSchema"in e&&"validate"in e}function Jo(e){return e==null?Wn({properties:{},additionalProperties:!1}):j3(e)?e:typeof e=="function"?e():Lr(e)}var{btoa:D3,atob:z3}=globalThis;function bi(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=z3(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Wo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return D3(t)}function Z3(e){return e instanceof Uint8Array?Wo(e):e}function kp(e){return e?.replace(/\/$/,"")}function F3(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Ep({execute:e,input:t,options:r}){const n=e(t,r);if(F3(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 Si(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $i,Tp;function V3(){if(Tp)return $i;Tp=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,m)=>{for(var f in m)e(u,f,{get:m[f],enumerable:!0})},s=(u,m,f,p)=>{if(m&&typeof m=="object"||typeof m=="function")for(let h of r(m))!n.call(u,h)&&h!==f&&e(u,h,{get:()=>m[h],enumerable:!(p=t(m,h))||p.enumerable});return u},i=u=>s(e({},"__esModule",{value:!0}),u),a={};o(a,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),$i=i(a);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return $i}var Ci,Ip;function H3(){if(Ip)return Ci;Ip=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(m,f)=>{for(var p in f)e(m,p,{get:f[p],enumerable:!0})},s=(m,f,p,h)=>{if(f&&typeof f=="object"||typeof f=="function")for(let v of r(f))!n.call(m,v)&&v!==p&&e(m,v,{get:()=>f[v],enumerable:!(h=t(f,v))||h.enumerable});return m},i=m=>s(e({},"__esModule",{value:!0}),m),a={};o(a,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Ci=i(a);var l=V3();async function c(){return""}function u(){return""}return Ci}var Rp=H3(),B3="vercel.ai.gateway.error",ki=Symbol.for(B3),xp,Pp,vt=class b_ extends(Pp=Error,xp=ki,Pp){constructor({message:t,statusCode:r=500,cause:n}){super(t),this[xp]=!0,this.statusCode=r,this.cause=n}static isInstance(t){return b_.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&ki in t&&t[ki]===!0}},Op="GatewayAuthenticationError",J3=`vercel.ai.gateway.error.${Op}`,Mp=Symbol.for(J3),Ap,Np,Ei=class S_ extends(Np=vt,Ap=Mp,Np){constructor({message:t="Authentication failed",statusCode:r=401,cause:n}={}){super({message:t,statusCode:r,cause:n}),this[Ap]=!0,this.name=Op,this.type="authentication_error"}static isInstance(t){return vt.hasMarker(t)&&Mp in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s}){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
 
42
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?a=`AI Gateway authentication failed: Invalid OIDC token.
42
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:r?i=`AI Gateway authentication failed: Invalid OIDC token.
43
43
 
44
44
  Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
45
45
 
46
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
46
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:i=`AI Gateway authentication failed: No authentication provided.
47
47
 
48
48
  Option 1 - API key:
49
49
  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 E2({message:a,statusCode:o,cause:s})}},bd="GatewayInvalidRequestError",Xy=`vercel.ai.gateway.error.${bd}`,kd=Symbol.for(Xy),Sd,Cd,ew=class extends(Cd=mt,Sd=kd,Cd){constructor({message:e="Invalid request",statusCode:t=400,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Sd]=!0,this.name=bd,this.type="invalid_request_error"}static isInstance(e){return mt.hasMarker(e)&&kd in e}},Td="GatewayRateLimitError",tw=`vercel.ai.gateway.error.${Td}`,$d=Symbol.for(tw),Ed,Id,rw=class extends(Id=mt,Ed=$d,Id){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Ed]=!0,this.name=Td,this.type="rate_limit_exceeded"}static isInstance(e){return mt.hasMarker(e)&&$d in e}},xd="GatewayModelNotFoundError",nw=`vercel.ai.gateway.error.${xd}`,Rd=Symbol.for(nw),ow=Br(()=>Er(T({modelId:v()}))),Pd,Od,Md=class extends(Od=mt,Pd=Rd,Od){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Pd]=!0,this.name=xd,this.type="model_not_found",this.modelId=r}static isInstance(e){return mt.hasMarker(e)&&Rd in e}},Nd="GatewayInternalServerError",sw=`vercel.ai.gateway.error.${Nd}`,Ad=Symbol.for(sw),qd,Ld,jd=class extends(Ld=mt,qd=Ad,Ld){constructor({message:e="Internal server error",statusCode:t=500,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[qd]=!0,this.name=Nd,this.type="internal_server_error"}static isInstance(e){return mt.hasMarker(e)&&Ad in e}},Ud="GatewayResponseError",aw=`vercel.ai.gateway.error.${Ud}`,zd=Symbol.for(aw),Dd,Zd,iw=class extends(Zd=mt,Dd=zd,Zd){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[Dd]=!0,this.name=Ud,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return mt.hasMarker(e)&&zd in e}};async function Fd({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){const s=await Tt({value:e,schema:lw});if(!s.success)return new iw({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:s.error,cause:n});const a=s.value,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return qa.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n});case"invalid_request_error":return new ew({message:l,statusCode:t,cause:n});case"rate_limit_exceeded":return new rw({message:l,statusCode:t,cause:n});case"model_not_found":{const c=await Tt({value:a.error.param,schema:ow});return new Md({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new jd({message:l,statusCode:t,cause:n});default:return new jd({message:l,statusCode:t,cause:n})}}var lw=Br(()=>Er(T({error:T({message:v(),type:v().nullish(),param:$e().nullish(),code:ne([v(),q()]).nullish()})})));function ur(e,t){var r;return mt.isInstance(e)?e:Pe.isInstance(e)?Fd({response:cw(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):Fd({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function cw(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 Vd="ai-gateway-auth-method";async function Wr(e){const t=await Tt({value:e[Vd],schema:uw});return t.success?t.value:void 0}var uw=Br(()=>Er(ne([L("api-key"),L("oidc")]))),Hd=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Yu({url:`${this.config.baseURL}/config`,headers:await qt(this.config.headers()),successfulResponseHandler:Gr(dw),failedResponseHandler:$r({errorSchema:et(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await ur(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Yu({url:`${e.origin}/v1/credits`,headers:await qt(this.config.headers()),successfulResponseHandler:Gr(pw),failedResponseHandler:$r({errorSchema:et(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await ur(e)}}},dw=Br(()=>Er(T({models:A(T({id:v(),name:v(),description:v().nullish(),pricing:T({input:v(),output:v(),input_cache_read:v().nullish(),input_cache_write:v().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:L("v2"),provider:v(),modelId:v()}),modelType:_e(["language","embedding","image"]).nullish()}))}))),pw=Br(()=>Er(T({balance:v(),total_used:v()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),fw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...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 qt(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Jr({url:this.getUrl(),headers:Hr(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Gr(et()),failedResponseHandler:$r({errorSchema:et(),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 ur(s,await Wr(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await qt(this.config.headers());try{const{value:s,responseHeaders:a}=await Jr({url:this.getUrl(),headers:Hr(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await qt(this.config.o11yHeaders)),body:t,successfulResponseHandler:rd(et()),failedResponseHandler:$r({errorSchema:et(),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 ur(s,await Wr(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":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},hw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await qt(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Jr({url:this.getUrl(),headers:Hr(s,t??{},this.getModelConfigHeaders(),await qt(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Gr(mw),failedResponseHandler:$r({errorSchema:et(),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}}}catch(a){throw await ur(a,await Wr(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},mw=Br(()=>Er(T({embeddings:A(A(q())),usage:T({tokens:q()}).nullish(),providerMetadata:ve(v(),ve(v(),$e())).optional()}))),gw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l;const c=await qt(this.config.headers());try{const{responseHeaders:u,value:g,rawValue:h}=await Jr({url:this.getUrl(),headers:Hr(c,a??{},this.getModelConfigHeaders(),await qt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...s&&{providerOptions:s}},successfulResponseHandler:Gr(_w),failedResponseHandler:$r({errorSchema:et(),errorToMessage:d=>d}),...i&&{abortSignal:i},fetch:this.config.fetch});return{images:g.images,warnings:(l=g.warnings)!=null?l:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw ur(u,await Wr(c))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},vw=T({images:A($e()).optional()}).catchall($e()),_w=T({images:A(v()),warnings:A(T({type:L("other"),message:v()})).optional(),providerMetadata:ve(v(),vw).optional()});async function yw(){var e;return(e=hd.getContext().headers)==null?void 0:e["x-vercel-id"]}var ww="2.0.18",bw="0.0.1";function kw(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=cd(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const p=await Cw(e);if(p)return cr({Authorization:`Bearer ${p.token}`,"ai-gateway-protocol-version":bw,[Vd]:p.authMethod,...e.headers},`ai-sdk/gateway/${ww}`);throw qa.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const p=wo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),w=wo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=wo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const y=await yw();return{...p&&{"ai-o11y-deployment-id":p},...w&&{"ai-o11y-environment":w},...m&&{"ai-o11y-region":m},...y&&{"ai-o11y-request-id":y}}}},u=p=>new fw(p,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),g=async()=>{var p,w,m;const y=(m=(w=(p=e._internal)==null?void 0:p.currentDate)==null?void 0:w.call(p).getTime())!=null?m:Date.now();return(!n||y-a>s)&&(a=y,n=new Hd({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(_=>(o=_,_)).catch(async _=>{throw await ur(_,await Wr(await l()))})),o?Promise.resolve(o):n},h=async()=>new Hd({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async p=>{throw await ur(p,await Wr(await l()))}),d=function(p){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(p)};return d.getAvailableModels=g,d.getCredits=h,d.imageModel=p=>new gw(p,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),d.languageModel=u,d.textEmbeddingModel=p=>new hw(p,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),d}var Sw=kw();async function Cw(e){const t=wo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await hd.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var Tw=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Ir="1.9.0",Bd=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function $w(e){var t=new Set([e]),r=new Set,n=e.match(Bd);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(Bd);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 Ew=$w(Ir),Iw=Ir.split(".")[0],Pn=Symbol.for("opentelemetry.js.api."+Iw),On=Tw;function Mn(e,t,r,n){var o;n===void 0&&(n=!1);var s=On[Pn]=(o=On[Pn])!==null&&o!==void 0?o:{version:Ir};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!==Ir){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Ir);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Ir+"."),!0}function xr(e){var t,r,n=(t=On[Pn])===null||t===void 0?void 0:t.version;if(!(!n||!Ew(n)))return(r=On[Pn])===null||r===void 0?void 0:r[e]}function Nn(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Ir+".");var r=On[Pn];r&&delete r[e]}var xw=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},Rw=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))},Pw=(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 An("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return An("verbose",this._namespace,t)},e})();function An(e,t,r){var n=xr("diag");if(n)return r.unshift(t),n[e].apply(n,Rw([],xw(r),!1))}var gt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(gt||(gt={}));function Ow(e,t){e<gt.NONE?e=gt.NONE:e>gt.ALL&&(e=gt.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",gt.ERROR),warn:r("warn",gt.WARN),info:r("info",gt.INFO),debug:r("debug",gt.DEBUG),verbose:r("verbose",gt.VERBOSE)}}var Mw=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},Nw=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))},Aw="diag",Lt=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=xr("diag");if(i)return i[o].apply(i,Nw([],Mw(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:gt.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=xr("diag"),g=Ow((i=s.logLevel)!==null&&i!==void 0?i:gt.INFO,o);if(u&&!s.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+h),g.warn("Current logger will overwrite one already registered from "+h)}return Mn("diag",g,r,!0)};r.setLogger=n,r.disable=function(){Nn(Aw,r)},r.createComponentLogger=function(o){return new Pw(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})(),qw=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},Lw=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.")},jw=(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=qw(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=Lw(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})();Lt.instance();function Uw(e){return e===void 0&&(e={}),new jw(new Map(Object.entries(e)))}function Jd(e){return Symbol.for(e)}var zw=(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})(),Dw=new zw,Rr=(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)}})(),Zw=(function(){function e(){}return e.prototype.createGauge=function(t,r){return Qw},e.prototype.createHistogram=function(t,r){return Xw},e.prototype.createCounter=function(t,r){return Yw},e.prototype.createUpDownCounter=function(t,r){return e3},e.prototype.createObservableGauge=function(t,r){return r3},e.prototype.createObservableCounter=function(t,r){return t3},e.prototype.createObservableUpDownCounter=function(t,r){return n3},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Co=(function(){function e(){}return e})(),Fw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Co),Vw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Co),Hw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Co),Bw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Co),La=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Jw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(La),Gw=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(La),Ww=(function(e){Rr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(La),Kw=new Zw,Yw=new Fw,Qw=new Hw,Xw=new Bw,e3=new Vw,t3=new Jw,r3=new Gw,n3=new Ww,o3={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},s3={set:function(e,t,r){e!=null&&(e[t]=r)}},a3=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},i3=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))},l3=(function(){function e(){}return e.prototype.active=function(){return Dw},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,i3([n],a3(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),c3=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},u3=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))},ja="context",d3=new l3,To=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Mn(ja,t,Lt.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,u3([t,r,n],c3(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return xr(ja)||d3},e.prototype.disable=function(){this._getContextManager().disable(),Nn(ja,Lt.instance())},e})(),Ua;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ua||(Ua={}));var Gd="0000000000000000",Wd="00000000000000000000000000000000",p3={traceId:Wd,spanId:Gd,traceFlags:Ua.NONE},qn=(function(){function e(t){t===void 0&&(t=p3),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})(),za=Jd("OpenTelemetry Context Key SPAN");function Da(e){return e.getValue(za)||void 0}function f3(){return Da(To.getInstance().active())}function Za(e,t){return e.setValue(za,t)}function h3(e){return e.deleteValue(za)}function m3(e,t){return Za(e,new qn(t))}function Kd(e){var t;return(t=Da(e))===null||t===void 0?void 0:t.spanContext()}var g3=/^([0-9a-f]{32})$/i,v3=/^[0-9a-f]{16}$/i;function _3(e){return g3.test(e)&&e!==Wd}function y3(e){return v3.test(e)&&e!==Gd}function Yd(e){return _3(e.traceId)&&y3(e.spanId)}function w3(e){return new qn(e)}var Fa=To.getInstance(),Qd=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Fa.active());var o=!!r?.root;if(o)return new qn;var s=n&&Kd(n);return b3(s)&&Yd(s)?new qn(s):new qn},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??Fa.active(),c=this.startSpan(t,s,l),u=Za(l,c);return Fa.with(u,i,void 0,c)}},e})();function b3(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var k3=new Qd,S3=(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):k3},e})(),C3=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Qd},e})(),T3=new C3,Xd=(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 S3(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:T3},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})(),$o;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})($o||($o={})),To.getInstance(),Lt.instance();var $3=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return Kw},e})(),E3=new $3,Va="metrics",I3=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Mn(Va,t,Lt.instance())},e.prototype.getMeterProvider=function(){return xr(Va)||E3},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Nn(Va,Lt.instance())},e})();I3.getInstance();var x3=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Ha=Jd("OpenTelemetry Baggage Key");function ep(e){return e.getValue(Ha)||void 0}function R3(){return ep(To.getInstance().active())}function P3(e,t){return e.setValue(Ha,t)}function O3(e){return e.deleteValue(Ha)}var Ba="propagation",M3=new x3,N3=(function(){function e(){this.createBaggage=Uw,this.getBaggage=ep,this.getActiveBaggage=R3,this.setBaggage=P3,this.deleteBaggage=O3}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Mn(Ba,t,Lt.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=s3),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=o3),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Nn(Ba,Lt.instance())},e.prototype._getGlobalPropagator=function(){return xr(Ba)||M3},e})();N3.getInstance();var Ja="trace",A3=(function(){function e(){this._proxyTracerProvider=new Xd,this.wrapSpanContext=w3,this.isSpanContextValid=Yd,this.deleteSpan=h3,this.getSpan=Da,this.getActiveSpan=f3,this.getSpanContext=Kd,this.setSpan=Za,this.setSpanContext=m3}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Mn(Ja,this._proxyTracerProvider,Lt.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return xr(Ja)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Nn(Ja,Lt.instance()),this._proxyTracerProvider=new Xd},e})(),q3=A3.getInstance(),L3=Object.defineProperty,j3=(e,t)=>{for(var r in t)L3(e,r,{get:t[r],enumerable:!0})},tp="AI_NoOutputSpecifiedError",rp=`vercel.ai.error.${tp}`,U3=Symbol.for(rp),np,op=class extends ue{constructor({message:e="No output specified."}={}){super({name:tp,message:e}),this[np]=!0}static isInstance(e){return ue.hasMarker(e,rp)}};np=U3;function z3(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let r=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"unsupported-tool":{const r="name"in e.tool?e.tool.name:"unknown tool";let n=`${t} The tool "${r}" is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var D3="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",sp=!1,ap=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}sp||(sp=!0,console.info(D3));for(const r of e)console.warn(z3(r))}},ip="AI_InvalidArgumentError",lp=`vercel.ai.error.${ip}`,Z3=Symbol.for(lp),cp,jt=class extends ue{constructor({parameter:e,value:t,message:r}){super({name:ip,message:`Invalid argument for parameter ${e}: ${r}`}),this[cp]=!0,this.parameter=e,this.value=t}static isInstance(e){return ue.hasMarker(e,lp)}};cp=Z3;var up="AI_InvalidToolInputError",dp=`vercel.ai.error.${up}`,F3=Symbol.for(dp),pp,fp=class extends ue{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Fr(r)}`}){super({name:up,message:n,cause:r}),this[pp]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ue.hasMarker(e,dp)}};pp=F3;var hp="AI_NoObjectGeneratedError",mp=`vercel.ai.error.${hp}`,V3=Symbol.for(mp),gp,vp=class extends ue{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:hp,message:e,cause:t}),this[gp]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ue.hasMarker(e,mp)}};gp=V3;var _p="AI_NoOutputGeneratedError",yp=`vercel.ai.error.${_p}`,H3=Symbol.for(yp),wp,B3=class extends ue{constructor({message:e="No output generated.",cause:t}={}){super({name:_p,message:e,cause:t}),this[wp]=!0}static isInstance(e){return ue.hasMarker(e,yp)}};wp=H3;var bp="AI_NoSuchToolError",kp=`vercel.ai.error.${bp}`,J3=Symbol.for(kp),Sp,Ga=class extends ue{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:bp,message:r}),this[Sp]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ue.hasMarker(e,kp)}};Sp=J3;var Cp="AI_ToolCallRepairError",Tp=`vercel.ai.error.${Cp}`,G3=Symbol.for(Tp),$p,W3=class extends ue{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Fr(e)}`}){super({name:Cp,message:r,cause:e}),this[$p]=!0,this.originalError=t}static isInstance(e){return ue.hasMarker(e,Tp)}};$p=G3;var K3=class extends ue{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}},Ep="AI_InvalidMessageRoleError",Ip=`vercel.ai.error.${Ep}`,Y3=Symbol.for(Ip),xp,Q3=class extends ue{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ep,message:t}),this[xp]=!0,this.role=e}static isInstance(e){return ue.hasMarker(e,Ip)}};xp=Y3;var Rp="AI_DownloadError",Pp=`vercel.ai.error.${Rp}`,X3=Symbol.for(Pp),Op,Wa=class extends ue{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:Rp,message:o,cause:n}),this[Op]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ue.hasMarker(e,Pp)}};Op=X3;var Mp="AI_RetryError",Np=`vercel.ai.error.${Mp}`,eb=Symbol.for(Np),Ap,qp=class extends ue{constructor({message:e,reason:t,errors:r}){super({name:Mp,message:e}),this[Ap]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ue.hasMarker(e,Np)}};Ap=eb;function Eo(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new K3({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return tb().languageModel(e)}function tb(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Sw}var rb=[{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]}],nb=e=>{const t=typeof e=="string"?Oa(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function ob(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?nb(e):e}function sb({data:e,signatures:t}){const r=ob(e),n=typeof r=="string"?Oa(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 Lp="5.0.106",ab=async({url:e})=>{var t;const r=e.toString();try{const n=await fetch(r,{headers:cr({},`ai-sdk/${Lp}`,xn())});if(!n.ok)throw new Wa({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(t=n.headers.get("content-type"))!=null?t:void 0}}catch(n){throw Wa.isInstance(n)?n:new Wa({url:r,cause:n})}},ib=(e=ab)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function lb(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 jp=ne([v(),_o(Uint8Array),_o(ArrayBuffer),Vu(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function Up(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}=lb(e.toString());if(t==null||r==null)throw new ue({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function cb(e){return typeof e=="string"?e:e instanceof ArrayBuffer?So(new Uint8Array(e)):So(e)}async function zp({prompt:e,supportedUrls:t,download:r=ib()}){const n=await db(e.messages,r,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>ub({message:o,downloadedAssets:n}))]}function ub({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=>pb(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).map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=Up(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:n.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:e.providerOptions};default:{const n=r;throw new Q3({role:n})}}}async function db(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&&D_({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 pb(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}=Up(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=sb({data:l,signatures:rb}))!=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 Ka({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 jt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new jt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new jt({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new jt({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new jt({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new jt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new jt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new jt({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 fb(e){return e!=null&&Object.keys(e).length>0}function Dp({tools:e,toolChoice:t,activeTools:r}){return fb(e)?{tools:(r!=null?Object.entries(e).filter(([o])=>r.includes(o)):Object.entries(e)).map(([o,s])=>{const a=s.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:ko(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var Ln=Fu(()=>ne([wa(),v(),q(),ce(),ve(v(),Ln),A(Ln)])),Ut=ve(v(),ve(v(),Ln)),Zp=T({type:L("text"),text:v(),providerOptions:Ut.optional()}),hb=T({type:L("image"),image:ne([jp,_o(URL)]),mediaType:v().optional(),providerOptions:Ut.optional()}),Fp=T({type:L("file"),data:ne([jp,_o(URL)]),filename:v().optional(),mediaType:v(),providerOptions:Ut.optional()}),mb=T({type:L("reasoning"),text:v(),providerOptions:Ut.optional()}),gb=T({type:L("tool-call"),toolCallId:v(),toolName:v(),input:$e(),providerOptions:Ut.optional(),providerExecuted:ce().optional()}),vb=Ze("type",[T({type:L("text"),value:v()}),T({type:L("json"),value:Ln}),T({type:L("error-text"),value:v()}),T({type:L("error-json"),value:Ln}),T({type:L("content"),value:A(ne([T({type:L("text"),text:v()}),T({type:L("media"),data:v(),mediaType:v()})]))})]),Vp=T({type:L("tool-result"),toolCallId:v(),toolName:v(),output:vb,providerOptions:Ut.optional()}),_b=T({role:L("system"),content:v(),providerOptions:Ut.optional()}),yb=T({role:L("user"),content:ne([v(),A(ne([Zp,hb,Fp]))]),providerOptions:Ut.optional()}),wb=T({role:L("assistant"),content:ne([v(),A(ne([Zp,Fp,mb,gb,Vp]))]),providerOptions:Ut.optional()}),bb=T({role:L("tool"),content:A(Vp),providerOptions:Ut.optional()}),kb=ne([_b,yb,wb,bb]);async function Hp(e){if(e.prompt==null&&e.messages==null)throw new br({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new br({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new br({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new br({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new br({prompt:e,message:"messages must not be empty"});const r=await Tt({value:t,schema:A(kb)});if(!r.success)throw new br({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:t,system:e.system}}function Bp(e){return qa.isInstance(e)||Md.isInstance(e)?new ue({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function Kr({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 Jp({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])=>(s[`ai.settings.${a}`]=i,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 Sb={startSpan(){return Io},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Io);if(typeof r=="function")return r(Io);if(typeof n=="function")return n(Io)}},Io={spanContext(){return Cb},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}},Cb={traceId:"",spanId:"",traceFlags:0};function Gp({isEnabled:e=!1,tracer:t}={}){return e?t||q3.getTracer("ai"):Sb}function Yr({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:r},async s=>{try{const a=await n(s);return o&&s.end(),a}catch(a){try{Ya(s,a)}finally{s.end()}throw a}})}function Ya(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:$o.ERROR,message:t.message})):e.setStatus({code:$o.ERROR})}function wt({telemetry:e,attributes:t}){return e?.isEnabled!==!0?{}:Object.entries(t).reduce((r,[n,o])=>{if(o==null)return r;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)return r;const s=o.input();return s==null?r:{...r,[n]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)return r;const s=o.output();return s==null?r:{...r,[n]:s}}return{...r,[n]:o}},{})}function Wp(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?cb(r.data):r.data}:r)})))}function Kp(e,t){return{inputTokens:jn(e.inputTokens,t.inputTokens),outputTokens:jn(e.outputTokens,t.outputTokens),totalTokens:jn(e.totalTokens,t.totalTokens),reasoningTokens:jn(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:jn(e.cachedInputTokens,t.cachedInputTokens)}}function jn(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Qa(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function Tb({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 $b=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>Yp(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function Yp(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(Cr(a)||t===0)throw a;const i=Ta(a),l=[...s,a],c=l.length;if(c>t)throw new qp({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Pe.isInstance(a)&&a.isRetryable===!0&&c<=t)return await L_(Tb({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),Yp(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new qp({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Qp({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new jt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new jt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:$b({maxRetries:r,abortSignal:t})}}function Xp(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var e0=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=So(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Oa(this.base64Data)),this.uint8ArrayData}},Eb=class extends e0{constructor(e){super(e),this.type="file"}};async function t0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){try{if(t==null)throw new Ga({toolName:e.toolName});try{return await r0({toolCall:e,tools:t})}catch(s){if(r==null||!(Ga.isInstance(s)||fp.isInstance(s)))throw s;let a=null;try{a=await r({toolCall:e,tools:t,inputSchema:({toolName:i})=>{const{inputSchema:l}=t[i];return ko(l).jsonSchema},system:n,messages:o,error:s})}catch(i){throw new W3({cause:i,originalError:s})}if(a==null)throw s;return await r0({toolCall:a,tools:t})}}catch(s){const a=await Tr({text:e.input}),i=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i,dynamic:!0,invalid:!0,error:s,providerMetadata:e.providerMetadata}}}async function r0({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null)throw new Ga({toolName:e.toolName,availableTools:Object.keys(t)});const o=ko(n.inputSchema),s=e.input.trim()===""?await Tt({value:{},schema:o}):await Tr({text:e.input,schema:o});if(s.success===!1)throw new fp({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}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var n0=class{constructor({content:e,finishReason:t,usage:r,warnings:n,request:o,response:s,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=r,this.warnings=n,this.request=o,this.response=s,this.providerMetadata=a}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!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 Xa(e){return({steps:t})=>t.length===e}async function o0({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}function ei({output:e,tool:t,errorMode:r}){return r==="text"?{type:"error-text",value:Fr(e)}:r==="json"?{type:"error-json",value:s0(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:s0(e)}}function s0(e){return e===void 0?null:e}function ti({content:e,tools:t}){const r=[],n=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:ei({tool:t?.[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:ei({tool:t?.[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:ei({tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"}),...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}}));return o.length>0&&r.push({role:"tool",content:o}),r}var Ib=En({prefix:"aitxt",size:24});async function a0({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Xa(1),experimental_output:u,experimental_telemetry:g,providerOptions:h,experimental_activeTools:d,activeTools:p=d,experimental_prepareStep:w,prepareStep:m=w,experimental_repairToolCall:y,experimental_download:_,experimental_context:f,_internal:{generateId:b=Ib,currentDate:k=()=>new Date}={},onStepFinish:S,...C}){const I=Eo(e),x=Qa(c),{maxRetries:M,retry:P}=Qp({maxRetries:a,abortSignal:i}),U=Ka(C),z=cr(l??{},`ai/${Lp}`),F=Jp({model:I,telemetry:g,headers:z,settings:{...U,maxRetries:M}}),te=await Hp({system:n,prompt:o,messages:s}),ie=Gp(g);try{return await Yr({name:"ai.generateText",attributes:wt({telemetry:g,attributes:{...Kr({operationId:"ai.generateText",telemetry:g}),...F,"ai.model.provider":I.provider,"ai.model.id":I.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:ie,fn:async se=>{var ee,pe,V,O,Z,j,E;const R=Ka(C);let $,H=[],G=[];const fe=[],ae=[];do{const B=[...te.messages,...fe],W=await m?.({model:I,steps:ae,stepNumber:ae.length,messages:B}),Y=Eo((ee=W?.model)!=null?ee:I),oe=await zp({prompt:{system:(pe=W?.system)!=null?pe:te.system,messages:(V=W?.messages)!=null?V:B},supportedUrls:await Y.supportedUrls,download:_}),{toolChoice:le,tools:Ne}=Dp({tools:t,toolChoice:(O=W?.toolChoice)!=null?O:r,activeTools:(Z=W?.activeTools)!=null?Z:p});$=await P(()=>{var be;return Yr({name:"ai.generateText.doGenerate",attributes:wt({telemetry:g,attributes:{...Kr({operationId:"ai.generateText.doGenerate",telemetry:g}),...F,"ai.model.provider":Y.provider,"ai.model.id":Y.modelId,"ai.prompt.messages":{input:()=>Wp(oe)},"ai.prompt.tools":{input:()=>Ne?.map(pt=>JSON.stringify(pt))},"ai.prompt.toolChoice":{input:()=>le!=null?JSON.stringify(le):void 0},"gen_ai.system":Y.provider,"gen_ai.request.model":Y.modelId,"gen_ai.request.frequency_penalty":C.frequencyPenalty,"gen_ai.request.max_tokens":C.maxOutputTokens,"gen_ai.request.presence_penalty":C.presencePenalty,"gen_ai.request.stop_sequences":C.stopSequences,"gen_ai.request.temperature":(be=C.temperature)!=null?be:void 0,"gen_ai.request.top_k":C.topK,"gen_ai.request.top_p":C.topP}}),tracer:ie,fn:async pt=>{var tr,ft,We,St,yr,wr,gn,aa;const He=await Y.doGenerate({...R,tools:Ne,toolChoice:le,responseFormat:u?.responseFormat,prompt:oe,providerOptions:h,abortSignal:i,headers:z}),rr={id:(ft=(tr=He.response)==null?void 0:tr.id)!=null?ft:b(),timestamp:(St=(We=He.response)==null?void 0:We.timestamp)!=null?St:k(),modelId:(wr=(yr=He.response)==null?void 0:yr.modelId)!=null?wr:Y.modelId,headers:(gn=He.response)==null?void 0:gn.headers,body:(aa=He.response)==null?void 0:aa.body};return pt.setAttributes(wt({telemetry:g,attributes:{"ai.response.finishReason":He.finishReason,"ai.response.text":{output:()=>Xp(He.content)},"ai.response.toolCalls":{output:()=>{const nr=i0(He.content);return nr==null?void 0:JSON.stringify(nr)}},"ai.response.id":rr.id,"ai.response.model":rr.modelId,"ai.response.timestamp":rr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(He.providerMetadata),"ai.usage.promptTokens":He.usage.inputTokens,"ai.usage.completionTokens":He.usage.outputTokens,"gen_ai.response.finish_reasons":[He.finishReason],"gen_ai.response.id":rr.id,"gen_ai.response.model":rr.modelId,"gen_ai.usage.input_tokens":He.usage.inputTokens,"gen_ai.usage.output_tokens":He.usage.outputTokens}})),{...He,response:rr}}})});const qe=await Promise.all($.content.filter(be=>be.type==="tool-call").map(be=>t0({toolCall:be,tools:t,repairToolCall:y,system:n,messages:B})));for(const be of qe){if(be.invalid)continue;const pt=t[be.toolName];pt?.onInputAvailable!=null&&await pt.onInputAvailable({input:be.input,toolCallId:be.toolCallId,messages:B,abortSignal:i,experimental_context:f})}const X=qe.filter(be=>be.invalid&&be.dynamic);G=[];for(const be of X)G.push({type:"tool-error",toolCallId:be.toolCallId,toolName:be.toolName,input:be.input,error:Ta(be.error),dynamic:!0});H=qe.filter(be=>!be.providerExecuted),t!=null&&G.push(...await xb({toolCalls:H.filter(be=>!be.invalid),tools:t,tracer:ie,telemetry:g,messages:B,abortSignal:i,experimental_context:f}));const me=Pb({content:$.content,toolCalls:qe,toolOutputs:G});fe.push(...ti({content:me,tools:t}));const st=new n0({content:me,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(j=$.request)!=null?j:{},response:{...$.response,messages:structuredClone(fe)}});ap((E=$.warnings)!=null?E:[]),ae.push(st),await S?.(st)}while(H.length>0&&G.length===H.length&&!await o0({stopConditions:x,steps:ae}));se.setAttributes(wt({telemetry:g,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>Xp($.content)},"ai.response.toolCalls":{output:()=>{const B=i0($.content);return B==null?void 0:JSON.stringify(B)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const N=ae[ae.length-1];let D;return N.finishReason==="stop"&&(D=await u?.parseOutput({text:N.text},{response:N.response,usage:N.usage,finishReason:N.finishReason})),new Rb({steps:ae,resolvedOutput:D})}})}catch(se){throw Bp(se)}}async function xb({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:c,input:u})=>{const g=t[c];if(g?.execute!=null)return Yr({name:"ai.toolCall",attributes:wt({telemetry:n,attributes:{...Kr({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async h=>{try{const d=ud({execute:g.execute.bind(g),input:u,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:a}});let p;for await(const w of d)w.type==="final"&&(p=w.output);try{h.setAttributes(wt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(p)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:p,dynamic:g.type==="dynamic"}}catch(d){return Ya(h,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:g.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Rb=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((e,t)=>Kp(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new op;return this.resolvedOutput}};function i0(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 Pb({content:e,toolCalls:t,toolOutputs:r}){return[...e.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new e0(n)};case"tool-call":return t.find(o=>o.toolCallId===n.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===n.toolCallId);if(o==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:o.input,error:n.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:o.input,output:n.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...r]}function xo(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 Ob({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:xo(r,{"content-type":"text/plain; charset=utf-8"})})}function l0({response:e,status:t,statusText:r,headers:n,stream:o}){e.writeHead(t??200,r,n);const s=o.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;e.write(l)||await new Promise(u=>{e.once("drain",u)})}}catch(i){throw i}finally{e.end()}})()}function Mb({response:e,status:t,statusText:r,headers:n,textStream:o}){l0({response:e,status:t,statusText:r,headers:Object.fromEntries(xo(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var c0=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
53
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new S_({message:i,statusCode:o,cause:s})}},qp="GatewayInvalidRequestError",W3=`vercel.ai.gateway.error.${qp}`,Lp=Symbol.for(W3),Up,jp,G3=class extends(jp=vt,Up=Lp,jp){constructor({message:e="Invalid request",statusCode:t=400,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Up]=!0,this.name=qp,this.type="invalid_request_error"}static isInstance(e){return vt.hasMarker(e)&&Lp in e}},Dp="GatewayRateLimitError",K3=`vercel.ai.gateway.error.${Dp}`,zp=Symbol.for(K3),Zp,Fp,Y3=class extends(Fp=vt,Zp=zp,Fp){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Zp]=!0,this.name=Dp,this.type="rate_limit_exceeded"}static isInstance(e){return vt.hasMarker(e)&&zp in e}},Vp="GatewayModelNotFoundError",Q3=`vercel.ai.gateway.error.${Vp}`,Hp=Symbol.for(Q3),X3=rn(()=>Lr(C({modelId:d()}))),Bp,Jp,Wp=class extends(Jp=vt,Bp=Hp,Jp){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Bp]=!0,this.name=Vp,this.type="model_not_found",this.modelId=r}static isInstance(e){return vt.hasMarker(e)&&Hp in e}},Gp="GatewayInternalServerError",e9=`vercel.ai.gateway.error.${Gp}`,Kp=Symbol.for(e9),Yp,Qp,Xp=class extends(Qp=vt,Yp=Kp,Qp){constructor({message:e="Internal server error",statusCode:t=500,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Yp]=!0,this.name=Gp,this.type="internal_server_error"}static isInstance(e){return vt.hasMarker(e)&&Kp in e}},eh="GatewayResponseError",t9=`vercel.ai.gateway.error.${eh}`,th=Symbol.for(t9),rh,nh,r9=class extends(nh=vt,rh=th,nh){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[rh]=!0,this.name=eh,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return vt.hasMarker(e)&&th in e}};async function oh({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){const s=await Pt({value:e,schema:n9});if(!s.success)return new r9({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:s.error,cause:n});const i=s.value,a=i.error.type,l=i.error.message;switch(a){case"authentication_error":return Ei.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n});case"invalid_request_error":return new G3({message:l,statusCode:t,cause:n});case"rate_limit_exceeded":return new Y3({message:l,statusCode:t,cause:n});case"model_not_found":{const c=await Pt({value:i.error.param,schema:X3});return new Wp({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new Xp({message:l,statusCode:t,cause:n});default:return new Xp({message:l,statusCode:t,cause:n})}}var n9=rn(()=>Lr(C({error:C({message:d(),type:d().nullish(),param:ce().nullish(),code:X([d(),A()]).nullish()})})));function yr(e,t){var r;return vt.isInstance(e)?e:ot.isInstance(e)?oh({response:o9(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):oh({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function o9(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 sh="ai-gateway-auth-method";async function sn(e){const t=await Pt({value:e[sh],schema:s9});return t.success?t.value:void 0}var s9=rn(()=>Lr(X([O("api-key"),O("oidc")]))),ah=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await hp({url:`${this.config.baseURL}/config`,headers:await Jt(this.config.headers()),successfulResponseHandler:on(a9),failedResponseHandler:qr({errorSchema:tt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await yr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await hp({url:`${e.origin}/v1/credits`,headers:await Jt(this.config.headers()),successfulResponseHandler:on(i9),failedResponseHandler:qr({errorSchema:tt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await yr(e)}}},a9=rn(()=>Lr(C({models:R(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:O("v2"),provider:d(),modelId:d()}),modelType:_e(["language","embedding","image"]).nullish()}))}))),i9=rn(()=>Lr(C({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),l9=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...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 Jt(this.config.headers());try{const{responseHeaders:s,value:i,rawValue:a}=await nn({url:this.getUrl(),headers:tn(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Jt(this.config.o11yHeaders)),body:t,successfulResponseHandler:on(tt()),failedResponseHandler:qr({errorSchema:tt(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...i,request:{body:t},response:{headers:s,body:a},warnings:r}}catch(s){throw await yr(s,await sn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Jt(this.config.headers());try{const{value:s,responseHeaders:i}=await nn({url:this.getUrl(),headers:tn(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Jt(this.config.o11yHeaders)),body:t,successfulResponseHandler:vp(tt()),failedResponseHandler:qr({errorSchema:tt(),errorToMessage:a=>a}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(a){r.length>0&&a.enqueue({type:"stream-start",warnings:r})},transform(a,l){if(a.success){const c=a.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(a.error)}})),request:{body:t},response:{headers:i}}}catch(s){throw await yr(s,await sn(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":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},c9=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Jt(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:l}=await nn({url:this.getUrl(),headers:tn(s,t??{},this.getModelConfigHeaders(),await Jt(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...n?{providerOptions:n}:{}},successfulResponseHandler:on(u9),failedResponseHandler:qr({errorSchema:tt(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:a.embeddings,usage:(o=a.usage)!=null?o:void 0,providerMetadata:a.providerMetadata,response:{headers:i,body:l}}}catch(i){throw await yr(i,await sn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},u9=rn(()=>Lr(C({embeddings:R(R(A())),usage:C({tokens:A()}).nullish(),providerMetadata:oe(d(),oe(d(),ce())).optional()}))),d9=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,providerOptions:s,headers:i,abortSignal:a}){var l;const c=await Jt(this.config.headers());try{const{responseHeaders:u,value:m,rawValue:f}=await nn({url:this.getUrl(),headers:tn(c,i??{},this.getModelConfigHeaders(),await Jt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...s&&{providerOptions:s}},successfulResponseHandler:on(h9),failedResponseHandler:qr({errorSchema:tt(),errorToMessage:p=>p}),...a&&{abortSignal:a},fetch:this.config.fetch});return{images:m.images,warnings:(l=m.warnings)!=null?l:[],providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw yr(u,await sn(c))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},p9=C({images:R(ce()).optional()}).catchall(ce()),h9=C({images:R(d()),warnings:R(C({type:O("other"),message:d()})).optional(),providerMetadata:oe(d(),p9).optional()});async function f9(){var e;return(e=Rp.getContext().headers)==null?void 0:e["x-vercel-id"]}var m9="2.0.18",g9="0.0.1";function _9(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let i=0;const a=(r=kp(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const h=await y9(e);if(h)return vr({Authorization:`Bearer ${h.token}`,"ai-gateway-protocol-version":g9,[sh]:h.authMethod,...e.headers},`ai-sdk/gateway/${m9}`);throw Ei.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const h=Ho({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=Ho({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),_=Ho({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const w=await f9();return{...h&&{"ai-o11y-deployment-id":h},...v&&{"ai-o11y-environment":v},..._&&{"ai-o11y-region":_},...w&&{"ai-o11y-request-id":w}}}},u=h=>new l9(h,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),m=async()=>{var h,v,_;const w=(_=(v=(h=e._internal)==null?void 0:h.currentDate)==null?void 0:v.call(h).getTime())!=null?_:Date.now();return(!n||w-i>s)&&(i=w,n=new ah({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(g=>(o=g,g)).catch(async g=>{throw await yr(g,await sn(await l()))})),o?Promise.resolve(o):n},f=async()=>new ah({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async h=>{throw await yr(h,await sn(await l()))}),p=function(h){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(h)};return p.getAvailableModels=m,p.getCredits=f,p.imageModel=h=>new d9(h,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),p.languageModel=u,p.textEmbeddingModel=h=>new c9(h,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),p}var v9=_9();async function y9(e){const t=Ho({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Rp.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var w9=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Ur="1.9.0",ih=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function b9(e){var t=new Set([e]),r=new Set,n=e.match(ih);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(a){return r.add(a),!1}function i(a){return t.add(a),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(ih);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?i(l):s(l):o.minor<=u.minor?i(l):s(l)}}var S9=b9(Ur),$9=Ur.split(".")[0],Gn=Symbol.for("opentelemetry.js.api."+$9),Kn=w9;function Yn(e,t,r,n){var o;n===void 0&&(n=!1);var s=Kn[Gn]=(o=Kn[Gn])!==null&&o!==void 0?o:{version:Ur};if(!n&&s[e]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(i.stack||i.message),!1}if(s.version!==Ur){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Ur);return r.error(i.stack||i.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Ur+"."),!0}function jr(e){var t,r,n=(t=Kn[Gn])===null||t===void 0?void 0:t.version;if(!(!n||!S9(n)))return(r=Kn[Gn])===null||r===void 0?void 0:r[e]}function Qn(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Ur+".");var r=Kn[Gn];r&&delete r[e]}var C9=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},k9=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))},E9=(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 Xn("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Xn("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Xn("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Xn("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Xn("verbose",this._namespace,t)},e})();function Xn(e,t,r){var n=jr("diag");if(n)return r.unshift(t),n[e].apply(n,k9([],C9(r),!1))}var yt;(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"})(yt||(yt={}));function T9(e,t){e<yt.NONE?e=yt.NONE:e>yt.ALL&&(e=yt.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",yt.ERROR),warn:r("warn",yt.WARN),info:r("info",yt.INFO),debug:r("debug",yt.DEBUG),verbose:r("verbose",yt.VERBOSE)}}var I9=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},R9=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))},x9="diag",Wt=(function(){function e(){function t(o){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=jr("diag");if(a)return a[o].apply(a,R9([],I9(s),!1))}}var r=this,n=function(o,s){var i,a,l;if(s===void 0&&(s={logLevel:yt.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((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=jr("diag"),m=T9((a=s.logLevel)!==null&&a!==void 0?a:yt.INFO,o);if(u&&!s.suppressOverrideMessage){var f=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+f),m.warn("Current logger will overwrite one already registered from "+f)}return Yn("diag",m,r,!0)};r.setLogger=n,r.disable=function(){Qn(x9,r)},r.createComponentLogger=function(o){return new E9(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})(),P9=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},O9=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.")},M9=(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=P9(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 i=O9(n),a=i.next();!a.done;a=i.next()){var l=a.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();Wt.instance();function A9(e){return e===void 0&&(e={}),new M9(new Map(Object.entries(e)))}function lh(e){return Symbol.for(e)}var N9=(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})(),q9=new N9,Dr=(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)}})(),L9=(function(){function e(){}return e.prototype.createGauge=function(t,r){return J9},e.prototype.createHistogram=function(t,r){return W9},e.prototype.createCounter=function(t,r){return B9},e.prototype.createUpDownCounter=function(t,r){return G9},e.prototype.createObservableGauge=function(t,r){return Y9},e.prototype.createObservableCounter=function(t,r){return K9},e.prototype.createObservableUpDownCounter=function(t,r){return Q9},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Go=(function(){function e(){}return e})(),U9=(function(e){Dr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Go),j9=(function(e){Dr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Go),D9=(function(e){Dr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Go),z9=(function(e){Dr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Go),Ti=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Z9=(function(e){Dr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ti),F9=(function(e){Dr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ti),V9=(function(e){Dr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ti),H9=new L9,B9=new U9,J9=new D9,W9=new z9,G9=new j9,K9=new Z9,Y9=new F9,Q9=new V9,X9={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},e4={set:function(e,t,r){e!=null&&(e[t]=r)}},t4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.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))},n4=(function(){function e(){}return e.prototype.active=function(){return q9},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,r4([n],t4(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),o4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],i;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s},s4=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))},Ii="context",a4=new n4,Ko=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Yn(Ii,t,Wt.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],i=3;i<arguments.length;i++)s[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,s4([t,r,n],o4(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return jr(Ii)||a4},e.prototype.disable=function(){this._getContextManager().disable(),Qn(Ii,Wt.instance())},e})(),Ri;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ri||(Ri={}));var ch="0000000000000000",uh="00000000000000000000000000000000",i4={traceId:uh,spanId:ch,traceFlags:Ri.NONE},eo=(function(){function e(t){t===void 0&&(t=i4),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})(),xi=lh("OpenTelemetry Context Key SPAN");function Pi(e){return e.getValue(xi)||void 0}function l4(){return Pi(Ko.getInstance().active())}function Oi(e,t){return e.setValue(xi,t)}function c4(e){return e.deleteValue(xi)}function u4(e,t){return Oi(e,new eo(t))}function dh(e){var t;return(t=Pi(e))===null||t===void 0?void 0:t.spanContext()}var d4=/^([0-9a-f]{32})$/i,p4=/^[0-9a-f]{16}$/i;function h4(e){return d4.test(e)&&e!==uh}function f4(e){return p4.test(e)&&e!==ch}function ph(e){return h4(e.traceId)&&f4(e.spanId)}function m4(e){return new eo(e)}var Mi=Ko.getInstance(),hh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Mi.active());var o=!!r?.root;if(o)return new eo;var s=n&&dh(n);return g4(s)&&ph(s)?new eo(s):new eo},e.prototype.startActiveSpan=function(t,r,n,o){var s,i,a;if(!(arguments.length<2)){arguments.length===2?a=r:arguments.length===3?(s=r,a=n):(s=r,i=n,a=o);var l=i??Mi.active(),c=this.startSpan(t,s,l),u=Oi(l,c);return Mi.with(u,a,void 0,c)}},e})();function g4(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var _4=new hh,v4=(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):_4},e})(),y4=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new hh},e})(),w4=new y4,fh=(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 v4(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:w4},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})(),Yo;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Yo||(Yo={})),Ko.getInstance(),Wt.instance();var b4=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return H9},e})(),S4=new b4,Ai="metrics",$4=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Yn(Ai,t,Wt.instance())},e.prototype.getMeterProvider=function(){return jr(Ai)||S4},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Qn(Ai,Wt.instance())},e})();$4.getInstance();var C4=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Ni=lh("OpenTelemetry Baggage Key");function mh(e){return e.getValue(Ni)||void 0}function k4(){return mh(Ko.getInstance().active())}function E4(e,t){return e.setValue(Ni,t)}function T4(e){return e.deleteValue(Ni)}var qi="propagation",I4=new C4,R4=(function(){function e(){this.createBaggage=A9,this.getBaggage=mh,this.getActiveBaggage=k4,this.setBaggage=E4,this.deleteBaggage=T4}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Yn(qi,t,Wt.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=e4),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=X9),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Qn(qi,Wt.instance())},e.prototype._getGlobalPropagator=function(){return jr(qi)||I4},e})();R4.getInstance();var Li="trace",x4=(function(){function e(){this._proxyTracerProvider=new fh,this.wrapSpanContext=m4,this.isSpanContextValid=ph,this.deleteSpan=c4,this.getSpan=Pi,this.getActiveSpan=l4,this.getSpanContext=dh,this.setSpan=Oi,this.setSpanContext=u4}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Yn(Li,this._proxyTracerProvider,Wt.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return jr(Li)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Qn(Li,Wt.instance()),this._proxyTracerProvider=new fh},e})(),P4=x4.getInstance(),O4=Object.defineProperty,M4=(e,t)=>{for(var r in t)O4(e,r,{get:t[r],enumerable:!0})},gh="AI_NoOutputSpecifiedError",_h=`vercel.ai.error.${gh}`,A4=Symbol.for(_h),vh,yh=class extends ge{constructor({message:e="No output specified."}={}){super({name:gh,message:e}),this[vh]=!0}static isInstance(e){return ge.hasMarker(e,_h)}};vh=A4;function N4(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let r=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"unsupported-tool":{const r="name"in e.tool?e.tool.name:"unknown tool";let n=`${t} The tool "${r}" is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var q4="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",wh=!1,bh=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}wh||(wh=!0,console.info(q4));for(const r of e)console.warn(N4(r))}},Sh="AI_InvalidArgumentError",$h=`vercel.ai.error.${Sh}`,L4=Symbol.for($h),Ch,Gt=class extends ge{constructor({parameter:t,value:r,message:n}){super({name:Sh,message:`Invalid argument for parameter ${t}: ${n}`}),this[Ch]=!0,this.parameter=t,this.value=r}static isInstance(t){return ge.hasMarker(t,$h)}};Ch=L4;var kh="AI_InvalidToolInputError",Eh=`vercel.ai.error.${kh}`,U4=Symbol.for(Eh),Th,Ih=class extends ge{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Xr(r)}`}){super({name:kh,message:n,cause:r}),this[Th]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ge.hasMarker(e,Eh)}};Th=U4;var Rh="AI_NoObjectGeneratedError",xh=`vercel.ai.error.${Rh}`,j4=Symbol.for(xh),Ph,Oh=class extends ge{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Rh,message:e,cause:t}),this[Ph]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ge.hasMarker(e,xh)}};Ph=j4;var Mh="AI_NoOutputGeneratedError",Ah=`vercel.ai.error.${Mh}`,D4=Symbol.for(Ah),Nh,z4=class extends ge{constructor({message:e="No output generated.",cause:t}={}){super({name:Mh,message:e,cause:t}),this[Nh]=!0}static isInstance(e){return ge.hasMarker(e,Ah)}};Nh=D4;var qh="AI_NoSuchToolError",Lh=`vercel.ai.error.${qh}`,Z4=Symbol.for(Lh),Uh,Ui=class extends ge{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:qh,message:r}),this[Uh]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ge.hasMarker(e,Lh)}};Uh=Z4;var jh="AI_ToolCallRepairError",Dh=`vercel.ai.error.${jh}`,F4=Symbol.for(Dh),zh,V4=class extends ge{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Xr(e)}`}){super({name:jh,message:r,cause:e}),this[zh]=!0,this.originalError=t}static isInstance(e){return ge.hasMarker(e,Dh)}};zh=F4;var H4=class extends ge{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}},Zh="AI_InvalidMessageRoleError",Fh=`vercel.ai.error.${Zh}`,B4=Symbol.for(Fh),Vh,J4=class extends ge{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Zh,message:t}),this[Vh]=!0,this.role=e}static isInstance(e){return ge.hasMarker(e,Fh)}};Vh=B4;var Hh="AI_DownloadError",Bh=`vercel.ai.error.${Hh}`,W4=Symbol.for(Bh),Jh,ji=class extends ge{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:Hh,message:o,cause:n}),this[Jh]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ge.hasMarker(e,Bh)}};Jh=W4;var Wh="AI_RetryError",Gh=`vercel.ai.error.${Wh}`,G4=Symbol.for(Gh),Kh,Yh=class extends ge{constructor({message:e,reason:t,errors:r}){super({name:Wh,message:e}),this[Kh]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ge.hasMarker(e,Gh)}};Kh=G4;function Qo(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new H4({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return K4().languageModel(e)}function K4(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:v9}var Y4=[{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]}],Q4=e=>{const t=typeof e=="string"?bi(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function X4(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Q4(e):e}function e6({data:e,signatures:t}){const r=X4(e),n=typeof r=="string"?bi(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,i)=>s===null||n[i]===s))return o.mediaType}var Qh="5.0.106",t6=async({url:e})=>{var t;const r=e.toString();try{const n=await fetch(r,{headers:vr({},`ai-sdk/${Qh}`,Jn())});if(!n.ok)throw new ji({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(t=n.headers.get("content-type"))!=null?t:void 0}}catch(n){throw ji.isInstance(n)?n:new ji({url:r,cause:n})}},r6=(e=t6)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function n6(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 Xh=X([d(),Fo(Uint8Array),Fo(ArrayBuffer),di(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function ef(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}=n6(e.toString());if(t==null||r==null)throw new ge({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function o6(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Wo(new Uint8Array(e)):Wo(e)}async function tf({prompt:e,supportedUrls:t,download:r=r6()}){const n=await a6(e.messages,r,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>s6({message:o,downloadedAssets:n}))]}function s6({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=>i6(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).map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:i}=ef(n.data);return{type:"file",data:s,filename:n.filename,mediaType:i??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:n.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:e.providerOptions};default:{const n=r;throw new J4({role:n})}}}async function a6(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 i;const a=(i=s.mediaType)!=null?i: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:a,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&qb({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,i)=>s==null?null:[n[i].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function i6(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:i}=ef(n);let a=i??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,a??(a=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(a=(r=e6({data:l,signatures:Y4}))!=null?r:a),{type:"file",mediaType:a??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(a==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:a,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function Di({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:i,stopSequences:a}){if(e!=null){if(!Number.isInteger(e))throw new Gt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Gt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Gt({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Gt({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Gt({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Gt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Gt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new Gt({parameter:"seed",value:i,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:a,seed:i}}function l6(e){return e!=null&&Object.keys(e).length>0}function rf({tools:e,toolChoice:t,activeTools:r}){return l6(e)?{tools:(r!=null?Object.entries(e).filter(([o])=>r.includes(o)):Object.entries(e)).map(([o,s])=>{const i=s.type;switch(i){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:Jo(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const a=i;throw new Error(`Unsupported tool type: ${a}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var to=lp(()=>X([ii(),d(),A(),te(),oe(d(),to),R(to)])),Kt=oe(d(),oe(d(),to)),nf=C({type:O("text"),text:d(),providerOptions:Kt.optional()}),c6=C({type:O("image"),image:X([Xh,Fo(URL)]),mediaType:d().optional(),providerOptions:Kt.optional()}),of=C({type:O("file"),data:X([Xh,Fo(URL)]),filename:d().optional(),mediaType:d(),providerOptions:Kt.optional()}),u6=C({type:O("reasoning"),text:d(),providerOptions:Kt.optional()}),d6=C({type:O("tool-call"),toolCallId:d(),toolName:d(),input:ce(),providerOptions:Kt.optional(),providerExecuted:te().optional()}),p6=De("type",[C({type:O("text"),value:d()}),C({type:O("json"),value:to}),C({type:O("error-text"),value:d()}),C({type:O("error-json"),value:to}),C({type:O("content"),value:R(X([C({type:O("text"),text:d()}),C({type:O("media"),data:d(),mediaType:d()})]))})]),sf=C({type:O("tool-result"),toolCallId:d(),toolName:d(),output:p6,providerOptions:Kt.optional()}),h6=C({role:O("system"),content:d(),providerOptions:Kt.optional()}),f6=C({role:O("user"),content:X([d(),R(X([nf,c6,of]))]),providerOptions:Kt.optional()}),m6=C({role:O("assistant"),content:X([d(),R(X([nf,of,u6,d6,sf]))]),providerOptions:Kt.optional()}),g6=C({role:O("tool"),content:R(sf),providerOptions:Kt.optional()}),_6=X([h6,f6,m6,g6]);async function af(e){if(e.prompt==null&&e.messages==null)throw new en({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new en({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new en({prompt:e,message:"system must be a string"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new en({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new en({prompt:e,message:"messages must not be empty"});const r=await Pt({value:t,schema:R(_6)});if(!r.success)throw new en({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:t,system:e.system}}function lf(e){return Ei.isInstance(e)||Wp.isInstance(e)?new ge({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function an({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 cf({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,[i,a])=>(s[`ai.settings.${i}`]=a,s),{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[i,a])=>(s[`ai.telemetry.metadata.${i}`]=a,s),{}),...Object.entries(n??{}).reduce((s,[i,a])=>(a!==void 0&&(s[`ai.request.headers.${i}`]=a),s),{})}}var v6={startSpan(){return Xo},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Xo);if(typeof r=="function")return r(Xo);if(typeof n=="function")return n(Xo)}},Xo={spanContext(){return y6},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}},y6={traceId:"",spanId:"",traceFlags:0};function uf({isEnabled:e=!1,tracer:t}={}){return e?t||P4.getTracer("ai"):v6}function ln({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:r},async s=>{try{const i=await n(s);return o&&s.end(),i}catch(i){try{zi(s,i)}finally{s.end()}throw i}})}function zi(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Yo.ERROR,message:t.message})):e.setStatus({code:Yo.ERROR})}function Ct({telemetry:e,attributes:t}){return e?.isEnabled!==!0?{}:Object.entries(t).reduce((r,[n,o])=>{if(o==null)return r;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)return r;const s=o.input();return s==null?r:{...r,[n]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)return r;const s=o.output();return s==null?r:{...r,[n]:s}}return{...r,[n]:o}},{})}function df(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?o6(r.data):r.data}:r)})))}function pf(e,t){return{inputTokens:ro(e.inputTokens,t.inputTokens),outputTokens:ro(e.outputTokens,t.outputTokens),totalTokens:ro(e.totalTokens,t.totalTokens),reasoningTokens:ro(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:ro(e.cachedInputTokens,t.cachedInputTokens)}}function ro(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Zi(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function w6({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(n=i)}const s=r["retry-after"];if(s&&n===void 0){const i=parseFloat(s);Number.isNaN(i)?n=Date.parse(s)-Date.now():n=i*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var b6=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>hf(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function hf(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(i){if(Ar(i)||t===0)throw i;const a=fi(i),l=[...s,i],c=l.length;if(c>t)throw new Yh({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&ot.isInstance(i)&&i.isRetryable===!0&&c<=t)return await Ob(w6({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),hf(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new Yh({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function ff({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Gt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Gt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:b6({maxRetries:r,abortSignal:t})}}function mf(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var gf=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=Wo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=bi(this.base64Data)),this.uint8ArrayData}},S6=class extends gf{constructor(e){super(e),this.type="file"}};async function _f({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){try{if(t==null)throw new Ui({toolName:e.toolName});try{return await vf({toolCall:e,tools:t})}catch(s){if(r==null||!(Ui.isInstance(s)||Ih.isInstance(s)))throw s;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:({toolName:a})=>{const{inputSchema:l}=t[a];return Jo(l).jsonSchema},system:n,messages:o,error:s})}catch(a){throw new V4({cause:a,originalError:s})}if(i==null)throw s;return await vf({toolCall:i,tools:t})}}catch(s){const i=await Nr({text:e.input}),a=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:a,dynamic:!0,invalid:!0,error:s,providerMetadata:e.providerMetadata}}}async function vf({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null)throw new Ui({toolName:e.toolName,availableTools:Object.keys(t)});const o=Jo(n.inputSchema),s=e.input.trim()===""?await Pt({value:{},schema:o}):await Nr({text:e.input,schema:o});if(s.success===!1)throw new Ih({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}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var yf=class{constructor({content:e,finishReason:t,usage:r,warnings:n,request:o,response:s,providerMetadata:i}){this.content=e,this.finishReason=t,this.usage=r,this.warnings=n,this.request=o,this.response=s,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 Fi(e){return({steps:t})=>t.length===e}async function wf({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}function Vi({output:e,tool:t,errorMode:r}){return r==="text"?{type:"error-text",value:Xr(e)}:r==="json"?{type:"error-json",value:bf(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:bf(e)}}function bf(e){return e===void 0?null:e}function Hi({content:e,tools:t}){const r=[],n=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:Vi({tool:t?.[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:Vi({tool:t?.[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:Vi({tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"}),...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}}));return o.length>0&&r.push({role:"tool",content:o}),r}var $6=Hn({prefix:"aitxt",size:24});async function Sf({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,headers:l,stopWhen:c=Fi(1),experimental_output:u,experimental_telemetry:m,providerOptions:f,experimental_activeTools:p,activeTools:h=p,experimental_prepareStep:v,prepareStep:_=v,experimental_repairToolCall:w,experimental_download:g,experimental_context:y,_internal:{generateId:b=$6,currentDate:S=()=>new Date}={},onStepFinish:$,...k}){const I=Qo(e),P=Zi(c),{maxRetries:L,retry:N}=ff({maxRetries:i,abortSignal:a}),j=Di(k),D=vr(l??{},`ai/${Qh}`),F=cf({model:I,telemetry:m,headers:D,settings:{...j,maxRetries:L}}),ne=await af({system:n,prompt:o,messages:s}),ue=uf(m);try{return await ln({name:"ai.generateText",attributes:Ct({telemetry:m,attributes:{...an({operationId:"ai.generateText",telemetry:m}),...F,"ai.model.provider":I.provider,"ai.model.id":I.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:ue,fn:async ie=>{var re,he,V,M,Z,U,T;const x=Di(k);let E,H=[],W=[];const fe=[],le=[];do{const B=[...ne.messages,...fe],G=await _?.({model:I,steps:le,stepNumber:le.length,messages:B}),Y=Qo((re=G?.model)!=null?re:I),ae=await tf({prompt:{system:(he=G?.system)!=null?he:ne.system,messages:(V=G?.messages)!=null?V:B},supportedUrls:await Y.supportedUrls,download:g}),{toolChoice:de,tools:Ae}=rf({tools:t,toolChoice:(M=G?.toolChoice)!=null?M:r,activeTools:(Z=G?.activeTools)!=null?Z:h});E=await N(()=>{var Se;return ln({name:"ai.generateText.doGenerate",attributes:Ct({telemetry:m,attributes:{...an({operationId:"ai.generateText.doGenerate",telemetry:m}),...F,"ai.model.provider":Y.provider,"ai.model.id":Y.modelId,"ai.prompt.messages":{input:()=>df(ae)},"ai.prompt.tools":{input:()=>Ae?.map(mt=>JSON.stringify(mt))},"ai.prompt.toolChoice":{input:()=>de!=null?JSON.stringify(de):void 0},"gen_ai.system":Y.provider,"gen_ai.request.model":Y.modelId,"gen_ai.request.frequency_penalty":k.frequencyPenalty,"gen_ai.request.max_tokens":k.maxOutputTokens,"gen_ai.request.presence_penalty":k.presencePenalty,"gen_ai.request.stop_sequences":k.stopSequences,"gen_ai.request.temperature":(Se=k.temperature)!=null?Se:void 0,"gen_ai.request.top_k":k.topK,"gen_ai.request.top_p":k.topP}}),tracer:ue,fn:async mt=>{var pr,gt,Xe,xt,Rr,xr,Mn,Ha;const He=await Y.doGenerate({...x,tools:Ae,toolChoice:de,responseFormat:u?.responseFormat,prompt:ae,providerOptions:f,abortSignal:a,headers:D}),hr={id:(gt=(pr=He.response)==null?void 0:pr.id)!=null?gt:b(),timestamp:(xt=(Xe=He.response)==null?void 0:Xe.timestamp)!=null?xt:S(),modelId:(xr=(Rr=He.response)==null?void 0:Rr.modelId)!=null?xr:Y.modelId,headers:(Mn=He.response)==null?void 0:Mn.headers,body:(Ha=He.response)==null?void 0:Ha.body};return mt.setAttributes(Ct({telemetry:m,attributes:{"ai.response.finishReason":He.finishReason,"ai.response.text":{output:()=>mf(He.content)},"ai.response.toolCalls":{output:()=>{const fr=$f(He.content);return fr==null?void 0:JSON.stringify(fr)}},"ai.response.id":hr.id,"ai.response.model":hr.modelId,"ai.response.timestamp":hr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(He.providerMetadata),"ai.usage.promptTokens":He.usage.inputTokens,"ai.usage.completionTokens":He.usage.outputTokens,"gen_ai.response.finish_reasons":[He.finishReason],"gen_ai.response.id":hr.id,"gen_ai.response.model":hr.modelId,"gen_ai.usage.input_tokens":He.usage.inputTokens,"gen_ai.usage.output_tokens":He.usage.outputTokens}})),{...He,response:hr}}})});const qe=await Promise.all(E.content.filter(Se=>Se.type==="tool-call").map(Se=>_f({toolCall:Se,tools:t,repairToolCall:w,system:n,messages:B})));for(const Se of qe){if(Se.invalid)continue;const mt=t[Se.toolName];mt?.onInputAvailable!=null&&await mt.onInputAvailable({input:Se.input,toolCallId:Se.toolCallId,messages:B,abortSignal:a,experimental_context:y})}const ee=qe.filter(Se=>Se.invalid&&Se.dynamic);W=[];for(const Se of ee)W.push({type:"tool-error",toolCallId:Se.toolCallId,toolName:Se.toolName,input:Se.input,error:fi(Se.error),dynamic:!0});H=qe.filter(Se=>!Se.providerExecuted),t!=null&&W.push(...await C6({toolCalls:H.filter(Se=>!Se.invalid),tools:t,tracer:ue,telemetry:m,messages:B,abortSignal:a,experimental_context:y}));const ve=E6({content:E.content,toolCalls:qe,toolOutputs:W});fe.push(...Hi({content:ve,tools:t}));const ct=new yf({content:ve,finishReason:E.finishReason,usage:E.usage,warnings:E.warnings,providerMetadata:E.providerMetadata,request:(U=E.request)!=null?U:{},response:{...E.response,messages:structuredClone(fe)}});bh((T=E.warnings)!=null?T:[]),le.push(ct),await $?.(ct)}while(H.length>0&&W.length===H.length&&!await wf({stopConditions:P,steps:le}));ie.setAttributes(Ct({telemetry:m,attributes:{"ai.response.finishReason":E.finishReason,"ai.response.text":{output:()=>mf(E.content)},"ai.response.toolCalls":{output:()=>{const B=$f(E.content);return B==null?void 0:JSON.stringify(B)}},"ai.response.providerMetadata":JSON.stringify(E.providerMetadata),"ai.usage.promptTokens":E.usage.inputTokens,"ai.usage.completionTokens":E.usage.outputTokens}}));const q=le[le.length-1];let z;return q.finishReason==="stop"&&(z=await u?.parseOutput({text:q.text},{response:q.response,usage:q.usage,finishReason:q.finishReason})),new k6({steps:le,resolvedOutput:z})}})}catch(ie){throw lf(ie)}}async function C6({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i}){return(await Promise.all(e.map(async({toolCallId:l,toolName:c,input:u})=>{const m=t[c];if(m?.execute!=null)return ln({name:"ai.toolCall",attributes:Ct({telemetry:n,attributes:{...an({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async f=>{try{const p=Ep({execute:m.execute.bind(m),input:u,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:i}});let h;for await(const v of p)v.type==="final"&&(h=v.output);try{f.setAttributes(Ct({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(h)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:h,dynamic:m.type==="dynamic"}}catch(p){return zi(f,p),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:p,dynamic:m.type==="dynamic"}}}})}))).filter(l=>l!=null)}var k6=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((e,t)=>pf(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new yh;return this.resolvedOutput}};function $f(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 E6({content:e,toolCalls:t,toolOutputs:r}){return[...e.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new gf(n)};case"tool-call":return t.find(o=>o.toolCallId===n.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===n.toolCallId);if(o==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:o.input,error:n.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:o.input,output:n.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...r]}function es(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 T6({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:es(r,{"content-type":"text/plain; charset=utf-8"})})}function Cf({response:e,status:t,statusText:r,headers:n,stream:o}){e.writeHead(t??200,r,n);const s=o.getReader();(async()=>{try{for(;;){const{done:a,value:l}=await s.read();if(a)break;e.write(l)||await new Promise(u=>{e.once("drain",u)})}}catch(a){throw a}finally{e.end()}})()}function I6({response:e,status:t,statusText:r,headers:n,textStream:o}){Cf({response:e,status:t,statusText:r,headers:Object.fromEntries(es(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var kf=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
54
54
 
55
55
  `)},flush(e){e.enqueue(`data: [DONE]
56
56
 
57
- `)}})}},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 Nb({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new c0);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:xo(r,u0)})}function Ab({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 qb(e){return e.type.startsWith("data-")}function d0(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]=d0(s,o):r[n]=o}return r}function Lb(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 p0(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Tr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Tr({text:Lb(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function ri(e){return e.type.startsWith("tool-")}function f0(e){return e.type.split("-").slice(1).join("-")}function jb({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Ub({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,h,d,p;function w(b){const S=c.message.parts.filter(ri).find(C=>C.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function m(b){const S=c.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function y(b){var k;const S=c.message.parts.find(x=>ri(x)&&x.toolCallId===b.toolCallId),C=b,I=S;S!=null?(S.state=b.state,I.input=C.input,I.output=C.output,I.errorText=C.errorText,I.rawInput=C.rawInput,I.preliminary=C.preliminary,I.providerExecuted=(k=C.providerExecuted)!=null?k:S.providerExecuted,C.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=C.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:C.input,output:C.output,rawInput:C.rawInput,errorText:C.errorText,providerExecuted:C.providerExecuted,preliminary:C.preliminary,...C.providerMetadata!=null?{callProviderMetadata:C.providerMetadata}:{}})}function _(b){var k,S;const C=c.message.parts.find(M=>M.type==="dynamic-tool"&&M.toolCallId===b.toolCallId),I=b,x=C;C!=null?(C.state=b.state,x.toolName=b.toolName,x.input=I.input,x.output=I.output,x.errorText=I.errorText,x.rawInput=(k=I.rawInput)!=null?k:x.rawInput,x.preliminary=I.preliminary,x.providerExecuted=(S=I.providerExecuted)!=null?S:C.providerExecuted,I.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=I.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,providerExecuted:I.providerExecuted,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}async function f(b){if(b!=null){const k=c.message.metadata!=null?d0(c.message.metadata,b):b;t!=null&&await Ea({value:k,schema:t}),c.message.metadata=k}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(g=i.providerMetadata)!=null?g:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[i.id];b.state="done",b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[i.id];b.providerMetadata=(p=i.providerMetadata)!=null?p:b.providerMetadata,b.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 b=c.message.parts.filter(ri);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:k}=await p0(b.text);b.dynamic?_({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}):y({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}),u();break}case"tool-input-available":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?_({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-output-available":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:f0(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:f0(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}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 f(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await f(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await f(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(qb(i)){r?.[i.type]!=null&&await Ea({value:i.data,schema:r[i.type]});const b=i;if(b.transient){a?.(b);break}const k=b.id!=null?c.message.parts.find(S=>b.type===S.type&&b.id===S.id):void 0;k!=null?k.data=b.data:c.message.parts.push(b),a?.(b),u()}}l.enqueue(i)})}}))}function zb({messageId:e,originalMessages:t=[],onFinish:r,onError:n,stream:o}){let s=t?.[t.length-1];s?.role!=="assistant"?s=void 0:e=s.id;let a=!1;const i=o.pipeThrough(new TransformStream({transform(h,d){if(h.type==="start"){const p=h;p.messageId==null&&e!=null&&(p.messageId=e)}h.type==="abort"&&(a=!0),d.enqueue(h)}}));if(r==null)return i;const l=jb({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),c=async h=>{await h({state:l,write:()=>{}})};let u=!1;const g=async()=>{if(u||!r)return;u=!0;const h=l.message.id===s?.id;await r({isAborted:a,isContinuation:h,responseMessage:l.message,messages:[...h?t.slice(0,-1):t,l.message],finishReason:l.finishReason})};return Ub({stream:i,runUpdateMessageJob:c,onError:n}).pipeThrough(new TransformStream({transform(h,d){d.enqueue(h)},async cancel(){await g()},async flush(){await g()}}))}function Db({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new c0);if(s){const[i,l]=a.tee();a=i,s({stream:l})}l0({response:e,status:t,statusText:r,headers:Object.fromEntries(xo(n,u0).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Ro(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;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 Zb({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 h0(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Fb(){let e=[],t=null,r=!1,n=h0();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=h0(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length>0?await s():r&&t?.close()):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 Vb(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function Hb({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(y){c=y}}),g=new Set,h=new Map;let d=!1,p;function w(){d&&g.size===0&&(p!=null&&c.enqueue(p),c.close())}const m=new TransformStream({async transform(y,_){const f=y.type;switch(f){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":{_.enqueue(y);break}case"file":{_.enqueue({type:"file",file:new Eb({data:y.data,mediaType:y.mediaType})});break}case"finish":{p={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const b=await t0({toolCall:y,tools:e,repairToolCall:i,system:o,messages:s});if(_.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Ta(b.error),dynamic:!0});break}const k=e[b.toolName];if(h.set(b.toolCallId,b.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:s,abortSignal:a,experimental_context:l}),k.execute!=null&&b.providerExecuted!==!0){const S=In();g.add(S),Yr({name:"ai.toolCall",attributes:wt({telemetry:n,attributes:{...Kr({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async C=>{let I;try{const x=ud({execute:k.execute.bind(k),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:a,experimental_context:l}});for await(const M of x)c.enqueue({...b,type:"tool-result",output:M.output,...M.type==="preliminary"&&{preliminary:!0}}),M.type==="final"&&(I=M.output)}catch(x){Ya(C,x),c.enqueue({...b,type:"tool-error",error:x}),g.delete(S),w();return}g.delete(S),w();try{C.setAttributes(wt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(I)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=y.toolName;y.isError?c.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):_.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const b=f;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,w()}});return new ReadableStream({async start(y){return Promise.all([t.pipeThrough(m).pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){}})),u.pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){y.close()}}))])}})}var Bb=En({prefix:"aitxt",size:24});function ni({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Xa(1),experimental_output:u,experimental_telemetry:g,prepareStep:h,providerOptions:d,experimental_activeTools:p,activeTools:w=p,experimental_repairToolCall:m,experimental_transform:y,experimental_download:_,includeRawChunks:f=!1,onChunk:b,onError:k=({error:F})=>{console.error(F)},onFinish:S,onAbort:C,onStepFinish:I,experimental_context:x,_internal:{now:M=Vb,generateId:P=Bb,currentDate:U=()=>new Date}={},...z}){return new Gb({model:Eo(e),telemetry:g,headers:l,settings:z,maxRetries:a,abortSignal:i,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Qa(y),activeTools:w,repairToolCall:m,stopConditions:Qa(c),output:u,providerOptions:d,prepareStep:h,includeRawChunks:f,onChunk:b,onError:k,onFinish:S,onAbort:C,onStepFinish:I,now:M,currentDate:U,generateId:P,experimental_context:x,download:_})}function Jb(e){if(!e)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let t,r="",n="",o="";function s({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&n.length>0&&s({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&s({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text;const l=await e.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==o&&(s({controller:i,partialOutput:l.partial}),o=c)}}})}var Gb=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,system:a,prompt:i,messages:l,tools:c,toolChoice:u,transforms:g,activeTools:h,repairToolCall:d,stopConditions:p,output:w,providerOptions:m,prepareStep:y,includeRawChunks:_,now:f,currentDate:b,generateId:k,onChunk:S,onError:C,onFinish:I,onAbort:x,onStepFinish:M,experimental_context:P,download:U}){this._totalUsage=new yo,this._finishReason=new yo,this._steps=new yo,this.output=w,this.includeRawChunks=_,this.tools=c;let z,F=[];const te=[];let ie,se,ee={},pe=[];const V=[];let O,Z={},j={};const E=new TransformStream({async transform(W,Y){var oe,le,Ne,qe;Y.enqueue(W);const{part:X}=W;if((X.type==="text-delta"||X.type==="reasoning-delta"||X.type==="source"||X.type==="tool-call"||X.type==="tool-result"||X.type==="tool-input-start"||X.type==="tool-input-delta"||X.type==="raw")&&await S?.({chunk:X}),X.type==="error"&&await C({error:Bp(X.error)}),X.type==="text-start"&&(Z[X.id]={type:"text",text:"",providerMetadata:X.providerMetadata},F.push(Z[X.id])),X.type==="text-delta"){const me=Z[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}me.text+=X.text,me.providerMetadata=(oe=X.providerMetadata)!=null?oe:me.providerMetadata}if(X.type==="text-end"){const me=Z[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`text part ${X.id} not found`},partialOutput:void 0});return}me.providerMetadata=(le=X.providerMetadata)!=null?le:me.providerMetadata,delete Z[X.id]}if(X.type==="reasoning-start"&&(j[X.id]={type:"reasoning",text:"",providerMetadata:X.providerMetadata},F.push(j[X.id])),X.type==="reasoning-delta"){const me=j[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}me.text+=X.text,me.providerMetadata=(Ne=X.providerMetadata)!=null?Ne:me.providerMetadata}if(X.type==="reasoning-end"){const me=j[X.id];if(me==null){Y.enqueue({part:{type:"error",error:`reasoning part ${X.id} not found`},partialOutput:void 0});return}me.providerMetadata=(qe=X.providerMetadata)!=null?qe:me.providerMetadata,delete j[X.id]}if(X.type==="file"&&F.push({type:"file",file:X.file}),X.type==="source"&&F.push(X),X.type==="tool-call"&&F.push(X),X.type==="tool-result"&&!X.preliminary&&F.push(X),X.type==="tool-error"&&F.push(X),X.type==="start-step"&&(ee=X.request,pe=X.warnings),X.type==="finish-step"){const me=ti({content:F,tools:c}),st=new n0({content:F,finishReason:X.finishReason,usage:X.usage,warnings:pe,request:ee,response:{...X.response,messages:[...te,...me]},providerMetadata:X.providerMetadata});await M?.(st),ap(pe),V.push(st),F=[],j={},Z={},te.push(...me),z.resolve()}X.type==="finish"&&(se=X.totalUsage,ie=X.finishReason)},async flush(W){try{if(V.length===0){const Ne=new B3({message:"No output generated. Check the stream for errors."});B._finishReason.reject(Ne),B._totalUsage.reject(Ne),B._steps.reject(Ne);return}const Y=ie??"unknown",oe=se??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};B._finishReason.resolve(Y),B._totalUsage.resolve(oe),B._steps.resolve(V);const le=V[V.length-1];await I?.({finishReason:Y,totalUsage:oe,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:V}),O.setAttributes(wt({telemetry:t,attributes:{"ai.response.finishReason":Y,"ai.response.text":{output:()=>le.text},"ai.response.toolCalls":{output:()=>{var Ne;return(Ne=le.toolCalls)!=null&&Ne.length?JSON.stringify(le.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(le.providerMetadata),"ai.usage.inputTokens":oe.inputTokens,"ai.usage.outputTokens":oe.outputTokens,"ai.usage.totalTokens":oe.totalTokens,"ai.usage.reasoningTokens":oe.reasoningTokens,"ai.usage.cachedInputTokens":oe.cachedInputTokens}}))}catch(Y){W.error(Y)}finally{O.end()}}}),R=Fb();this.addStream=R.addStream,this.closeStream=R.close;const $=R.stream.getReader();let H=new ReadableStream({async start(W){W.enqueue({type:"start"})},async pull(W){function Y(){x?.({steps:V}),W.enqueue({type:"abort"}),W.close()}try{const{done:oe,value:le}=await $.read();if(oe){W.close();return}if(s?.aborted){Y();return}W.enqueue(le)}catch(oe){Cr(oe)&&s?.aborted?Y():W.error(oe)}},cancel(W){return R.stream.cancel(W)}});for(const W of g)H=H.pipeThrough(W({tools:c,stopStream(){R.terminate()}}));this.baseStream=H.pipeThrough(Jb(w)).pipeThrough(E);const{maxRetries:G,retry:fe}=Qp({maxRetries:o,abortSignal:s}),ae=Gp(t),N=Ka(n),D=Jp({model:e,telemetry:t,headers:r,settings:{...N,maxRetries:G}}),B=this;Yr({name:"ai.streamText",attributes:wt({telemetry:t,attributes:{...Kr({operationId:"ai.streamText",telemetry:t}),...D,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:ae,endWhenDone:!1,fn:async W=>{O=W;async function Y({currentStep:oe,responseMessages:le,usage:Ne}){var qe,X,me,st,be;const pt=B.includeRawChunks;z=new yo;const tr=await Hp({system:a,prompt:i,messages:l}),ft=[...tr.messages,...le],We=await y?.({model:e,steps:V,stepNumber:V.length,messages:ft}),St=Eo((qe=We?.model)!=null?qe:e),yr=await zp({prompt:{system:(X=We?.system)!=null?X:tr.system,messages:(me=We?.messages)!=null?me:ft},supportedUrls:await St.supportedUrls,download:U}),{toolChoice:wr,tools:gn}=Dp({tools:c,toolChoice:(st=We?.toolChoice)!=null?st:u,activeTools:(be=We?.activeTools)!=null?be:h}),{result:{stream:aa,response:He,request:rr},doStreamSpan:nr,startTimestampMs:b2}=await fe(()=>Yr({name:"ai.streamText.doStream",attributes:wt({telemetry:t,attributes:{...Kr({operationId:"ai.streamText.doStream",telemetry:t}),...D,"ai.model.provider":St.provider,"ai.model.id":St.modelId,"ai.prompt.messages":{input:()=>Wp(yr)},"ai.prompt.tools":{input:()=>gn?.map(he=>JSON.stringify(he))},"ai.prompt.toolChoice":{input:()=>wr!=null?JSON.stringify(wr):void 0},"gen_ai.system":St.provider,"gen_ai.request.model":St.modelId,"gen_ai.request.frequency_penalty":N.frequencyPenalty,"gen_ai.request.max_tokens":N.maxOutputTokens,"gen_ai.request.presence_penalty":N.presencePenalty,"gen_ai.request.stop_sequences":N.stopSequences,"gen_ai.request.temperature":N.temperature,"gen_ai.request.top_k":N.topK,"gen_ai.request.top_p":N.topP}}),tracer:ae,endWhenDone:!1,fn:async he=>({startTimestampMs:f(),doStreamSpan:he,result:await St.doStream({...N,tools:gn,toolChoice:wr,responseFormat:w?.responseFormat,prompt:yr,providerOptions:m,abortSignal:s,headers:r,includeRawChunks:pt})})})),hC=Hb({tools:c,generatorStream:aa,tracer:ae,telemetry:t,system:a,messages:ft,repairToolCall:d,abortSignal:s,experimental_context:P}),mC=rr??{},ia=[],ec=[];let tc;const rc={};let vn="unknown",Nt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},nc,k2=!0,Bt={id:k(),timestamp:b(),modelId:e.modelId},S2="";B.addStream(hC.pipeThrough(new TransformStream({async transform(he,Ke){var so,ao,la,or;if(he.type==="stream-start"){tc=he.warnings;return}if(k2){const at=f()-b2;k2=!1,nr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":at}),nr.setAttributes({"ai.response.msToFirstChunk":at}),Ke.enqueue({type:"start-step",request:mC,warnings:tc??[]})}const C2=he.type;switch(C2){case"text-start":case"text-end":{Ke.enqueue(he);break}case"text-delta":{he.delta.length>0&&(Ke.enqueue({type:"text-delta",id:he.id,text:he.delta,providerMetadata:he.providerMetadata}),S2+=he.delta);break}case"reasoning-start":case"reasoning-end":{Ke.enqueue(he);break}case"reasoning-delta":{Ke.enqueue({type:"reasoning-delta",id:he.id,text:he.delta,providerMetadata:he.providerMetadata});break}case"tool-call":{Ke.enqueue(he),ia.push(he);break}case"tool-result":{Ke.enqueue(he),he.preliminary||ec.push(he);break}case"tool-error":{Ke.enqueue(he),ec.push(he);break}case"response-metadata":{Bt={id:(so=he.id)!=null?so:Bt.id,timestamp:(ao=he.timestamp)!=null?ao:Bt.timestamp,modelId:(la=he.modelId)!=null?la:Bt.modelId};break}case"finish":{Nt=he.usage,vn=he.finishReason,nc=he.providerMetadata;const at=f()-b2;nr.addEvent("ai.stream.finish"),nr.setAttributes({"ai.response.msToFinish":at,"ai.response.avgOutputTokensPerSecond":1e3*((or=Nt.outputTokens)!=null?or:0)/at});break}case"file":{Ke.enqueue(he);break}case"source":{Ke.enqueue(he);break}case"tool-input-start":{rc[he.id]=he.toolName;const at=c?.[he.toolName];at?.onInputStart!=null&&await at.onInputStart({toolCallId:he.id,messages:ft,abortSignal:s,experimental_context:P}),Ke.enqueue({...he,dynamic:at?.type==="dynamic"});break}case"tool-input-end":{delete rc[he.id],Ke.enqueue(he);break}case"tool-input-delta":{const at=rc[he.id],oc=c?.[at];oc?.onInputDelta!=null&&await oc.onInputDelta({inputTextDelta:he.delta,toolCallId:he.id,messages:ft,abortSignal:s,experimental_context:P}),Ke.enqueue(he);break}case"error":{Ke.enqueue(he),vn="error";break}case"raw":{pt&&Ke.enqueue(he);break}default:{const at=C2;throw new Error(`Unknown chunk type: ${at}`)}}},async flush(he){const Ke=ia.length>0?JSON.stringify(ia):void 0;try{nr.setAttributes(wt({telemetry:t,attributes:{"ai.response.finishReason":vn,"ai.response.text":{output:()=>S2},"ai.response.toolCalls":{output:()=>Ke},"ai.response.id":Bt.id,"ai.response.model":Bt.modelId,"ai.response.timestamp":Bt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(nc),"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,"gen_ai.response.finish_reasons":[vn],"gen_ai.response.id":Bt.id,"gen_ai.response.model":Bt.modelId,"gen_ai.usage.input_tokens":Nt.inputTokens,"gen_ai.usage.output_tokens":Nt.outputTokens}}))}catch{}finally{nr.end()}he.enqueue({type:"finish-step",finishReason:vn,usage:Nt,providerMetadata:nc,response:{...Bt,headers:He?.headers}});const so=Kp(Ne,Nt);await z.promise;const ao=ia.filter(or=>or.providerExecuted!==!0),la=ec.filter(or=>or.providerExecuted!==!0);if(ao.length>0&&la.length===ao.length&&!await o0({stopConditions:p,steps:V})){le.push(...ti({content:V[V.length-1].content,tools:c}));try{await Y({currentStep:oe+1,responseMessages:le,usage:so})}catch(or){he.enqueue({type:"error",error:or}),B.closeStream()}}else he.enqueue({type:"finish",finishReason:vn,totalUsage:so}),B.closeStream()}})))}await Y({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(W=>{B.addStream(new ReadableStream({start(Y){Y.enqueue({type:"error",error:W}),Y.close()}})),B.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ro(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ro(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Zb({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new op;return Ro(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=Fr}={}){const c=t!=null?Ab({originalMessages:e,responseMessageId:t}):void 0,u={},g=d=>{var p,w;const m=u[d];return((w=(p=this.tools)==null?void 0:p[m])==null?void 0:w.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(d,p)=>{const w=n?.({part:d}),m=d.type;switch(m){case"text-start":{p.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{p.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{p.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{p.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{o&&p.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{p.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{p.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{s&&d.sourceType==="url"&&p.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),s&&d.sourceType==="document"&&p.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const y=g(d.id);p.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{p.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const y=g(d.toolCallId);d.invalid?p.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(d.error)}):p.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=g(d.toolCallId);p.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=g(d.toolCallId);p.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{p.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{p.enqueue({type:"start-step"});break}case"finish-step":{p.enqueue({type:"finish-step"});break}case"start":{a&&p.enqueue({type:"start",...w!=null?{messageMetadata:w}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&p.enqueue({type:"finish",finishReason:d.finishReason,...w!=null?{messageMetadata:w}:{}});break}case"abort":{p.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const y=m;throw new Error(`Unknown chunk type: ${y}`)}}w!=null&&m!=="start"&&m!=="finish"&&p.enqueue({type:"message-metadata",messageMetadata:w})}}));return Ro(zb({stream:h,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}={}){Db({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){Mb({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 Nb({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 Ob({textStream:this.textStream,...e})}};En({prefix:"aiobj",size:24}),En({prefix:"aiobj",size:24});var Wb={};j3(Wb,{object:()=>Yb,text:()=>Kb});var Kb=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Yb=({schema:e})=>{const t=ko(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await p0(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const o=n.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:r},n){const o=await Tr({text:r});if(!o.success)throw new vp({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const s=await Tt({value:o.value,schema:t});if(!s.success)throw new vp({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return s.value}}};let oi;oi=globalThis.crypto;async function Qb(e){return(await oi).getRandomValues(new Uint8Array(e))}async function Xb(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await Qb(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function e9(e){return await Xb(e)}async function t9(e){const t=await(await oi).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function m0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await e9(e),r=await t9(t);return{code_verifier:t,code_challenge:r}}var r9="AI_MCPClientError",g0=`vercel.ai.error.${r9}`,n9=Symbol.for(g0),v0,_0,Ie=class extends(_0=ue,v0=n9,_0){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[v0]=!0,this.data=n,this.code=o}static isInstance(e){return ue.hasMarker(e,g0)}},Qr="2025-06-18",o9=[Qr,"2025-03-26","2024-11-05"],s9=ze({name:v(),version:v()}),Po=ze({_meta:K(T({}).loose())}),Gt=Po,y0=T({method:v(),params:K(Po)}),w0=T({applyDefaults:K(ce())}).loose(),a9=ze({experimental:K(T({}).loose()),logging:K(T({}).loose()),prompts:K(ze({listChanged:K(ce())})),resources:K(ze({subscribe:K(ce()),listChanged:K(ce())})),tools:K(ze({listChanged:K(ce())})),elicitation:K(w0)});T({elicitation:K(w0)}).loose();var i9=Gt.extend({protocolVersion:v(),capabilities:a9,serverInfo:s9,instructions:K(v())}),si=Gt.extend({nextCursor:K(v())}),l9=T({name:v(),description:K(v()),inputSchema:T({type:L("object"),properties:K(T({}).loose())}).loose()}).loose(),c9=si.extend({tools:A(l9)}),b0=T({type:L("text"),text:v()}).loose(),k0=T({type:L("image"),data:Au(),mimeType:v()}).loose(),u9=T({uri:v(),name:v(),title:K(v()),description:K(v()),mimeType:K(v()),size:K(q())}).loose(),d9=si.extend({resources:A(u9)}),S0=T({uri:v(),name:K(v()),title:K(v()),mimeType:K(v())}).loose(),C0=S0.extend({text:v()}),T0=S0.extend({blob:Au()}),$0=T({type:L("resource"),resource:ne([C0,T0])}).loose(),p9=Gt.extend({content:A(ne([b0,k0,$0])),isError:ce().default(!1).optional()}).or(Gt.extend({toolResult:$e()})),f9=T({uriTemplate:v(),name:v(),title:K(v()),description:K(v()),mimeType:K(v())}).loose(),h9=Gt.extend({resourceTemplates:A(f9)}),m9=Gt.extend({contents:A(ne([C0,T0]))}),g9=T({name:v(),description:K(v()),required:K(ce())}).loose(),v9=T({name:v(),title:K(v()),description:K(v()),arguments:K(A(g9))}).loose(),_9=si.extend({prompts:A(v9)}),y9=T({role:ne([L("user"),L("assistant")]),content:ne([b0,k0,$0])}).loose(),w9=Gt.extend({description:K(v()),messages:A(y9)}),b9=Po.extend({message:v(),requestedSchema:$e()}),E0=y0.extend({method:L("elicitation/create"),params:b9}),k9=Gt.extend({action:ne([L("accept"),L("decline"),L("cancel")]),content:K(ve(v(),$e()))}),Oo="2.0",S9=T({jsonrpc:L(Oo),id:ne([v(),q().int()])}).merge(y0).strict(),C9=T({jsonrpc:L(Oo),id:ne([v(),q().int()]),result:Gt}).strict(),T9=T({jsonrpc:L(Oo),id:ne([v(),q().int()]),error:T({code:q().int(),message:v(),data:K($e())})}).strict(),$9=T({jsonrpc:L(Oo)}).merge(T({method:v(),params:K(Po)})).strict(),Un=ne([S9,$9,C9,T9]),I0=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",x0=T({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:q().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),lt=v().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bu.custom,message:"URL must be parseable",fatal:!0}),Vc}).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"}),E9=T({resource:v().url(),authorization_servers:A(lt).optional(),jwks_uri:v().url().optional(),scopes_supported:A(v()).optional(),bearer_methods_supported:A(v()).optional(),resource_signing_alg_values_supported:A(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ce().optional(),authorization_details_types_supported:A(v()).optional(),dpop_signing_alg_values_supported:A(v()).optional(),dpop_bound_access_tokens_required:ce().optional()}).passthrough(),R0=T({issuer:v(),authorization_endpoint:lt,token_endpoint:lt,registration_endpoint:lt.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),grant_types_supported:A(v()).optional(),code_challenge_methods_supported:A(v()),token_endpoint_auth_methods_supported:A(v()).optional(),token_endpoint_auth_signing_alg_values_supported:A(v()).optional()}).passthrough(),I9=T({issuer:v(),authorization_endpoint:lt,token_endpoint:lt,userinfo_endpoint:lt.optional(),jwks_uri:lt,registration_endpoint:lt.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),grant_types_supported:A(v()).optional(),subject_types_supported:A(v()),id_token_signing_alg_values_supported:A(v()),claims_supported:A(v()).optional(),token_endpoint_auth_methods_supported:A(v()).optional()}).passthrough(),x9=I9.merge(R0.pick({code_challenge_methods_supported:!0})),R9=T({client_id:v(),client_secret:v().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional()}).strip(),P9=T({redirect_uris:A(lt),token_endpoint_auth_method:v().optional(),grant_types:A(v()).optional(),response_types:A(v()).optional(),client_name:v().optional(),client_uri:lt.optional(),logo_uri:lt.optional(),scope:v().optional(),contacts:A(v()).optional(),tos_uri:lt.optional(),policy_uri:v().optional(),jwks_uri:lt.optional(),jwks:et().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),O9=T({error:v(),error_description:v().optional(),error_uri:v().optional()}),M9=P9.merge(R9),N9="AI_MCPClientOAuthError",P0=`vercel.ai.error.${N9}`,A9=Symbol.for(P0),O0,M0,zn=class extends(M0=ue,O0=A9,M0){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[O0]=!0}static isInstance(e){return ue.hasMarker(e,P0)}},Xr=class extends zn{};Xr.errorCode="server_error";var Mo=class extends zn{};Mo.errorCode="invalid_client";var No=class extends zn{};No.errorCode="invalid_grant";var Ao=class extends zn{};Ao.errorCode="unauthorized_client";var q9={[Xr.errorCode]:Xr,[Mo.errorCode]:Mo,[No.errorCode]:No,[Ao.errorCode]:Ao};function L9(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function j9({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 qo=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Lo(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 U9(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function ai(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?ai(e,void 0,r):void 0;throw n}}async function N0(e,t,r=fetch){return await ai(e,{"MCP-Protocol-Version":t},r)}function z9(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function D9(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:Qr;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=U9(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await N0(l,i,r);if(!n?.metadataUrl&&z9(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await N0(u,i,r)}return c}async function Z9(e,t,r=fetch){const n=await D9(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 E9.parse(await n.json())}function F9(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 V9(e,{fetchFn:t=fetch,protocolVersion:r=Qr}={}){var n;const o={"MCP-Protocol-Version":r},s=F9(e);for(const{url:a,type:i}of s){const l=await ai(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 R0.parse(await l.json());{const c=x9.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 H9(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 m0(),g=u.code_verifier,h=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",h),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 A0(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 q0(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":B9(o,s,r);return;case"client_secret_post":J9(o,s,n);return;case"none":G9(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function B9(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 J9(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function G9(e,t){t.set("client_id",e)}async function ii(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=O9.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=q9[o]||Xr;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Xr({message:o})}}async function W9(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 h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(h,d,e,t);else{const w=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],m=A0(r,w);q0(m,r,h,d)}a&&d.set("resource",a.href);const p=await(l??fetch)(g,{method:"POST",headers:h,body:d});if(!p.ok)throw await ii(p);return x0.parse(await p.json())}async function K9(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"}),g=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,g,e,t);else{const d=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],p=A0(r,d);q0(p,r,u,g)}o&&g.set("resource",o.href);const h=await(a??fetch)(c,{method:"POST",headers:u,body:g});if(!h.ok)throw await ii(h);return x0.parse({refresh_token:n,...await h.json()})}async function Y9(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 ii(s);return M9.parse(await s.json())}async function jo(e,t){var r,n;try{return await li(e,t)}catch(o){if(o instanceof Mo||o instanceof Ao)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await li(e,t);if(o instanceof No)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await li(e,t);throw o}}async function Q9(e,t,r){const n=L9(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!j9({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 li(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await Z9(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await Q9(t,e,a),c=await V9(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 Y9(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 W9(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 K9(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 zn)||w instanceof Xr))throw w}const h=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:p}=await H9(i,{metadata:c,clientInformation:u,state:h,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(p),await e.redirectToAuthorization(d),"REDIRECT"}var X9=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":Qr};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return cr(t,`ai-sdk/${I0}`,xn())}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=Lo(u);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new qo;return(s=this.onerror)==null||s.call(this,w),t(w)}}catch(p){return(a=this.onerror)==null||a.call(this,p),t(p)}return r(!0)}if(!u.ok||!u.body){let p=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(p+=". This server does not support SSE transport. Try using `http` transport instead");const w=new Ie({message:p});return(i=this.onerror)==null||i.call(this,w),t(w)}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader(),d=async()=>{var p,w,m;try{for(;;){const{done:y,value:_}=await h.read();if(y){if(this.connected)throw this.connected=!1,new Ie({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:f,data:b}=_;if(f==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new Ie({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=Un.parse(JSON.parse(b));(p=this.onmessage)==null||p.call(this,k)}catch(k){const S=new Ie({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(w=this.onerror)==null||w.call(this,S)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(m=this.onerror)==null||m.call(this,y),t(y)}};this.sseConnection={close:()=>h.cancel()},d()}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 Ie({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=Lo(g);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new qo;(s=this.onerror)==null||s.call(this,d);return}}catch(h){(a=this.onerror)==null||a.call(this,h);return}return r(!0)}if(!g.ok){const h=await g.text().catch(()=>null),d=new Ie({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${g.status}): ${h}`});(i=this.onerror)==null||i.call(this,d);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},e4=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":Qr};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 cr(t,`ai-sdk/${I0}`,xn())}async start(){if(this.abortController)throw new Ie({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},h=await fetch(this.url,g),d=h.headers.get("mcp-session-id");if(d&&(this.sessionId=d),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Lo(h);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new qo}catch(m){throw(o=this.onerror)==null||o.call(this,m),m}return t(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const m=await h.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${m}`;h.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const _=new Ie({message:y});throw(s=this.onerror)==null||s.call(this,_),_}const p=h.headers.get("content-type")||"";if(p.includes("application/json")){const m=await h.json(),y=Array.isArray(m)?m.map(_=>Un.parse(_)):[Un.parse(m)];for(const _ of y)(a=this.onmessage)==null||a.call(this,_);return}if(p.includes("text/event-stream")){if(!h.body){const f=new Ie({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,f),f}const y=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader();(async()=>{var f,b,k;try{for(;;){const{done:S,value:C}=await y.read();if(S)return;const{event:I,data:x}=C;if(I==="message")try{const M=Un.parse(JSON.parse(x));(f=this.onmessage)==null||f.call(this,M)}catch(M){const P=new Ie({message:"MCP HTTP Transport Error: Failed to parse message",cause:M});(b=this.onerror)==null||b.call(this,P)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const w=new Ie({message:`MCP HTTP Transport Error: Unexpected content type: ${p}`});throw(l=this.onerror)==null||l.call(this,w),w}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 Ie({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=Lo(c);try{if(await jo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new qo;(n=this.onerror)==null||n.call(this,w);return}}catch(p){(o=this.onerror)==null||o.call(this,p);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const p=new Ie({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,p);return}const h=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader(),d=async()=>{var p,w,m,y;try{for(;;){const{done:_,value:f}=await h.read();if(_)return;const{event:b,data:k,id:S}=f;if(S&&(this.lastInboundEventId=S),b==="message")try{const C=Un.parse(JSON.parse(k));(p=this.onmessage)==null||p.call(this,C)}catch(C){const I=new Ie({message:"MCP HTTP Transport Error: Failed to parse message",cause:C});(w=this.onerror)==null||w.call(this,I)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(m=this.onerror)==null||m.call(this,_),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,d()}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 t4(e){switch(e.type){case"sse":return new X9(e);case"http":return new e4(e);default:throw new Ie({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function r4(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var n4="1.0.0";async function o4(e){const t=new s4(e);return await t.init(),t}var s4=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=n4,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},r4(e)?this.transport=e:this.transport=t4(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 Ie({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:Qr,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:i9});if(e===void 0)throw new Ie({message:"Server sent invalid initialize result"});if(!o9.includes(e.protocolVersion))throw new Ie({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 Ie({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Ie({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Ie({message:"Server does not support prompts"});break;default:throw new Ie({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Ie({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 Ie({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 Ie({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}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:c9,options:t})}catch(r){throw r}}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:p9,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:d9,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:m9,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:h9,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:_9,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:w9,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"}={}){var t;const r={};try{const n=await this.listTools();for(const{name:o,description:s,inputSchema:a}of n.tools){if(e!=="automatic"&&!(o in e))continue;const i=this,l=async(u,g)=>{var h;return(h=g?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:o,args:u,options:g})},c=e==="automatic"?td({description:s,inputSchema:Rn({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};r[o]=c}return r}catch(n){throw n}}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})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==E0)throw new Ie({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=E0.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=k9.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 Ie({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 Ie({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Ie({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function Uo(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function L0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Uo(t.headers),...Uo(n.headers)}:t.headers};return e(r,o)}:e}const zo="2025-11-25",a4=[zo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Wt="io.modelcontextprotocol/related-task",Do="2.0",zt=Vu(e=>e!==null&&(typeof e=="object"||typeof e=="function")),j0=ne([v(),q().int()]),U0=v(),i4=ze({ttl:ne([q(),wa()]).optional(),pollInterval:q().optional()}),ci=ze({taskId:v()}),l4=ze({progressToken:j0.optional(),[Wt]:ci.optional()}),ct=ze({task:i4.optional(),_meta:l4.optional()}),Be=T({method:v(),params:ct.optional()}),Pr=ze({_meta:T({[Wt]:K(ci)}).passthrough().optional()}),bt=T({method:v(),params:Pr.optional()}),Ye=ze({_meta:ze({[Wt]:ci.optional()}).optional()}),Zo=ne([v(),q().int()]),z0=T({jsonrpc:L(Do),id:Zo,...Be.shape}).strict(),ui=e=>z0.safeParse(e).success,D0=T({jsonrpc:L(Do),...bt.shape}).strict(),c4=e=>D0.safeParse(e).success,Z0=T({jsonrpc:L(Do),id:Zo,result:Ye}).strict(),Dn=e=>Z0.safeParse(e).success;var ge;(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"})(ge||(ge={}));const F0=T({jsonrpc:L(Do),id:Zo,error:T({code:q().int(),message:v(),data:K($e())})}).strict(),u4=e=>F0.safeParse(e).success,Or=ne([z0,D0,Z0,F0]),Mr=Ye.strict(),d4=Pr.extend({requestId:Zo,reason:v().optional()}),di=bt.extend({method:L("notifications/cancelled"),params:d4}),p4=T({src:v(),mimeType:v().optional(),sizes:A(v()).optional()}),Zn=T({icons:A(p4).optional()}),en=T({name:v(),title:v().optional()}),V0=en.extend({...en.shape,...Zn.shape,version:v(),websiteUrl:v().optional()}),f4=ba(T({applyDefaults:ce().optional()}),ve(v(),$e())),h4=Hu(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ba(T({form:f4.optional(),url:zt.optional()}),ve(v(),$e()).optional())),m4=T({list:K(T({}).passthrough()),cancel:K(T({}).passthrough()),requests:K(T({sampling:K(T({createMessage:K(T({}).passthrough())}).passthrough()),elicitation:K(T({create:K(T({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),g4=T({list:K(T({}).passthrough()),cancel:K(T({}).passthrough()),requests:K(T({tools:K(T({call:K(T({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),v4=T({experimental:ve(v(),zt).optional(),sampling:T({context:zt.optional(),tools:zt.optional()}).optional(),elicitation:h4.optional(),roots:T({listChanged:ce().optional()}).optional(),tasks:K(m4)}),_4=ct.extend({protocolVersion:v(),capabilities:v4,clientInfo:V0}),y4=Be.extend({method:L("initialize"),params:_4}),w4=T({experimental:ve(v(),zt).optional(),logging:zt.optional(),completions:zt.optional(),prompts:K(T({listChanged:K(ce())})),resources:T({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:T({listChanged:ce().optional()}).optional(),tasks:K(g4)}).passthrough(),H0=Ye.extend({protocolVersion:v(),capabilities:w4,serverInfo:V0,instructions:v().optional()}),B0=bt.extend({method:L("notifications/initialized")}),b4=e=>B0.safeParse(e).success,pi=Be.extend({method:L("ping")}),k4=T({progress:q(),total:K(q()),message:K(v())}),S4=T({...Pr.shape,...k4.shape,progressToken:j0}),fi=bt.extend({method:L("notifications/progress"),params:S4}),C4=ct.extend({cursor:U0.optional()}),Fn=Be.extend({params:C4.optional()}),Vn=Ye.extend({nextCursor:K(U0)}),Hn=T({taskId:v(),status:_e(["working","input_required","completed","failed","cancelled"]),ttl:ne([q(),wa()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:K(q()),statusMessage:K(v())}),Bn=Ye.extend({task:Hn}),T4=Pr.merge(Hn),Fo=bt.extend({method:L("notifications/tasks/status"),params:T4}),hi=Be.extend({method:L("tasks/get"),params:ct.extend({taskId:v()})}),mi=Ye.merge(Hn),gi=Be.extend({method:L("tasks/result"),params:ct.extend({taskId:v()})}),vi=Fn.extend({method:L("tasks/list")}),_i=Vn.extend({tasks:A(Hn)}),$4=Be.extend({method:L("tasks/cancel"),params:ct.extend({taskId:v()})}),E4=Ye.merge(Hn),J0=T({uri:v(),mimeType:K(v()),_meta:ve(v(),$e()).optional()}),G0=J0.extend({text:v()}),yi=v().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),W0=J0.extend({blob:yi}),tn=T({audience:A(_e(["user","assistant"])).optional(),priority:q().min(0).max(1).optional(),lastModified:Ru({offset:!0}).optional()}),K0=T({...en.shape,...Zn.shape,uri:v(),description:K(v()),mimeType:K(v()),annotations:tn.optional(),_meta:K(ze({}))}),I4=T({...en.shape,...Zn.shape,uriTemplate:v(),description:K(v()),mimeType:K(v()),annotations:tn.optional(),_meta:K(ze({}))}),x4=Fn.extend({method:L("resources/list")}),Y0=Vn.extend({resources:A(K0)}),R4=Fn.extend({method:L("resources/templates/list")}),Q0=Vn.extend({resourceTemplates:A(I4)}),wi=ct.extend({uri:v()}),P4=wi,O4=Be.extend({method:L("resources/read"),params:P4}),X0=Ye.extend({contents:A(ne([G0,W0]))}),ef=bt.extend({method:L("notifications/resources/list_changed")}),M4=wi,N4=Be.extend({method:L("resources/subscribe"),params:M4}),A4=wi,q4=Be.extend({method:L("resources/unsubscribe"),params:A4}),L4=Pr.extend({uri:v()}),tf=bt.extend({method:L("notifications/resources/updated"),params:L4}),j4=T({name:v(),description:K(v()),required:K(ce())}),U4=T({...en.shape,...Zn.shape,description:K(v()),arguments:K(A(j4)),_meta:K(ze({}))}),z4=Fn.extend({method:L("prompts/list")}),rf=Vn.extend({prompts:A(U4)}),D4=ct.extend({name:v(),arguments:ve(v(),v()).optional()}),Z4=Be.extend({method:L("prompts/get"),params:D4}),bi=T({type:L("text"),text:v(),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),ki=T({type:L("image"),data:yi,mimeType:v(),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),Si=T({type:L("audio"),data:yi,mimeType:v(),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),F4=T({type:L("tool_use"),name:v(),id:v(),input:T({}).passthrough(),_meta:K(T({}).passthrough())}).passthrough(),V4=T({type:L("resource"),resource:ne([G0,W0]),annotations:tn.optional(),_meta:ve(v(),$e()).optional()}),H4=K0.extend({type:L("resource_link")}),Ci=ne([bi,ki,Si,H4,V4]),B4=T({role:_e(["user","assistant"]),content:Ci}),nf=Ye.extend({description:K(v()),messages:A(B4)}),of=bt.extend({method:L("notifications/prompts/list_changed")}),J4=T({title:v().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),G4=T({taskSupport:_e(["required","optional","forbidden"]).optional()}),sf=T({...en.shape,...Zn.shape,description:v().optional(),inputSchema:T({type:L("object"),properties:ve(v(),zt).optional(),required:A(v()).optional()}).catchall($e()),outputSchema:T({type:L("object"),properties:ve(v(),zt).optional(),required:A(v()).optional()}).catchall($e()).optional(),annotations:K(J4),execution:K(G4),_meta:ve(v(),$e()).optional()}),W4=Fn.extend({method:L("tools/list")}),af=Vn.extend({tools:A(sf)}),Jn=Ye.extend({content:A(Ci).default([]),structuredContent:ve(v(),$e()).optional(),isError:K(ce())});Jn.or(Ye.extend({toolResult:$e()}));const K4=ct.extend({name:v(),arguments:K(ve(v(),$e()))}),Y4=Be.extend({method:L("tools/call"),params:K4}),lf=bt.extend({method:L("notifications/tools/list_changed")}),cf=_e(["debug","info","notice","warning","error","critical","alert","emergency"]),Q4=ct.extend({level:cf}),X4=Be.extend({method:L("logging/setLevel"),params:Q4}),e6=Pr.extend({level:cf,logger:v().optional(),data:$e()}),uf=bt.extend({method:L("notifications/message"),params:e6}),t6=T({name:v().optional()}),r6=T({hints:K(A(t6)),costPriority:K(q().min(0).max(1)),speedPriority:K(q().min(0).max(1)),intelligencePriority:K(q().min(0).max(1))}),n6=T({mode:K(_e(["auto","required","none"]))}),o6=T({type:L("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:A(Ci).default([]),structuredContent:T({}).passthrough().optional(),isError:K(ce()),_meta:K(T({}).passthrough())}).passthrough(),s6=Ze("type",[bi,ki,Si]),Vo=Ze("type",[bi,ki,Si,F4,o6]),a6=T({role:_e(["user","assistant"]),content:ne([Vo,A(Vo)]),_meta:K(T({}).passthrough())}).passthrough(),i6=ct.extend({messages:A(a6),modelPreferences:r6.optional(),systemPrompt:v().optional(),includeContext:_e(["none","thisServer","allServers"]).optional(),temperature:q().optional(),maxTokens:q().int(),stopSequences:A(v()).optional(),metadata:zt.optional(),tools:K(A(sf)),toolChoice:K(n6)}),Ti=Be.extend({method:L("sampling/createMessage"),params:i6}),$i=Ye.extend({model:v(),stopReason:K(_e(["endTurn","stopSequence","maxTokens"]).or(v())),role:_e(["user","assistant"]),content:s6}),l6=Ye.extend({model:v(),stopReason:K(_e(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:_e(["user","assistant"]),content:ne([Vo,A(Vo)])}),c6=T({type:L("boolean"),title:v().optional(),description:v().optional(),default:ce().optional()}),u6=T({type:L("string"),title:v().optional(),description:v().optional(),minLength:q().optional(),maxLength:q().optional(),format:_e(["email","uri","date","date-time"]).optional(),default:v().optional()}),d6=T({type:_e(["number","integer"]),title:v().optional(),description:v().optional(),minimum:q().optional(),maximum:q().optional(),default:q().optional()}),p6=T({type:L("string"),title:v().optional(),description:v().optional(),enum:A(v()),default:v().optional()}),f6=T({type:L("string"),title:v().optional(),description:v().optional(),oneOf:A(T({const:v(),title:v()})),default:v().optional()}),h6=T({type:L("string"),title:v().optional(),description:v().optional(),enum:A(v()),enumNames:A(v()).optional(),default:v().optional()}),m6=ne([p6,f6]),g6=T({type:L("array"),title:v().optional(),description:v().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({type:L("string"),enum:A(v())}),default:A(v()).optional()}),v6=T({type:L("array"),title:v().optional(),description:v().optional(),minItems:q().optional(),maxItems:q().optional(),items:T({anyOf:A(T({const:v(),title:v()}))}),default:A(v()).optional()}),_6=ne([g6,v6]),y6=ne([h6,m6,_6]),w6=ne([y6,c6,u6,d6]),b6=ct.extend({mode:L("form").optional(),message:v(),requestedSchema:T({type:L("object"),properties:ve(v(),w6),required:A(v()).optional()})}),k6=ct.extend({mode:L("url"),message:v(),elicitationId:v(),url:v().url()}),S6=ne([b6,k6]),Ei=Be.extend({method:L("elicitation/create"),params:S6}),C6=Pr.extend({elicitationId:v()}),T6=bt.extend({method:L("notifications/elicitation/complete"),params:C6}),Ii=Ye.extend({action:_e(["accept","decline","cancel"]),content:Hu(e=>e===null?void 0:e,ve(v(),ne([v(),q(),ce(),A(v())])).optional())}),$6=T({type:L("ref/resource"),uri:v()}),E6=T({type:L("ref/prompt"),name:v()}),I6=ct.extend({ref:ne([E6,$6]),argument:T({name:v(),value:v()}),context:T({arguments:ve(v(),v()).optional()}).optional()}),x6=Be.extend({method:L("completion/complete"),params:I6}),df=Ye.extend({completion:ze({values:A(v()).max(100),total:K(q().int()),hasMore:K(ce())})}),R6=T({uri:v().startsWith("file://"),name:v().optional(),_meta:ve(v(),$e()).optional()}),pf=Be.extend({method:L("roots/list")}),ff=Ye.extend({roots:A(R6)}),P6=bt.extend({method:L("notifications/roots/list_changed")});ne([pi,y4,x6,X4,Z4,z4,x4,R4,O4,N4,q4,Y4,W4,hi,gi,vi]),ne([di,fi,B0,P6,Fo]),ne([Mr,$i,l6,Ii,ff,mi,_i,Bn]),ne([pi,Ti,Ei,pf,hi,gi,vi]),ne([di,fi,uf,tf,ef,lf,of,Fo,T6]),ne([Mr,H0,df,nf,rf,Y0,Q0,X0,Jn,af,mi,_i,Bn]);class de 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===ge.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new O6(o.elicitations,r)}return new de(t,r,n)}}class O6 extends de{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ge.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){var t,r;return(r=(t=this.data)===null||t===void 0?void 0:t.elicitations)!==null&&r!==void 0?r:[]}}const Je=Gv().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bu.custom,message:"URL must be parseable",fatal:!0}),Vc}).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"}),M6=ze({resource:v().url(),authorization_servers:A(Je).optional(),jwks_uri:v().url().optional(),scopes_supported:A(v()).optional(),bearer_methods_supported:A(v()).optional(),resource_signing_alg_values_supported:A(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ce().optional(),authorization_details_types_supported:A(v()).optional(),dpop_signing_alg_values_supported:A(v()).optional(),dpop_bound_access_tokens_required:ce().optional()}),hf=ze({issuer:v(),authorization_endpoint:Je,token_endpoint:Je,registration_endpoint:Je.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),response_modes_supported:A(v()).optional(),grant_types_supported:A(v()).optional(),token_endpoint_auth_methods_supported:A(v()).optional(),token_endpoint_auth_signing_alg_values_supported:A(v()).optional(),service_documentation:Je.optional(),revocation_endpoint:Je.optional(),revocation_endpoint_auth_methods_supported:A(v()).optional(),revocation_endpoint_auth_signing_alg_values_supported:A(v()).optional(),introspection_endpoint:v().optional(),introspection_endpoint_auth_methods_supported:A(v()).optional(),introspection_endpoint_auth_signing_alg_values_supported:A(v()).optional(),code_challenge_methods_supported:A(v()).optional(),client_id_metadata_document_supported:ce().optional()}),N6=ze({issuer:v(),authorization_endpoint:Je,token_endpoint:Je,userinfo_endpoint:Je.optional(),jwks_uri:Je,registration_endpoint:Je.optional(),scopes_supported:A(v()).optional(),response_types_supported:A(v()),response_modes_supported:A(v()).optional(),grant_types_supported:A(v()).optional(),acr_values_supported:A(v()).optional(),subject_types_supported:A(v()),id_token_signing_alg_values_supported:A(v()),id_token_encryption_alg_values_supported:A(v()).optional(),id_token_encryption_enc_values_supported:A(v()).optional(),userinfo_signing_alg_values_supported:A(v()).optional(),userinfo_encryption_alg_values_supported:A(v()).optional(),userinfo_encryption_enc_values_supported:A(v()).optional(),request_object_signing_alg_values_supported:A(v()).optional(),request_object_encryption_alg_values_supported:A(v()).optional(),request_object_encryption_enc_values_supported:A(v()).optional(),token_endpoint_auth_methods_supported:A(v()).optional(),token_endpoint_auth_signing_alg_values_supported:A(v()).optional(),display_values_supported:A(v()).optional(),claim_types_supported:A(v()).optional(),claims_supported:A(v()).optional(),service_documentation:v().optional(),claims_locales_supported:A(v()).optional(),ui_locales_supported:A(v()).optional(),claims_parameter_supported:ce().optional(),request_parameter_supported:ce().optional(),request_uri_parameter_supported:ce().optional(),require_request_uri_registration:ce().optional(),op_policy_uri:Je.optional(),op_tos_uri:Je.optional(),client_id_metadata_document_supported:ce().optional()}),A6=T({...N6.shape,...hf.pick({code_challenge_methods_supported:!0}).shape}),q6=T({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:Ju().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),L6=T({error:v(),error_description:v().optional(),error_uri:v().optional()}),mf=Je.optional().or(L("").transform(()=>{})),j6=T({redirect_uris:A(Je),token_endpoint_auth_method:v().optional(),grant_types:A(v()).optional(),response_types:A(v()).optional(),client_name:v().optional(),client_uri:Je.optional(),logo_uri:mf,scope:v().optional(),contacts:A(v()).optional(),tos_uri:mf,policy_uri:v().optional(),jwks_uri:Je.optional(),jwks:et().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),U6=T({client_id:v(),client_secret:v().optional(),client_id_issued_at:q().optional(),client_secret_expires_at:q().optional()}).strip(),z6=j6.merge(U6);T({error:v(),error_description:v().optional()}).strip(),T({token:v(),token_type_hint:v().optional()}).strip();function D6(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Z6({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 Ve 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 xi extends Ve{}xi.errorCode="invalid_request";class Ho extends Ve{}Ho.errorCode="invalid_client";class Bo extends Ve{}Bo.errorCode="invalid_grant";class Jo extends Ve{}Jo.errorCode="unauthorized_client";class Ri extends Ve{}Ri.errorCode="unsupported_grant_type";class Pi extends Ve{}Pi.errorCode="invalid_scope";class Oi extends Ve{}Oi.errorCode="access_denied";class rn extends Ve{}rn.errorCode="server_error";class Mi extends Ve{}Mi.errorCode="temporarily_unavailable";class Ni extends Ve{}Ni.errorCode="unsupported_response_type";class Ai extends Ve{}Ai.errorCode="unsupported_token_type";class qi extends Ve{}qi.errorCode="invalid_token";class Li extends Ve{}Li.errorCode="method_not_allowed";class ji extends Ve{}ji.errorCode="too_many_requests";class Go extends Ve{}Go.errorCode="invalid_client_metadata";class Ui extends Ve{}Ui.errorCode="insufficient_scope";class zi extends Ve{}zi.errorCode="invalid_target";const F6={[xi.errorCode]:xi,[Ho.errorCode]:Ho,[Bo.errorCode]:Bo,[Jo.errorCode]:Jo,[Ri.errorCode]:Ri,[Pi.errorCode]:Pi,[Oi.errorCode]:Oi,[rn.errorCode]:rn,[Mi.errorCode]:Mi,[Ni.errorCode]:Ni,[Ai.errorCode]:Ai,[qi.errorCode]:qi,[Li.errorCode]:Li,[ji.errorCode]:ji,[Go.errorCode]:Go,[Ui.errorCode]:Ui,[zi.errorCode]:zi};class kt extends Error{constructor(t){super(t??"Unauthorized")}}function V6(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Di="code",Zi="S256";function H6(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&&V6(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 B6(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":J6(o,s,r);return;case"client_secret_post":G6(o,s,n);return;case"none":W6(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function J6(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 G6(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function W6(e,t){t.set("client_id",e)}async function gf(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=L6.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=F6[o]||rn;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new rn(o)}}async function Nr(e,t){var r,n;try{return await Fi(e,t)}catch(o){if(o instanceof Ho||o instanceof Jo)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"all")),await Fi(e,t);if(o instanceof Bo)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"tokens")),await Fi(e,t);throw o}}async function Fi(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){var a,i;let l,c;try{l=await Q6(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",t));const u=await Y6(t,e,l),g=await n5(c,{fetchFn:s});let h=await Promise.resolve(e.clientInformation());if(!h){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const _=g?.client_id_metadata_document_supported===!0,f=e.clientMetadataUrl;if(f&&!K6(f))throw new Go(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${f}`);if(_&&f)h={client_id:f},await((a=e.saveClientInformation)===null||a===void 0?void 0:a.call(e,h));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const k=await l5(c,{metadata:g,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(k),h=k}}const d=!e.redirectUrl;if(r!==void 0||d){const _=await i5(e,c,{metadata:g,resource:u,authorizationCode:r,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const _=await a5(c,{metadata:g,clientInformation:h,refreshToken:p.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof Ve)||_ instanceof rn))throw _}const w=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await o5(c,{metadata:g,clientInformation:h,state:w,redirectUrl:e.redirectUrl,scope:n||((i=l?.scopes_supported)===null||i===void 0?void 0:i.join(" "))||e.clientMetadata.scope,resource:u});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}function K6(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Y6(e,t,r){const n=D6(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Z6({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 Wo(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Vi(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=Vi(e,"scope")||void 0,i=Vi(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function Vi(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 Q6(e,t,r=fetch){var n,o;const s=await t5(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!s||s.status===404)throw await((n=s?.body)===null||n===void 0?void 0:n.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!s.ok)throw await((o=s.body)===null||o===void 0?void 0:o.cancel()),new Error(`HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`);return M6.parse(await s.json())}async function Hi(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Hi(e,void 0,r):void 0;throw n}}function X6(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function vf(e,t,r=fetch){return await Hi(e,{"MCP-Protocol-Version":t},r)}function e5(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function t5(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!==null&&o!==void 0?o:zo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=X6(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:a),l.search=a.search}let c=await vf(l,i,r);if(!n?.metadataUrl&&e5(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await vf(u,i,r)}return c}function r5(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 n5(e,{fetchFn:t=fetch,protocolVersion:r=zo}={}){var n;const o={"MCP-Protocol-Version":r,Accept:"application/json"},s=r5(e);for(const{url:a,type:i}of s){const l=await Hi(a,o,t);if(l){if(!l.ok){if(await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?hf.parse(await l.json()):A6.parse(await l.json())}}}async function o5(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(Di))throw new Error(`Incompatible auth server: does not support response type ${Di}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Zi))throw new Error(`Incompatible auth server: does not support code challenge method ${Zi}`)}else i=new URL("/authorize",e);const l=await m0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Di),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Zi),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 s5(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function _f(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){var i;const l=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,l,t);else if(n){const g=(i=t?.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],h=H6(n,g);B6(h,n,c,r)}const u=await(a??fetch)(l,{method:"POST",headers:c,body:r});if(!u.ok)throw await gf(u);return q6.parse(await u.json())}async function a5(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 _f(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function i5(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=s5(o,c,e.redirectUrl)}const l=await e.clientInformation();return _f(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function l5(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 gf(s);return z6.parse(await s.json())}const c5={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class nn extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Ko{constructor(t,r){var n;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=L0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:c5}async _authThenStart(){var t;if(!this._authProvider)throw new kt("No auth provider");let r;try{r=await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(t=this.onerror)===null||t===void 0||t.call(this,n),n}if(r!=="AUTHORIZED")throw new kt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const r={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(r.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Uo((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...r,...n})}async _startOrAuthSse(t){var r,n,o,s;const{resumptionToken:a}=t;try{const i=await this._commonHeaders();i.set("Accept","text/event-stream"),a&&i.set("last-event-id",a);const l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:i,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((o=l.body)===null||o===void 0?void 0:o.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new nn(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,t,!0)}catch(i){throw(s=this.onerror)===null||s===void 0||s.call(this,i),i}}_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){var n;const o=this._reconnectionOptions.maxRetries;if(r>=o){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,r+1)})},s)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{var u,g,h,d;try{const p=t.pipeThrough(new TextDecoderStream).pipeThrough(new Vr({onRetry:y=>{this._serverRetryMs=y}})).getReader();for(;;){const{value:y,done:_}=await p.read();if(_)break;if(y.id&&(a=y.id,i=!0,o?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{const f=Or.parse(JSON.parse(y.data));Dn(f)&&(l=!0,s!==void 0&&(f.id=s)),(u=this.onmessage)===null||u===void 0||u.call(this,f)}catch(f){(g=this.onerror)===null||g===void 0||g.call(this,f)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(p){if((h=this.onerror)===null||h===void 0||h.call(this,new Error(`SSE stream disconnected: ${p}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(y){(d=this.onerror)===null||d===void 0||d.call(this,new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}})()}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 kt("No auth provider");if(await Nr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt("Failed to authorize")}async close(){var t,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)===null||t===void 0||t.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(t,r){var n,o,s,a,i,l,c;try{const{resumptionToken:u,onresumptiontoken:g}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:ui(t)?t.id:void 0}).catch(f=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,f)});return}const h=await this._commonHeaders();h.set("content-type","application/json"),h.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:h,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},p=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,d),w=p.headers.get("mcp-session-id");if(w&&(this._sessionId=w),!p.ok){const f=await p.text().catch(()=>null);if(p.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new nn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:b,scope:k}=Wo(p);if(this._resourceMetadataUrl=b,this._scope=k,await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(p.status===403&&this._authProvider){const{resourceMetadataUrl:b,scope:k,error:S}=Wo(p);if(S==="insufficient_scope"){const C=p.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===C)throw new nn(403,"Server returned 403 after trying upscoping");if(k&&(this._scope=k),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=C??void 0,await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new kt;return this.send(t)}}throw new nn(p.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,p.status===202){await((s=p.body)===null||s===void 0?void 0:s.cancel()),b4(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,f)});return}const y=(Array.isArray(t)?t:[t]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,_=p.headers.get("content-type");if(y)if(_?.includes("text/event-stream"))this._handleSseStream(p.body,{onresumptiontoken:g},!1);else if(_?.includes("application/json")){const f=await p.json(),b=Array.isArray(f)?f.map(k=>Or.parse(k)):[Or.parse(f)];for(const k of b)(a=this.onmessage)===null||a===void 0||a.call(this,k)}else throw await((i=p.body)===null||i===void 0?void 0:i.cancel()),new nn(-1,`Unexpected content type: ${_}`);else await((l=p.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var t,r,n,o;if(this._sessionId)try{const s=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:s,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,a);if(await((n=i.body)===null||n===void 0?void 0:n.cancel()),!i.ok&&i.status!==405)throw new nn(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class Yo{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Yo,r=new Yo;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(var t;this._messageQueue.length>0;){const r=this._messageQueue.shift();(t=this.onmessage)===null||t===void 0||t.call(this,r.message,r.extra)}}async close(){var t;const r=this._otherTransport;this._otherTransport=void 0,await r?.close(),(t=this.onclose)===null||t===void 0||t.call(this)}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}})}}function Dt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Gn(e){return Object.fromEntries([...e.headers])}var u5=({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 io({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},It=u5();function Bi(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var d5=["fetch failed","failed to fetch"];function p5({error:e,url:t,requestBodyValues:r}){if(Bi(e))return e;if(e instanceof TypeError&&d5.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Pe({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function f5(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 h5(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 yf(e,...t){const r=new Headers(h5(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var m5="3.0.19";function g5({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ar({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ar({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 ar({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ar({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function v5({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 _5(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 y5=/"__proto__"\s*:/,w5=/"constructor"\s*:/;function wf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||y5.test(e)===!1&&w5.test(e)===!1?t:b5(t)}function b5(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 wf(e)}try{return wf(e)}finally{Error.stackTraceLimit=t}}var Qo=Symbol.for("vercel.ai.validator");function k5(e){return{[Qo]:!0,validate:e}}function S5(e){return typeof e=="object"&&e!==null&&Qo in e&&e[Qo]===!0&&"validate"in e}function rt(e){let t;return()=>(t==null&&(t=e()),t)}function C5(e){return S5(e)?e:typeof e=="function"?e():T5(e)}function T5(e){return k5(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new At({value:t,cause:r.issues})}})}async function dr({value:e,schema:t}){const r=await Gi({value:e,schema:t});if(!r.success)throw At.wrap({value:e,cause:r.error});return r.value}async function Gi({value:e,schema:t}){const r=C5(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:At.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:At.wrap({value:e,cause:n}),rawValue:e}}}async function $5({text:e,schema:t}){try{const r=Ji(e);return t==null?r:dr({value:r,schema:t})}catch(r){throw sr.isInstance(r)||At.isInstance(r)?r:new sr({text:e,cause:r})}}async function bf({text:e,schema:t}){try{const r=Ji(e);return t==null?{success:!0,value:r,rawValue:r}:await Gi({value:r,schema:t})}catch(r){return{success:!1,error:sr.isInstance(r)?r:new sr({text:e,cause:r}),rawValue:void 0}}}function kf(e){try{return Ji(e),!0}catch{return!1}}function E5({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await bf({text:r,schema:t}))}}))}async function pr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Gi({value:t[e],schema:r});if(!n.success)throw new io({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var I5=()=>globalThis.fetch,Kt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Sf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),x5=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Sf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Sf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=I5()})=>{try{const i=await a(e,{method:"POST",headers:yf(t,`ai-sdk/provider-utils/${m5}`,f5()),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 Bi(u)||Pe.isInstance(u)?u:new Pe({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&&(Bi(c)||Pe.isInstance(c))?c:new Pe({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw p5({error:i,url:e,requestBodyValues:r.values})}};function _C(e){return e}function on({id:e,name:t,inputSchema:r,outputSchema:n}){return({execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:r,outputSchema:n,execute:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}var R5=({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 Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await $5({text:a,schema:e});return{responseHeaders:i,value:new Pe({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 Pe({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Wi=e=>async({response:t})=>{const r=Gn(t);if(t.body==null)throw new fc({});return{responseHeaders:r,value:E5({stream:t.body,schema:e})}},sn=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await bf({text:o,schema:e}),a=Gn(t);if(!s.success)throw new Pe({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}},P5=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Gn(e);if(!e.body)throw new Pe({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 Pe({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function Xo(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const r in t)t[r]=Xo(t[r])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>Xo(t)):e.items=Xo(e.items)),e}var O5=(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("/")},M5=Symbol("Let zodToJsonSchema decide on which parser to use"),Cf={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"},N5=e=>typeof e=="string"?{...Cf,name:e}:{...Cf,...e};function vt(){return{}}function A5(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)!==Q.ZodAny&&(s.items=xe(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 q5(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 L5(){return{type:"boolean"}}function Tf(e,t){return xe(e.type._def,t)}var j5=(e,t)=>xe(e.innerType._def,t);function $f(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>$f(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 U5(e)}}var U5=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 z5(e,t){return{...xe(e.innerType._def,t),default:e.defaultValue()}}function D5(e,t){return t.effectStrategy==="input"?xe(e.schema._def,t):vt()}function Z5(e){return{type:"string",enum:Array.from(e.values)}}var F5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function V5(e,t){const r=[xe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),xe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(F5(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 H5(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 Ki=void 0,xt={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:()=>(Ki===void 0&&(Ki=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ki),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 Ef(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":Rt(r,"email",n.message,t);break;case"format:idn-email":Rt(r,"idn-email",n.message,t);break;case"pattern:zod":nt(r,xt.email,n.message,t);break}break;case"url":Rt(r,"uri",n.message,t);break;case"uuid":Rt(r,"uuid",n.message,t);break;case"regex":nt(r,n.regex,n.message,t);break;case"cuid":nt(r,xt.cuid,n.message,t);break;case"cuid2":nt(r,xt.cuid2,n.message,t);break;case"startsWith":nt(r,RegExp(`^${Yi(n.value,t)}`),n.message,t);break;case"endsWith":nt(r,RegExp(`${Yi(n.value,t)}$`),n.message,t);break;case"datetime":Rt(r,"date-time",n.message,t);break;case"date":Rt(r,"date",n.message,t);break;case"time":Rt(r,"time",n.message,t);break;case"duration":Rt(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":{nt(r,RegExp(Yi(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Rt(r,"ipv4",n.message,t),n.version!=="v4"&&Rt(r,"ipv6",n.message,t);break}case"base64url":nt(r,xt.base64url,n.message,t);break;case"jwt":nt(r,xt.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&nt(r,xt.ipv4Cidr,n.message,t),n.version!=="v4"&&nt(r,xt.ipv6Cidr,n.message,t);break}case"emoji":nt(r,xt.emoji(),n.message,t);break;case"ulid":{nt(r,xt.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Rt(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{nt(r,xt.base64,n.message,t);break}}break}case"nanoid":nt(r,xt.nanoid,n.message,t)}return r}function Yi(e,t){return t.patternStrategy==="escape"?J5(e):e}var B5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function J5(e){let t="";for(let r=0;r<e.length;r++)B5.has(e[r])||(t+="\\"),t+=e[r];return t}function Rt(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 nt(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:If(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=If(t,n)}function If(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
57
+ `)}})}},Ef={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function R6({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new kf);if(o){const[i,a]=s.tee();s=i,o({stream:a})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:es(r,Ef)})}function x6({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 P6(e){return e.type.startsWith("data-")}function Tf(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,i=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);i&&a?r[n]=Tf(s,o):r[n]=o}return r}function O6(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 i(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"&&i(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"&&i(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"&&i(c,l)):r=l;break}}}let a=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';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":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?a+="true".slice(u.length):"false".startsWith(u)?a+="false".slice(u.length):"null".startsWith(u)&&(a+="null".slice(u.length))}}return a}async function If(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Nr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Nr({text:O6(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Bi(e){return e.type.startsWith("tool-")}function Rf(e){return e.type.split("-").slice(1).join("-")}function M6({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function A6({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await n(async({state:c,write:u})=>{var m,f,p,h;function v(b){const $=c.message.parts.filter(Bi).find(k=>k.toolCallId===b);if($==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return $}function _(b){const $=c.message.parts.filter(k=>k.type==="dynamic-tool").find(k=>k.toolCallId===b);if($==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return $}function w(b){var S;const $=c.message.parts.find(P=>Bi(P)&&P.toolCallId===b.toolCallId),k=b,I=$;$!=null?($.state=b.state,I.input=k.input,I.output=k.output,I.errorText=k.errorText,I.rawInput=k.rawInput,I.preliminary=k.preliminary,I.providerExecuted=(S=k.providerExecuted)!=null?S:$.providerExecuted,k.providerMetadata!=null&&$.state==="input-available"&&($.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function g(b){var S,$;const k=c.message.parts.find(L=>L.type==="dynamic-tool"&&L.toolCallId===b.toolCallId),I=b,P=k;k!=null?(k.state=b.state,P.toolName=b.toolName,P.input=I.input,P.output=I.output,P.errorText=I.errorText,P.rawInput=(S=I.rawInput)!=null?S:P.rawInput,P.preliminary=I.preliminary,P.providerExecuted=($=I.providerExecuted)!=null?$:k.providerExecuted,I.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=I.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:I.input,output:I.output,errorText:I.errorText,preliminary:I.preliminary,providerExecuted:I.providerExecuted,...I.providerMetadata!=null?{callProviderMetadata:I.providerMetadata}:{}})}async function y(b){if(b!=null){const S=c.message.metadata!=null?Tf(c.message.metadata,b):b;t!=null&&await gi({value:S,schema:t}),c.message.metadata=S}}switch(a.type){case"text-start":{const b={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeTextParts[a.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[a.id];b.text+=a.delta,b.providerMetadata=(m=a.providerMetadata)!=null?m:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[a.id];b.state="done",b.providerMetadata=(f=a.providerMetadata)!=null?f:b.providerMetadata,delete c.activeTextParts[a.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeReasoningParts[a.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[a.id];b.text+=a.delta,b.providerMetadata=(p=a.providerMetadata)!=null?p:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[a.id];b.providerMetadata=(h=a.providerMetadata)!=null?h:b.providerMetadata,b.state="done",delete c.activeReasoningParts[a.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(Bi);c.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:b.length,dynamic:a.dynamic},a.dynamic?g({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[a.toolCallId];b.text+=a.inputTextDelta;const{value:S}=await If(b.text);b.dynamic?g({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}):w({toolCallId:a.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}),u();break}case"tool-input-available":{a.dynamic?g({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),u(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{a.dynamic?g({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):w({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),u();break}case"tool-output-available":{if(a.dynamic){const b=_(a.toolCallId);g({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:a.output,preliminary:a.preliminary})}else{const b=v(a.toolCallId);w({toolCallId:a.toolCallId,toolName:Rf(b),state:"output-available",input:b.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}u();break}case"tool-output-error":{if(a.dynamic){const b=_(a.toolCallId);g({toolCallId:a.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const b=v(a.toolCallId);w({toolCallId:a.toolCallId,toolName:Rf(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{a.messageId!=null&&(c.message.id=a.messageId),await y(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&u();break}case"finish":{a.finishReason!=null&&(c.finishReason=a.finishReason),await y(a.messageMetadata),a.messageMetadata!=null&&u();break}case"message-metadata":{await y(a.messageMetadata),a.messageMetadata!=null&&u();break}case"error":{o?.(new Error(a.errorText));break}default:if(P6(a)){r?.[a.type]!=null&&await gi({value:a.data,schema:r[a.type]});const b=a;if(b.transient){i?.(b);break}const S=b.id!=null?c.message.parts.find($=>b.type===$.type&&b.id===$.id):void 0;S!=null?S.data=b.data:c.message.parts.push(b),i?.(b),u()}}l.enqueue(a)})}}))}function N6({messageId:e,originalMessages:t=[],onFinish:r,onError:n,stream:o}){let s=t?.[t.length-1];s?.role!=="assistant"?s=void 0:e=s.id;let i=!1;const a=o.pipeThrough(new TransformStream({transform(f,p){if(f.type==="start"){const h=f;h.messageId==null&&e!=null&&(h.messageId=e)}f.type==="abort"&&(i=!0),p.enqueue(f)}}));if(r==null)return a;const l=M6({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),c=async f=>{await f({state:l,write:()=>{}})};let u=!1;const m=async()=>{if(u||!r)return;u=!0;const f=l.message.id===s?.id;await r({isAborted:i,isContinuation:f,responseMessage:l.message,messages:[...f?t.slice(0,-1):t,l.message],finishReason:l.finishReason})};return A6({stream:a,runUpdateMessageJob:c,onError:n}).pipeThrough(new TransformStream({transform(f,p){p.enqueue(f)},async cancel(){await m()},async flush(){await m()}}))}function q6({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let i=o.pipeThrough(new kf);if(s){const[a,l]=i.tee();i=a,s({stream:l})}Cf({response:e,status:t,statusText:r,headers:Object.fromEntries(es(n,Ef).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function ts(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var i;n=!0;try{s&&await((i=r.cancel)==null?void 0:i.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:i}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function L6({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 xf(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function U6(){let e=[],t=null,r=!1,n=xf();const o=()=>{r=!0,n.resolve(),e.forEach(i=>i.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=xf(),await n.promise,s();try{const{value:i,done:a}=await e[0].read();a?(e.shift(),e.length>0?await s():r&&t?.close()):t?.enqueue(i)}catch(i){t?.error(i),e.shift(),o()}};return{stream:new ReadableStream({start(i){t=i},pull:s,async cancel(){for(const i of e)await i.cancel();e=[],r=!0}}),addStream:i=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(i.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function j6(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function D6({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:i,repairToolCall:a,experimental_context:l}){let c=null;const u=new ReadableStream({start(w){c=w}}),m=new Set,f=new Map;let p=!1,h;function v(){p&&m.size===0&&(h!=null&&c.enqueue(h),c.close())}const _=new TransformStream({async transform(w,g){const y=w.type;switch(y){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":{g.enqueue(w);break}case"file":{g.enqueue({type:"file",file:new S6({data:w.data,mediaType:w.mediaType})});break}case"finish":{h={type:"finish",finishReason:w.finishReason,usage:w.usage,providerMetadata:w.providerMetadata};break}case"tool-call":{try{const b=await _f({toolCall:w,tools:e,repairToolCall:a,system:o,messages:s});if(g.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:fi(b.error),dynamic:!0});break}const S=e[b.toolName];if(f.set(b.toolCallId,b.input),S.onInputAvailable!=null&&await S.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:s,abortSignal:i,experimental_context:l}),S.execute!=null&&b.providerExecuted!==!0){const $=Bn();m.add($),ln({name:"ai.toolCall",attributes:Ct({telemetry:n,attributes:{...an({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async k=>{let I;try{const P=Ep({execute:S.execute.bind(S),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:i,experimental_context:l}});for await(const L of P)c.enqueue({...b,type:"tool-result",output:L.output,...L.type==="preliminary"&&{preliminary:!0}}),L.type==="final"&&(I=L.output)}catch(P){zi(k,P),c.enqueue({...b,type:"tool-error",error:P}),m.delete($),v();return}m.delete($),v();try{k.setAttributes(Ct({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(I)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=w.toolName;w.isError?c.enqueue({type:"tool-error",toolCallId:w.toolCallId,toolName:b,input:f.get(w.toolCallId),providerExecuted:w.providerExecuted,error:w.result}):g.enqueue({type:"tool-result",toolCallId:w.toolCallId,toolName:b,input:f.get(w.toolCallId),output:w.result,providerExecuted:w.providerExecuted});break}default:{const b=y;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){p=!0,v()}});return new ReadableStream({async start(w){return Promise.all([t.pipeThrough(_).pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){}})),u.pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){w.close()}}))])}})}var z6=Hn({prefix:"aitxt",size:24});function Ji({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,headers:l,stopWhen:c=Fi(1),experimental_output:u,experimental_telemetry:m,prepareStep:f,providerOptions:p,experimental_activeTools:h,activeTools:v=h,experimental_repairToolCall:_,experimental_transform:w,experimental_download:g,includeRawChunks:y=!1,onChunk:b,onError:S=({error:F})=>{console.error(F)},onFinish:$,onAbort:k,onStepFinish:I,experimental_context:P,_internal:{now:L=j6,generateId:N=z6,currentDate:j=()=>new Date}={},...D}){return new F6({model:Qo(e),telemetry:m,headers:l,settings:D,maxRetries:i,abortSignal:a,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Zi(w),activeTools:v,repairToolCall:_,stopConditions:Zi(c),output:u,providerOptions:p,prepareStep:f,includeRawChunks:y,onChunk:b,onError:S,onFinish:$,onAbort:k,onStepFinish:I,now:L,currentDate:j,generateId:N,experimental_context:P,download:g})}function Z6(e){if(!e)return new TransformStream({transform(i,a){a.enqueue({part:i,partialOutput:void 0})}});let t,r="",n="",o="";function s({controller:i,partialOutput:a=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n},partialOutput:a}),n=""}return new TransformStream({async transform(i,a){if(i.type==="finish-step"&&n.length>0&&s({controller:a}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){a.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){a.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){a.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&s({controller:a}),a.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text;const l=await e.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==o&&(s({controller:a,partialOutput:l.partial}),o=c)}}})}var F6=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,system:i,prompt:a,messages:l,tools:c,toolChoice:u,transforms:m,activeTools:f,repairToolCall:p,stopConditions:h,output:v,providerOptions:_,prepareStep:w,includeRawChunks:g,now:y,currentDate:b,generateId:S,onChunk:$,onError:k,onFinish:I,onAbort:P,onStepFinish:L,experimental_context:N,download:j}){this._totalUsage=new Vo,this._finishReason=new Vo,this._steps=new Vo,this.output=v,this.includeRawChunks=g,this.tools=c;let D,F=[];const ne=[];let ue,ie,re={},he=[];const V=[];let M,Z={},U={};const T=new TransformStream({async transform(G,Y){var ae,de,Ae,qe;Y.enqueue(G);const{part:ee}=G;if((ee.type==="text-delta"||ee.type==="reasoning-delta"||ee.type==="source"||ee.type==="tool-call"||ee.type==="tool-result"||ee.type==="tool-input-start"||ee.type==="tool-input-delta"||ee.type==="raw")&&await $?.({chunk:ee}),ee.type==="error"&&await k({error:lf(ee.error)}),ee.type==="text-start"&&(Z[ee.id]={type:"text",text:"",providerMetadata:ee.providerMetadata},F.push(Z[ee.id])),ee.type==="text-delta"){const ve=Z[ee.id];if(ve==null){Y.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}ve.text+=ee.text,ve.providerMetadata=(ae=ee.providerMetadata)!=null?ae:ve.providerMetadata}if(ee.type==="text-end"){const ve=Z[ee.id];if(ve==null){Y.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}ve.providerMetadata=(de=ee.providerMetadata)!=null?de:ve.providerMetadata,delete Z[ee.id]}if(ee.type==="reasoning-start"&&(U[ee.id]={type:"reasoning",text:"",providerMetadata:ee.providerMetadata},F.push(U[ee.id])),ee.type==="reasoning-delta"){const ve=U[ee.id];if(ve==null){Y.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}ve.text+=ee.text,ve.providerMetadata=(Ae=ee.providerMetadata)!=null?Ae:ve.providerMetadata}if(ee.type==="reasoning-end"){const ve=U[ee.id];if(ve==null){Y.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}ve.providerMetadata=(qe=ee.providerMetadata)!=null?qe:ve.providerMetadata,delete U[ee.id]}if(ee.type==="file"&&F.push({type:"file",file:ee.file}),ee.type==="source"&&F.push(ee),ee.type==="tool-call"&&F.push(ee),ee.type==="tool-result"&&!ee.preliminary&&F.push(ee),ee.type==="tool-error"&&F.push(ee),ee.type==="start-step"&&(re=ee.request,he=ee.warnings),ee.type==="finish-step"){const ve=Hi({content:F,tools:c}),ct=new yf({content:F,finishReason:ee.finishReason,usage:ee.usage,warnings:he,request:re,response:{...ee.response,messages:[...ne,...ve]},providerMetadata:ee.providerMetadata});await L?.(ct),bh(he),V.push(ct),F=[],U={},Z={},ne.push(...ve),D.resolve()}ee.type==="finish"&&(ie=ee.totalUsage,ue=ee.finishReason)},async flush(G){try{if(V.length===0){const Ae=new z4({message:"No output generated. Check the stream for errors."});B._finishReason.reject(Ae),B._totalUsage.reject(Ae),B._steps.reject(Ae);return}const Y=ue??"unknown",ae=ie??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};B._finishReason.resolve(Y),B._totalUsage.resolve(ae),B._steps.resolve(V);const de=V[V.length-1];await I?.({finishReason:Y,totalUsage:ae,usage:de.usage,content:de.content,text:de.text,reasoningText:de.reasoningText,reasoning:de.reasoning,files:de.files,sources:de.sources,toolCalls:de.toolCalls,staticToolCalls:de.staticToolCalls,dynamicToolCalls:de.dynamicToolCalls,toolResults:de.toolResults,staticToolResults:de.staticToolResults,dynamicToolResults:de.dynamicToolResults,request:de.request,response:de.response,warnings:de.warnings,providerMetadata:de.providerMetadata,steps:V}),M.setAttributes(Ct({telemetry:t,attributes:{"ai.response.finishReason":Y,"ai.response.text":{output:()=>de.text},"ai.response.toolCalls":{output:()=>{var Ae;return(Ae=de.toolCalls)!=null&&Ae.length?JSON.stringify(de.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(de.providerMetadata),"ai.usage.inputTokens":ae.inputTokens,"ai.usage.outputTokens":ae.outputTokens,"ai.usage.totalTokens":ae.totalTokens,"ai.usage.reasoningTokens":ae.reasoningTokens,"ai.usage.cachedInputTokens":ae.cachedInputTokens}}))}catch(Y){G.error(Y)}finally{M.end()}}}),x=U6();this.addStream=x.addStream,this.closeStream=x.close;const E=x.stream.getReader();let H=new ReadableStream({async start(G){G.enqueue({type:"start"})},async pull(G){function Y(){P?.({steps:V}),G.enqueue({type:"abort"}),G.close()}try{const{done:ae,value:de}=await E.read();if(ae){G.close();return}if(s?.aborted){Y();return}G.enqueue(de)}catch(ae){Ar(ae)&&s?.aborted?Y():G.error(ae)}},cancel(G){return x.stream.cancel(G)}});for(const G of m)H=H.pipeThrough(G({tools:c,stopStream(){x.terminate()}}));this.baseStream=H.pipeThrough(Z6(v)).pipeThrough(T);const{maxRetries:W,retry:fe}=ff({maxRetries:o,abortSignal:s}),le=uf(t),q=Di(n),z=cf({model:e,telemetry:t,headers:r,settings:{...q,maxRetries:W}}),B=this;ln({name:"ai.streamText",attributes:Ct({telemetry:t,attributes:{...an({operationId:"ai.streamText",telemetry:t}),...z,"ai.prompt":{input:()=>JSON.stringify({system:i,prompt:a,messages:l})}}}),tracer:le,endWhenDone:!1,fn:async G=>{M=G;async function Y({currentStep:ae,responseMessages:de,usage:Ae}){var qe,ee,ve,ct,Se;const mt=B.includeRawChunks;D=new Vo;const pr=await af({system:i,prompt:a,messages:l}),gt=[...pr.messages,...de],Xe=await w?.({model:e,steps:V,stepNumber:V.length,messages:gt}),xt=Qo((qe=Xe?.model)!=null?qe:e),Rr=await tf({prompt:{system:(ee=Xe?.system)!=null?ee:pr.system,messages:(ve=Xe?.messages)!=null?ve:gt},supportedUrls:await xt.supportedUrls,download:j}),{toolChoice:xr,tools:Mn}=rf({tools:c,toolChoice:(ct=Xe?.toolChoice)!=null?ct:u,activeTools:(Se=Xe?.activeTools)!=null?Se:f}),{result:{stream:Ha,response:He,request:hr},doStreamSpan:fr,startTimestampMs:g_}=await fe(()=>ln({name:"ai.streamText.doStream",attributes:Ct({telemetry:t,attributes:{...an({operationId:"ai.streamText.doStream",telemetry:t}),...z,"ai.model.provider":xt.provider,"ai.model.id":xt.modelId,"ai.prompt.messages":{input:()=>df(Rr)},"ai.prompt.tools":{input:()=>Mn?.map(me=>JSON.stringify(me))},"ai.prompt.toolChoice":{input:()=>xr!=null?JSON.stringify(xr):void 0},"gen_ai.system":xt.provider,"gen_ai.request.model":xt.modelId,"gen_ai.request.frequency_penalty":q.frequencyPenalty,"gen_ai.request.max_tokens":q.maxOutputTokens,"gen_ai.request.presence_penalty":q.presencePenalty,"gen_ai.request.stop_sequences":q.stopSequences,"gen_ai.request.temperature":q.temperature,"gen_ai.request.top_k":q.topK,"gen_ai.request.top_p":q.topP}}),tracer:le,endWhenDone:!1,fn:async me=>({startTimestampMs:y(),doStreamSpan:me,result:await xt.doStream({...q,tools:Mn,toolChoice:xr,responseFormat:v?.responseFormat,prompt:Rr,providerOptions:_,abortSignal:s,headers:r,includeRawChunks:mt})})})),MR=D6({tools:c,generatorStream:Ha,tracer:le,telemetry:t,system:i,messages:gt,repairToolCall:p,abortSignal:s,experimental_context:N}),AR=hr??{},Ba=[],wu=[];let bu;const Su={};let An="unknown",Bt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},$u,__=!0,tr={id:S(),timestamp:b(),modelId:e.modelId},v_="";B.addStream(MR.pipeThrough(new TransformStream({async transform(me,et){var xo,Po,Ja,mr;if(me.type==="stream-start"){bu=me.warnings;return}if(__){const ut=y()-g_;__=!1,fr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":ut}),fr.setAttributes({"ai.response.msToFirstChunk":ut}),et.enqueue({type:"start-step",request:AR,warnings:bu??[]})}const y_=me.type;switch(y_){case"text-start":case"text-end":{et.enqueue(me);break}case"text-delta":{me.delta.length>0&&(et.enqueue({type:"text-delta",id:me.id,text:me.delta,providerMetadata:me.providerMetadata}),v_+=me.delta);break}case"reasoning-start":case"reasoning-end":{et.enqueue(me);break}case"reasoning-delta":{et.enqueue({type:"reasoning-delta",id:me.id,text:me.delta,providerMetadata:me.providerMetadata});break}case"tool-call":{et.enqueue(me),Ba.push(me);break}case"tool-result":{et.enqueue(me),me.preliminary||wu.push(me);break}case"tool-error":{et.enqueue(me),wu.push(me);break}case"response-metadata":{tr={id:(xo=me.id)!=null?xo:tr.id,timestamp:(Po=me.timestamp)!=null?Po:tr.timestamp,modelId:(Ja=me.modelId)!=null?Ja:tr.modelId};break}case"finish":{Bt=me.usage,An=me.finishReason,$u=me.providerMetadata;const ut=y()-g_;fr.addEvent("ai.stream.finish"),fr.setAttributes({"ai.response.msToFinish":ut,"ai.response.avgOutputTokensPerSecond":1e3*((mr=Bt.outputTokens)!=null?mr:0)/ut});break}case"file":{et.enqueue(me);break}case"source":{et.enqueue(me);break}case"tool-input-start":{Su[me.id]=me.toolName;const ut=c?.[me.toolName];ut?.onInputStart!=null&&await ut.onInputStart({toolCallId:me.id,messages:gt,abortSignal:s,experimental_context:N}),et.enqueue({...me,dynamic:ut?.type==="dynamic"});break}case"tool-input-end":{delete Su[me.id],et.enqueue(me);break}case"tool-input-delta":{const ut=Su[me.id],Cu=c?.[ut];Cu?.onInputDelta!=null&&await Cu.onInputDelta({inputTextDelta:me.delta,toolCallId:me.id,messages:gt,abortSignal:s,experimental_context:N}),et.enqueue(me);break}case"error":{et.enqueue(me),An="error";break}case"raw":{mt&&et.enqueue(me);break}default:{const ut=y_;throw new Error(`Unknown chunk type: ${ut}`)}}},async flush(me){const et=Ba.length>0?JSON.stringify(Ba):void 0;try{fr.setAttributes(Ct({telemetry:t,attributes:{"ai.response.finishReason":An,"ai.response.text":{output:()=>v_},"ai.response.toolCalls":{output:()=>et},"ai.response.id":tr.id,"ai.response.model":tr.modelId,"ai.response.timestamp":tr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify($u),"ai.usage.inputTokens":Bt.inputTokens,"ai.usage.outputTokens":Bt.outputTokens,"ai.usage.totalTokens":Bt.totalTokens,"ai.usage.reasoningTokens":Bt.reasoningTokens,"ai.usage.cachedInputTokens":Bt.cachedInputTokens,"gen_ai.response.finish_reasons":[An],"gen_ai.response.id":tr.id,"gen_ai.response.model":tr.modelId,"gen_ai.usage.input_tokens":Bt.inputTokens,"gen_ai.usage.output_tokens":Bt.outputTokens}}))}catch{}finally{fr.end()}me.enqueue({type:"finish-step",finishReason:An,usage:Bt,providerMetadata:$u,response:{...tr,headers:He?.headers}});const xo=pf(Ae,Bt);await D.promise;const Po=Ba.filter(mr=>mr.providerExecuted!==!0),Ja=wu.filter(mr=>mr.providerExecuted!==!0);if(Po.length>0&&Ja.length===Po.length&&!await wf({stopConditions:h,steps:V})){de.push(...Hi({content:V[V.length-1].content,tools:c}));try{await Y({currentStep:ae+1,responseMessages:de,usage:xo})}catch(mr){me.enqueue({type:"error",error:mr}),B.closeStream()}}else me.enqueue({type:"finish",finishReason:An,totalUsage:xo}),B.closeStream()}})))}await Y({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(G=>{B.addStream(new ReadableStream({start(Y){Y.enqueue({type:"error",error:G}),Y.close()}})),B.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return ts(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return ts(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await L6({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new yh;return ts(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:i=!0,sendFinish:a=!0,onError:l=Xr}={}){const c=t!=null?x6({originalMessages:e,responseMessageId:t}):void 0,u={},m=p=>{var h,v;const _=u[p];return((v=(h=this.tools)==null?void 0:h[_])==null?void 0:v.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,h)=>{const v=n?.({part:p}),_=p.type;switch(_){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":{u[p.id]=p.toolName;const w=m(p.id);h.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...w!=null?{dynamic:w}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{u[p.toolCallId]=p.toolName;const w=m(p.toolCallId);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}:{},...w!=null?{dynamic:w}:{},errorText:l(p.error)}):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}:{},...w!=null?{dynamic:w}:{}});break}case"tool-result":{const w=m(p.toolCallId);h.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...w!=null?{dynamic:w}:{}});break}case"tool-error":{const w=m(p.toolCallId);h.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...w!=null?{dynamic:w}:{}});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":{i&&h.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&h.enqueue({type:"finish",finishReason:p.finishReason,...v!=null?{messageMetadata:v}:{}});break}case"abort":{h.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const w=_;throw new Error(`Unknown chunk type: ${w}`)}}v!=null&&_!=="start"&&_!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:v})}}));return ts(N6({stream:f,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c,...u}={}){q6({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){I6({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l,...c}={}){return R6({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l}),...c})}toTextStreamResponse(e){return T6({textStream:this.textStream,...e})}};Hn({prefix:"aiobj",size:24}),Hn({prefix:"aiobj",size:24});var V6={};M4(V6,{object:()=>B6,text:()=>H6});var H6=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),B6=({schema:e})=>{const t=Jo(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await If(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const o=n.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:r},n){const o=await Nr({text:r});if(!o.success)throw new Oh({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const s=await Pt({value:o.value,schema:t});if(!s.success)throw new Oh({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return s.value}}};let Wi;Wi=globalThis.crypto;async function J6(e){return(await Wi).getRandomValues(new Uint8Array(e))}async function W6(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await J6(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function G6(e){return await W6(e)}async function K6(e){const t=await(await Wi).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Gi(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await G6(e),r=await K6(t);return{code_verifier:t,code_challenge:r}}var Y6="AI_MCPClientError",Pf=`vercel.ai.error.${Y6}`,Q6=Symbol.for(Pf),Of,Mf,Re=class extends(Mf=ge,Of=Q6,Mf){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[Of]=!0,this.data=n,this.code=o}static isInstance(e){return ge.hasMarker(e,Pf)}},cn="2025-06-18",X6=[cn,"2025-03-26","2024-11-05"],eS=Ce({name:d(),version:d()}),rs=Ce({_meta:K(C({}).loose())}),nr=rs,Af=C({method:d(),params:K(rs)}),Nf=C({applyDefaults:K(te())}).loose(),tS=Ce({experimental:K(C({}).loose()),logging:K(C({}).loose()),prompts:K(Ce({listChanged:K(te())})),resources:K(Ce({subscribe:K(te()),listChanged:K(te())})),tools:K(Ce({listChanged:K(te())})),elicitation:K(Nf)});C({elicitation:K(Nf)}).loose();var rS=nr.extend({protocolVersion:d(),capabilities:tS,serverInfo:eS,instructions:K(d())}),Ki=nr.extend({nextCursor:K(d())}),nS=C({name:d(),description:K(d()),inputSchema:C({type:O("object"),properties:K(C({}).loose())}).loose()}).loose(),oS=Ki.extend({tools:R(nS)}),qf=C({type:O("text"),text:d()}).loose(),Lf=C({type:O("image"),data:ep(),mimeType:d()}).loose(),sS=C({uri:d(),name:d(),title:K(d()),description:K(d()),mimeType:K(d()),size:K(A())}).loose(),aS=Ki.extend({resources:R(sS)}),Uf=C({uri:d(),name:K(d()),title:K(d()),mimeType:K(d())}).loose(),jf=Uf.extend({text:d()}),Df=Uf.extend({blob:ep()}),zf=C({type:O("resource"),resource:X([jf,Df])}).loose(),iS=nr.extend({content:R(X([qf,Lf,zf])),isError:te().default(!1).optional()}).or(nr.extend({toolResult:ce()})),lS=C({uriTemplate:d(),name:d(),title:K(d()),description:K(d()),mimeType:K(d())}).loose(),cS=nr.extend({resourceTemplates:R(lS)}),uS=nr.extend({contents:R(X([jf,Df]))}),dS=C({name:d(),description:K(d()),required:K(te())}).loose(),pS=C({name:d(),title:K(d()),description:K(d()),arguments:K(R(dS))}).loose(),hS=Ki.extend({prompts:R(pS)}),fS=C({role:X([O("user"),O("assistant")]),content:X([qf,Lf,zf])}).loose(),mS=nr.extend({description:K(d()),messages:R(fS)}),gS=rs.extend({message:d(),requestedSchema:ce()}),Zf=Af.extend({method:O("elicitation/create"),params:gS}),_S=nr.extend({action:X([O("accept"),O("decline"),O("cancel")]),content:K(oe(d(),ce()))}),ns="2.0",vS=C({jsonrpc:O(ns),id:X([d(),A().int()])}).merge(Af).strict(),yS=C({jsonrpc:O(ns),id:X([d(),A().int()]),result:nr}).strict(),wS=C({jsonrpc:O(ns),id:X([d(),A().int()]),error:C({code:A().int(),message:d(),data:K(ce())})}).strict(),bS=C({jsonrpc:O(ns)}).merge(C({method:d(),params:K(rs)})).strict(),no=X([vS,bS,yS,wS]),Ff=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Vf=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:A().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),pt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:hi.custom,message:"URL must be parseable",fatal:!0}),Ga}).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"}),SS=C({resource:d().url(),authorization_servers:R(pt).optional(),jwks_uri:d().url().optional(),scopes_supported:R(d()).optional(),bearer_methods_supported:R(d()).optional(),resource_signing_alg_values_supported:R(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:te().optional(),authorization_details_types_supported:R(d()).optional(),dpop_signing_alg_values_supported:R(d()).optional(),dpop_bound_access_tokens_required:te().optional()}).passthrough(),Hf=C({issuer:d(),authorization_endpoint:pt,token_endpoint:pt,registration_endpoint:pt.optional(),scopes_supported:R(d()).optional(),response_types_supported:R(d()),grant_types_supported:R(d()).optional(),code_challenge_methods_supported:R(d()),token_endpoint_auth_methods_supported:R(d()).optional(),token_endpoint_auth_signing_alg_values_supported:R(d()).optional()}).passthrough(),$S=C({issuer:d(),authorization_endpoint:pt,token_endpoint:pt,userinfo_endpoint:pt.optional(),jwks_uri:pt,registration_endpoint:pt.optional(),scopes_supported:R(d()).optional(),response_types_supported:R(d()),grant_types_supported:R(d()).optional(),subject_types_supported:R(d()),id_token_signing_alg_values_supported:R(d()),claims_supported:R(d()).optional(),token_endpoint_auth_methods_supported:R(d()).optional()}).passthrough(),CS=$S.merge(Hf.pick({code_challenge_methods_supported:!0})),kS=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:A().optional(),client_secret_expires_at:A().optional()}).strip(),ES=C({redirect_uris:R(pt),token_endpoint_auth_method:d().optional(),grant_types:R(d()).optional(),response_types:R(d()).optional(),client_name:d().optional(),client_uri:pt.optional(),logo_uri:pt.optional(),scope:d().optional(),contacts:R(d()).optional(),tos_uri:pt.optional(),policy_uri:d().optional(),jwks_uri:pt.optional(),jwks:tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),TS=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),IS=ES.merge(kS),RS="AI_MCPClientOAuthError",Bf=`vercel.ai.error.${RS}`,xS=Symbol.for(Bf),Jf,Wf,oo=class extends(Wf=ge,Jf=xS,Wf){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[Jf]=!0}static isInstance(e){return ge.hasMarker(e,Bf)}},un=class extends oo{};un.errorCode="server_error";var os=class extends oo{};os.errorCode="invalid_client";var ss=class extends oo{};ss.errorCode="invalid_grant";var as=class extends oo{};as.errorCode="unauthorized_client";var PS={[un.errorCode]:un,[os.errorCode]:os,[ss.errorCode]:ss,[as.errorCode]:as};function OS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function MS({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 is=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function ls(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="([^"]*)"/,i=r.match(s);if(i)try{return new URL(i[1])}catch{return}}function AS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Yi(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Yi(e,void 0,r):void 0;throw n}}async function Gf(e,t,r=fetch){return await Yi(e,{"MCP-Protocol-Version":t},r)}function NS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function qS(e,t,r,n){var o,s;const i=new URL(e),a=(o=n?.protocolVersion)!=null?o:cn;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=AS(t,i.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:i),l.search=i.search}let c=await Gf(l,a,r);if(!n?.metadataUrl&&NS(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await Gf(u,a,r)}return c}async function LS(e,t,r=fetch){const n=await qS(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 SS.parse(await n.json())}function US(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 jS(e,{fetchFn:t=fetch,protocolVersion:r=cn}={}){var n;const o={"MCP-Protocol-Version":r},s=US(e);for(const{url:i,type:a}of s){const l=await Yi(i,o,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}if(a==="oauth")return Hf.parse(await l.json());{const c=CS.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${i}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function DS(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){const a="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(a))throw new Error(`Incompatible auth server: does not support response type ${a}`);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 Gi(),m=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",a),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),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"),i&&c.searchParams.set("resource",i.href),{authorizationUrl:c,codeVerifier:m}}function Kf(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 Yf(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":zS(o,s,r);return;case"client_secret_post":ZS(o,s,n);return;case"none":FS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function zS(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 ZS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function FS(e,t){t.set("client_id",e)}async function Qi(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=TS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=PS[o]||un;return new a({message:s||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new un({message:o})}}async function VS(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:a,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 f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(a)a(f,p,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],_=Kf(r,v);Yf(_,r,f,p)}i&&p.set("resource",i.href);const h=await(l??fetch)(m,{method:"POST",headers:f,body:p});if(!h.ok)throw await Qi(h);return Vf.parse(await h.json())}async function HS(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){var a;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"}),m=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,m,e,t);else{const p=(a=t?.token_endpoint_auth_methods_supported)!=null?a:[],h=Kf(r,p);Yf(h,r,u,m)}o&&m.set("resource",o.href);const f=await(i??fetch)(c,{method:"POST",headers:u,body:m});if(!f.ok)throw await Qi(f);return Vf.parse({refresh_token:n,...await f.json()})}async function BS(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 Qi(s);return IS.parse(await s.json())}async function cs(e,t){var r,n;try{return await Xi(e,t)}catch(o){if(o instanceof os||o instanceof as)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Xi(e,t);if(o instanceof ss)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Xi(e,t);throw o}}async function JS(e,t,r){const n=OS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!MS({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 Xi(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await LS(t,{resourceMetadataUrl:o},s),i.authorization_servers&&i.authorization_servers.length>0&&(a=i.authorization_servers[0])}catch{}a||(a=t);const l=await JS(t,e,i),c=await jS(a,{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 BS(a,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),_=await VS(a,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}const m=await e.tokens();if(m?.refresh_token)try{const v=await HS(a,{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 oo)||v instanceof un))throw v}const f=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:h}=await DS(a,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(p),"REDIRECT"}var WS=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":cn};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return vr(t,`ai-sdk/${Ff}`,Jn())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,i,a,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=ls(u);try{if(await cs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new is;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(h){return(i=this.onerror)==null||i.call(this,h),t(h)}return r(!0)}if(!u.ok||!u.body){let h=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(h+=". This server does not support SSE transport. Try using `http` transport instead");const v=new Re({message:h});return(a=this.onerror)==null||a.call(this,v),t(v)}const f=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pr).getReader(),p=async()=>{var h,v,_;try{for(;;){const{done:w,value:g}=await f.read();if(w){if(this.connected)throw this.connected=!1,new Re({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:y,data:b}=g;if(y==="endpoint"){if(this.endpoint=new URL(b,this.url),this.endpoint.origin!==this.url.origin)throw new Re({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(y==="message")try{const S=no.parse(JSON.parse(b));(h=this.onmessage)==null||h.call(this,S)}catch(S){const $=new Re({message:"MCP SSE Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,$)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(_=this.onerror)==null||_.call(this,w),t(w)}};this.sseConnection={close:()=>f.cancel()},p()}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 Re({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,i,a,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=ls(m);try{if(await cs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const p=new is;(s=this.onerror)==null||s.call(this,p);return}}catch(f){(i=this.onerror)==null||i.call(this,f);return}return r(!0)}if(!m.ok){const f=await m.text().catch(()=>null),p=new Re({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${f}`});(a=this.onerror)==null||a.call(this,p);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},GS=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":cn};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 vr(t,`ai-sdk/${Ff}`,Jn())}async start(){if(this.abortController)throw new Re({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,i,a,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},f=await fetch(this.url,m),p=f.headers.get("mcp-session-id");if(p&&(this.sessionId=p),f.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=ls(f);try{if(await cs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new is}catch(_){throw(o=this.onerror)==null||o.call(this,_),_}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const _=await f.text().catch(()=>null);let w=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${_}`;f.status===404&&(w+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new Re({message:w});throw(s=this.onerror)==null||s.call(this,g),g}const h=f.headers.get("content-type")||"";if(h.includes("application/json")){const _=await f.json(),w=Array.isArray(_)?_.map(g=>no.parse(g)):[no.parse(_)];for(const g of w)(i=this.onmessage)==null||i.call(this,g);return}if(h.includes("text/event-stream")){if(!f.body){const y=new Re({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(a=this.onerror)==null||a.call(this,y),y}const w=f.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pr).getReader();(async()=>{var y,b,S;try{for(;;){const{done:$,value:k}=await w.read();if($)return;const{event:I,data:P}=k;if(I==="message")try{const L=no.parse(JSON.parse(P));(y=this.onmessage)==null||y.call(this,L)}catch(L){const N=new Re({message:"MCP HTTP Transport Error: Failed to parse message",cause:L});(b=this.onerror)==null||b.call(this,N)}}}catch($){if($ instanceof Error&&$.name==="AbortError")return;(S=this.onerror)==null||S.call(this,$)}})();return}const v=new Re({message:`MCP HTTP Transport Error: Unexpected content type: ${h}`});throw(l=this.onerror)==null||l.call(this,v),v}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 Re({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,i,a;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=ls(c);try{if(await cs(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new is;(n=this.onerror)==null||n.call(this,v);return}}catch(h){(o=this.onerror)==null||o.call(this,h);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const h=new Re({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,h);return}const f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pr).getReader(),p=async()=>{var h,v,_,w;try{for(;;){const{done:g,value:y}=await f.read();if(g)return;const{event:b,data:S,id:$}=y;if($&&(this.lastInboundEventId=$),b==="message")try{const k=no.parse(JSON.parse(S));(h=this.onmessage)==null||h.call(this,k)}catch(k){const I=new Re({message:"MCP HTTP Transport Error: Failed to parse message",cause:k});(v=this.onerror)==null||v.call(this,I)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(_=this.onerror)==null||_.call(this,g),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,p()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(i=this.onerror)==null||i.call(this,l),(a=this.abortController)!=null&&a.signal.aborted||this.scheduleInboundSseReconnection()}}};function KS(e){switch(e.type){case"sse":return new WS(e);case"http":return new GS(e);default:throw new Re({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function YS(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var QS="1.0.0";async function XS(e){const t=new e5(e);return await t.init(),t}var e5=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=QS,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},YS(e)?this.transport=e:this.transport=KS(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 Re({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:cn,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:rS});if(e===void 0)throw new Re({message:"Server sent invalid initialize result"});if(!X6.includes(e.protocolVersion))throw new Re({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 Re({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Re({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Re({message:"Server does not support prompts"});break;default:throw new Re({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Re({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const i=this.requestMessageId++,a={...e,jsonrpc:"2.0",id:i},l=()=>{this.responseHandlers.delete(i)};this.responseHandlers.set(i,c=>{if(s?.aborted)return o(new Re({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 Re({message:"Failed to parse server response",cause:u});o(m)}}),this.transport.send(a).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:oS,options:t})}catch(r){throw r}}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:iS,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:aS,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:uS,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:cS,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:hS,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:mS,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"}={}){var t;const r={};try{const n=await this.listTools();for(const{name:o,description:s,inputSchema:i}of n.tools){if(e!=="automatic"&&!(o in e))continue;const a=this,l=async(u,m)=>{var f;return(f=m?.abortSignal)==null||f.throwIfAborted(),a.callTool({name:o,args:u,options:m})},c=e==="automatic"?_p({description:s,inputSchema:Wn({...i,properties:(t=i.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};r[o]=c}return r}catch(n){throw n}}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})}listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==Zf)throw new Re({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=Zf.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=_S.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 Re({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 Re({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Re({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function el(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Qf(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...el(t.headers),...el(n.headers)}:t.headers};return e(r,o)}:e}const us="2025-06-18",t5=[us,"2025-03-26","2024-11-05","2024-10-07"],ds="2.0",Yt=di(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Xf=X([d(),A().int()]),e0=d(),r5=Ce({progressToken:Xf.optional()}),At=Ce({_meta:r5.optional()}),ht=C({method:d(),params:At.optional()}),dn=Ce({_meta:oe(d(),ce()).optional()}),Nt=C({method:d(),params:dn.optional()}),kt=Ce({_meta:oe(d(),ce()).optional()}),ps=X([d(),A().int()]),t0=C({jsonrpc:O(ds),id:ps,...ht.shape}).strict(),r0=e=>t0.safeParse(e).success,n0=C({jsonrpc:O(ds),...Nt.shape}).strict(),n5=e=>n0.safeParse(e).success,o0=C({jsonrpc:O(ds),id:ps,result:kt}).strict(),tl=e=>o0.safeParse(e).success;var rt;(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"})(rt||(rt={}));const s0=C({jsonrpc:O(ds),id:ps,error:C({code:A().int(),message:d(),data:K(ce())})}).strict(),o5=e=>s0.safeParse(e).success,pn=X([t0,n0,o0,s0]),hn=kt.strict(),s5=dn.extend({requestId:ps,reason:d().optional()}),rl=Nt.extend({method:O("notifications/cancelled"),params:s5}),a5=C({src:d(),mimeType:d().optional(),sizes:R(d()).optional()}),so=C({icons:R(a5).optional()}),fn=C({name:d(),title:d().optional()}),a0=fn.extend({...fn.shape,...so.shape,version:d(),websiteUrl:d().optional()}),i5=Fn(C({applyDefaults:te().optional()}),oe(d(),ce())),l5=pi(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Fn(C({form:i5.optional(),url:Yt.optional()}),oe(d(),ce()).optional())),c5=C({experimental:oe(d(),Yt).optional(),sampling:C({context:Yt.optional(),tools:Yt.optional()}).optional(),elicitation:l5.optional(),roots:C({listChanged:te().optional()}).optional()}),u5=At.extend({protocolVersion:d(),capabilities:c5,clientInfo:a0}),d5=ht.extend({method:O("initialize"),params:u5}),p5=C({experimental:oe(d(),Yt).optional(),logging:Yt.optional(),completions:Yt.optional(),prompts:K(C({listChanged:K(te())})),resources:C({subscribe:te().optional(),listChanged:te().optional()}).optional(),tools:C({listChanged:te().optional()}).optional()}),i0=kt.extend({protocolVersion:d(),capabilities:p5,serverInfo:a0,instructions:d().optional()}),l0=Nt.extend({method:O("notifications/initialized")}),h5=e=>l0.safeParse(e).success,nl=ht.extend({method:O("ping")}),f5=C({progress:A(),total:K(A()),message:K(d())}),m5=C({...dn.shape,...f5.shape,progressToken:Xf}),ol=Nt.extend({method:O("notifications/progress"),params:m5}),g5=At.extend({cursor:e0.optional()}),hs=ht.extend({params:g5.optional()}),fs=kt.extend({nextCursor:K(e0)}),c0=C({uri:d(),mimeType:K(d()),_meta:oe(d(),ce()).optional()}),u0=c0.extend({text:d()}),sl=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),d0=c0.extend({blob:sl}),p0=C({...fn.shape,...so.shape,uri:d(),description:K(d()),mimeType:K(d()),_meta:K(Ce({}))}),_5=C({...fn.shape,...so.shape,uriTemplate:d(),description:K(d()),mimeType:K(d()),_meta:K(Ce({}))}),v5=hs.extend({method:O("resources/list")}),h0=fs.extend({resources:R(p0)}),y5=hs.extend({method:O("resources/templates/list")}),f0=fs.extend({resourceTemplates:R(_5)}),al=At.extend({uri:d()}),w5=al,b5=ht.extend({method:O("resources/read"),params:w5}),m0=kt.extend({contents:R(X([u0,d0]))}),g0=Nt.extend({method:O("notifications/resources/list_changed")}),S5=al,$5=ht.extend({method:O("resources/subscribe"),params:S5}),C5=al,k5=ht.extend({method:O("resources/unsubscribe"),params:C5}),E5=dn.extend({uri:d()}),_0=Nt.extend({method:O("notifications/resources/updated"),params:E5}),T5=C({name:d(),description:K(d()),required:K(te())}),I5=C({...fn.shape,...so.shape,description:K(d()),arguments:K(R(T5)),_meta:K(Ce({}))}),R5=hs.extend({method:O("prompts/list")}),v0=fs.extend({prompts:R(I5)}),x5=At.extend({name:d(),arguments:oe(d(),d()).optional()}),P5=ht.extend({method:O("prompts/get"),params:x5}),y0=C({type:O("text"),text:d(),_meta:oe(d(),ce()).optional()}),w0=C({type:O("image"),data:sl,mimeType:d(),_meta:oe(d(),ce()).optional()}),b0=C({type:O("audio"),data:sl,mimeType:d(),_meta:oe(d(),ce()).optional()}),O5=C({type:O("tool_use"),name:d(),id:d(),input:C({}).passthrough(),_meta:K(C({}).passthrough())}).passthrough(),M5=C({type:O("resource"),resource:X([u0,d0]),_meta:oe(d(),ce()).optional()}),A5=p0.extend({type:O("resource_link")}),il=X([y0,w0,b0,A5,M5]),N5=C({role:_e(["user","assistant"]),content:il}),S0=kt.extend({description:K(d()),messages:R(N5)}),$0=Nt.extend({method:O("notifications/prompts/list_changed")}),q5=C({title:d().optional(),readOnlyHint:te().optional(),destructiveHint:te().optional(),idempotentHint:te().optional(),openWorldHint:te().optional()}),C0=C({...fn.shape,...so.shape,description:d().optional(),inputSchema:C({type:O("object"),properties:oe(d(),Yt).optional(),required:R(d()).optional()}).catchall(ce()),outputSchema:C({type:O("object"),properties:oe(d(),Yt).optional(),required:R(d()).optional()}).catchall(ce()).optional(),annotations:K(q5),_meta:oe(d(),ce()).optional()}),L5=hs.extend({method:O("tools/list")}),k0=fs.extend({tools:R(C0)}),ms=kt.extend({content:R(il).default([]),structuredContent:oe(d(),ce()).optional(),isError:K(te())});ms.or(kt.extend({toolResult:ce()}));const U5=At.extend({name:d(),arguments:K(oe(d(),ce()))}),j5=ht.extend({method:O("tools/call"),params:U5}),E0=Nt.extend({method:O("notifications/tools/list_changed")}),T0=_e(["debug","info","notice","warning","error","critical","alert","emergency"]),D5=At.extend({level:T0}),z5=ht.extend({method:O("logging/setLevel"),params:D5}),Z5=dn.extend({level:T0,logger:d().optional(),data:ce()}),I0=Nt.extend({method:O("notifications/message"),params:Z5}),F5=C({name:d().optional()}),V5=C({hints:K(R(F5)),costPriority:K(A().min(0).max(1)),speedPriority:K(A().min(0).max(1)),intelligencePriority:K(A().min(0).max(1))}),H5=C({mode:K(_e(["auto","required","none"]))}),B5=C({type:O("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:R(il).default([]),structuredContent:C({}).passthrough().optional(),isError:K(te()),_meta:K(C({}).passthrough())}).passthrough(),gs=De("type",[y0,w0,b0,O5,B5]),J5=C({role:_e(["user","assistant"]),content:X([gs,R(gs)]),_meta:K(C({}).passthrough())}).passthrough(),W5=At.extend({messages:R(J5),modelPreferences:V5.optional(),systemPrompt:d().optional(),includeContext:_e(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:R(d()).optional(),metadata:Yt.optional(),tools:K(R(C0)),toolChoice:K(H5)}),R0=ht.extend({method:O("sampling/createMessage"),params:W5}),G5=kt.extend({model:d(),stopReason:K(_e(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:_e(["user","assistant"]),content:X([gs,R(gs)])}),K5=C({type:O("boolean"),title:d().optional(),description:d().optional(),default:te().optional()}),Y5=C({type:O("string"),title:d().optional(),description:d().optional(),minLength:A().optional(),maxLength:A().optional(),format:_e(["email","uri","date","date-time"]).optional(),default:d().optional()}),Q5=C({type:_e(["number","integer"]),title:d().optional(),description:d().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),X5=C({type:O("string"),title:d().optional(),description:d().optional(),enum:R(d()),default:d().optional()}),e$=C({type:O("string"),title:d().optional(),description:d().optional(),oneOf:R(C({const:d(),title:d()})),default:d().optional()}),t$=C({type:O("string"),title:d().optional(),description:d().optional(),enum:R(d()),enumNames:R(d()).optional(),default:d().optional()}),r$=X([X5,e$]),n$=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:A().optional(),maxItems:A().optional(),items:C({type:O("string"),enum:R(d())}),default:R(d()).optional()}),o$=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:A().optional(),maxItems:A().optional(),items:C({anyOf:R(C({const:d(),title:d()}))}),default:R(d()).optional()}),s$=X([n$,o$]),a$=X([t$,r$,s$]),i$=X([a$,K5,Y5,Q5]),l$=At.extend({mode:O("form").optional(),message:d(),requestedSchema:C({type:O("object"),properties:oe(d(),i$),required:R(d()).optional()})}),c$=At.extend({mode:O("url"),message:d(),elicitationId:d(),url:d().url()}),u$=X([l$,c$]),ll=ht.extend({method:O("elicitation/create"),params:u$}),d$=dn.extend({elicitationId:d()}),p$=Nt.extend({method:O("notifications/elicitation/complete"),params:d$}),x0=kt.extend({action:_e(["accept","decline","cancel"]),content:oe(d(),X([d(),A(),te(),R(d())])).optional()}),h$=C({type:O("ref/resource"),uri:d()}),f$=C({type:O("ref/prompt"),name:d()}),m$=At.extend({ref:X([f$,h$]),argument:C({name:d(),value:d()}),context:C({arguments:oe(d(),d()).optional()}).optional()}),g$=ht.extend({method:O("completion/complete"),params:m$}),P0=kt.extend({completion:Ce({values:R(d()).max(100),total:K(A().int()),hasMore:K(te())})}),_$=C({uri:d().startsWith("file://"),name:d().optional(),_meta:oe(d(),ce()).optional()}),O0=ht.extend({method:O("roots/list")}),v$=kt.extend({roots:R(_$)}),y$=Nt.extend({method:O("notifications/roots/list_changed")});X([nl,d5,g$,z5,P5,R5,v5,y5,b5,$5,k5,j5,L5]),X([rl,ol,l0,y$]),X([hn,G5,x0,v$]),X([nl,R0,ll,O0]),X([rl,ol,I0,_0,g0,E0,$0,p$]),X([hn,i0,P0,S0,v0,h0,f0,m0,ms,k0]);let wt=class $_ 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===rt.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new w$(o.elicitations,r)}return new $_(t,r,n)}},w$=class extends wt{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(rt.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){var t,r;return(r=(t=this.data)===null||t===void 0?void 0:t.elicitations)!==null&&r!==void 0?r:[]}};const Be=Qd().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:hi.custom,message:"URL must be parseable",fatal:!0}),Ga}).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"}),b$=Ce({resource:d().url(),authorization_servers:R(Be).optional(),jwks_uri:d().url().optional(),scopes_supported:R(d()).optional(),bearer_methods_supported:R(d()).optional(),resource_signing_alg_values_supported:R(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:te().optional(),authorization_details_types_supported:R(d()).optional(),dpop_signing_alg_values_supported:R(d()).optional(),dpop_bound_access_tokens_required:te().optional()}),M0=Ce({issuer:d(),authorization_endpoint:Be,token_endpoint:Be,registration_endpoint:Be.optional(),scopes_supported:R(d()).optional(),response_types_supported:R(d()),response_modes_supported:R(d()).optional(),grant_types_supported:R(d()).optional(),token_endpoint_auth_methods_supported:R(d()).optional(),token_endpoint_auth_signing_alg_values_supported:R(d()).optional(),service_documentation:Be.optional(),revocation_endpoint:Be.optional(),revocation_endpoint_auth_methods_supported:R(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:R(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:R(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:R(d()).optional(),code_challenge_methods_supported:R(d()).optional(),client_id_metadata_document_supported:te().optional()}),S$=Ce({issuer:d(),authorization_endpoint:Be,token_endpoint:Be,userinfo_endpoint:Be.optional(),jwks_uri:Be,registration_endpoint:Be.optional(),scopes_supported:R(d()).optional(),response_types_supported:R(d()),response_modes_supported:R(d()).optional(),grant_types_supported:R(d()).optional(),acr_values_supported:R(d()).optional(),subject_types_supported:R(d()),id_token_signing_alg_values_supported:R(d()),id_token_encryption_alg_values_supported:R(d()).optional(),id_token_encryption_enc_values_supported:R(d()).optional(),userinfo_signing_alg_values_supported:R(d()).optional(),userinfo_encryption_alg_values_supported:R(d()).optional(),userinfo_encryption_enc_values_supported:R(d()).optional(),request_object_signing_alg_values_supported:R(d()).optional(),request_object_encryption_alg_values_supported:R(d()).optional(),request_object_encryption_enc_values_supported:R(d()).optional(),token_endpoint_auth_methods_supported:R(d()).optional(),token_endpoint_auth_signing_alg_values_supported:R(d()).optional(),display_values_supported:R(d()).optional(),claim_types_supported:R(d()).optional(),claims_supported:R(d()).optional(),service_documentation:d().optional(),claims_locales_supported:R(d()).optional(),ui_locales_supported:R(d()).optional(),claims_parameter_supported:te().optional(),request_parameter_supported:te().optional(),request_uri_parameter_supported:te().optional(),require_request_uri_registration:te().optional(),op_policy_uri:Be.optional(),op_tos_uri:Be.optional(),client_id_metadata_document_supported:te().optional()}),$$=C({...S$.shape,...M0.pick({code_challenge_methods_supported:!0}).shape}),A0=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:A().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),C$=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),N0=Be.optional().or(O("").transform(()=>{})),k$=C({redirect_uris:R(Be),token_endpoint_auth_method:d().optional(),grant_types:R(d()).optional(),response_types:R(d()).optional(),client_name:d().optional(),client_uri:Be.optional(),logo_uri:N0,scope:d().optional(),contacts:R(d()).optional(),tos_uri:N0,policy_uri:d().optional(),jwks_uri:Be.optional(),jwks:tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),E$=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:A().optional(),client_secret_expires_at:A().optional()}).strip(),T$=k$.merge(E$);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function I$(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function R$({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)}let Je=class 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}},cl=class extends Je{};cl.errorCode="invalid_request";let _s=class extends Je{};_s.errorCode="invalid_client";let vs=class extends Je{};vs.errorCode="invalid_grant";let ys=class extends Je{};ys.errorCode="unauthorized_client";let ul=class extends Je{};ul.errorCode="unsupported_grant_type";let dl=class extends Je{};dl.errorCode="invalid_scope";let pl=class extends Je{};pl.errorCode="access_denied";let mn=class extends Je{};mn.errorCode="server_error";let hl=class extends Je{};hl.errorCode="temporarily_unavailable";let fl=class extends Je{};fl.errorCode="unsupported_response_type";let ml=class extends Je{};ml.errorCode="unsupported_token_type";let gl=class extends Je{};gl.errorCode="invalid_token";let _l=class extends Je{};_l.errorCode="method_not_allowed";let vl=class extends Je{};vl.errorCode="too_many_requests";let ws=class extends Je{};ws.errorCode="invalid_client_metadata";let yl=class extends Je{};yl.errorCode="insufficient_scope";const x$={[cl.errorCode]:cl,[_s.errorCode]:_s,[vs.errorCode]:vs,[ys.errorCode]:ys,[ul.errorCode]:ul,[dl.errorCode]:dl,[pl.errorCode]:pl,[mn.errorCode]:mn,[hl.errorCode]:hl,[fl.errorCode]:fl,[ml.errorCode]:ml,[gl.errorCode]:gl,[_l.errorCode]:_l,[vl.errorCode]:vl,[ws.errorCode]:ws,[yl.errorCode]:yl};let qt=class extends Error{constructor(t){super(t??"Unauthorized")}};function P$(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const wl="code",bl="S256";function q0(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&&P$(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 L0(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":O$(o,s,r);return;case"client_secret_post":M$(o,s,n);return;case"none":A$(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function O$(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 M$(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function A$(e,t){t.set("client_id",e)}async function Sl(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=C$.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=x$[o]||mn;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new mn(o)}}async function zr(e,t){var r,n;try{return await $l(e,t)}catch(o){if(o instanceof _s||o instanceof ys)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"all")),await $l(e,t);if(o instanceof vs)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"tokens")),await $l(e,t);throw o}}async function $l(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){var i,a;let l,c;try{l=await L$(t,{resourceMetadataUrl:o},s),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",t));const u=await q$(t,e,l),m=await Z$(c,{fetchFn:s});let f=await Promise.resolve(e.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const w=m?.client_id_metadata_document_supported===!0,g=e.clientMetadataUrl;if(g&&!N$(g))throw new ws(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${g}`);if(w&&g)f={client_id:g},await((i=e.saveClientInformation)===null||i===void 0?void 0:i.call(e,f));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const b=await B$(c,{metadata:m,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(b),f=b}}if(r!==void 0){const w=await e.codeVerifier(),g=await V$(c,{metadata:m,clientInformation:f,authorizationCode:r,codeVerifier:w,redirectUri:e.redirectUrl,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(g),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const w=await H$(c,{metadata:m,clientInformation:f,refreshToken:p.refresh_token,resource:u,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Je)||w instanceof mn))throw w}const h=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:_}=await F$(c,{metadata:m,clientInformation:f,state:h,redirectUrl:e.redirectUrl,scope:n||((a=l?.scopes_supported)===null||a===void 0?void 0:a.join(" "))||e.clientMetadata.scope,resource:u});return await e.saveCodeVerifier(_),await e.redirectToAuthorization(v),"REDIRECT"}function N$(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function q$(e,t,r){const n=I$(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!R$({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 bs(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Cl(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Cl(e,"scope")||void 0,a=Cl(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Cl(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 L$(e,t,r=fetch){const n=await D$(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 b$.parse(await n.json())}async function kl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?kl(e,void 0,r):void 0;throw n}}function U$(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function U0(e,t,r=fetch){return await kl(e,{"MCP-Protocol-Version":t},r)}function j$(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function D$(e,t,r,n){var o,s;const i=new URL(e),a=(o=n?.protocolVersion)!==null&&o!==void 0?o:us;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=U$(t,i.pathname);l=new URL(u,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:i),l.search=i.search}let c=await U0(l,a,r);if(!n?.metadataUrl&&j$(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await U0(u,a,r)}return c}function z$(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 Z$(e,{fetchFn:t=fetch,protocolVersion:r=us}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=z$(e);for(const{url:s,type:i}of o){const a=await kl(s,n,t);if(a){if(!a.ok){if(a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?M0.parse(await a.json()):$$.parse(await a.json())}}}async function F$(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(wl))throw new Error(`Incompatible auth server: does not support response type ${wl}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(bl))throw new Error(`Incompatible auth server: does not support code challenge method ${bl}`)}else a=new URL("/authorize",e);const l=await Gi(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",wl),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",bl),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:c}}async function V$(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:a,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 f=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),p=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(a)a(f,p,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],_=q0(r,v);L0(_,r,f,p)}i&&p.set("resource",i.href);const h=await(l??fetch)(m,{method:"POST",headers:f,body:p});if(!h.ok)throw await Sl(h);return A0.parse(await h.json())}async function H$(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){var a;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"}),m=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,m,e,t);else{const p=(a=t?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],h=q0(r,p);L0(h,r,u,m)}o&&m.set("resource",o.href);const f=await(i??fetch)(c,{method:"POST",headers:u,body:m});if(!f.ok)throw await Sl(f);return A0.parse({refresh_token:n,...await f.json()})}async function B$(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 Sl(s);return T$.parse(await s.json())}const J$={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};let ao=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},El=class{constructor(t,r){var n;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=Qf(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:J$}async _authThenStart(){var t;if(!this._authProvider)throw new qt("No auth provider");let r;try{r=await zr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(t=this.onerror)===null||t===void 0||t.call(this,n),n}if(r!=="AUTHORIZED")throw new qt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const r={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(r.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=el((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...r,...n})}async _startOrAuthSse(t){var r,n,o;const{resumptionToken:s}=t;try{const i=await this._commonHeaders();i.set("Accept","text/event-stream"),s&&i.set("last-event-id",s);const a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:i,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!a.ok){if(a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new ao(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}_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){var n;const o=this._reconnectionOptions.maxRetries;if(o>0&&r>=o){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},s)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let i,a=!1;(async()=>{var c,u,m,f;try{const p=t.pipeThrough(new TextDecoderStream).pipeThrough(new Pr({onRetry:v=>{this._serverRetryMs=v}})).getReader();for(;;){const{value:v,done:_}=await p.read();if(_)break;if(v.id&&(i=v.id,a=!0,o?.(v.id)),!v.event||v.event==="message")try{const w=pn.parse(JSON.parse(v.data));s!==void 0&&tl(w)&&(w.id=s),(c=this.onmessage)===null||c===void 0||c.call(this,w)}catch(w){(u=this.onerror)===null||u===void 0||u.call(this,w)}}(n||a)&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(p){if((m=this.onerror)===null||m===void 0||m.call(this,new Error(`SSE stream disconnected: ${p}`)),(n||a)&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(v){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${v instanceof Error?v.message:String(v)}`))}}})()}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 qt("No auth provider");if(await zr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qt("Failed to authorize")}async close(){var t,r;(t=this._abortController)===null||t===void 0||t.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(t,r){var n,o,s,i;try{const{resumptionToken:a,onresumptiontoken:l}=r||{};if(a){this._startOrAuthSse({resumptionToken:a,replayMessageId:r0(t)?t.id:void 0}).catch(_=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,_)});return}const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,u),f=m.headers.get("mcp-session-id");if(f&&(this._sessionId=f),!m.ok){if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ao(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:w,scope:g}=bs(m);if(this._resourceMetadataUrl=w,this._scope=g,await zr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(m.status===403&&this._authProvider){const{resourceMetadataUrl:w,scope:g,error:y}=bs(m);if(y==="insufficient_scope"){const b=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===b)throw new ao(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),w&&(this._resourceMetadataUrl=w),this._lastUpscopingHeader=b??void 0,await zr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qt;return this.send(t)}}const _=await m.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${m.status}): ${_}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){h5(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(_=>{var w;return(w=this.onerror)===null||w===void 0?void 0:w.call(this,_)});return}const h=(Array.isArray(t)?t:[t]).filter(_=>"method"in _&&"id"in _&&_.id!==void 0).length>0,v=m.headers.get("content-type");if(h)if(v?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:l},!1);else if(v?.includes("application/json")){const _=await m.json(),w=Array.isArray(_)?_.map(g=>pn.parse(g)):[pn.parse(_)];for(const g of w)(s=this.onmessage)===null||s===void 0||s.call(this,g)}else throw new ao(-1,`Unexpected content type: ${v}`)}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}get sessionId(){return this._sessionId}async terminateSession(){var t,r,n;if(this._sessionId)try{const o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!i.ok&&i.status!==405)throw new ao(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};class Ss{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Ss,r=new Ss;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(var t;this._messageQueue.length>0;){const r=this._messageQueue.shift();(t=this.onmessage)===null||t===void 0||t.call(this,r.message,r.extra)}}async close(){var t;const r=this._otherTransport;this._otherTransport=void 0,await r?.close(),(t=this.onclose)===null||t===void 0||t.call(this)}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 j0="vercel.ai.error",W$=Symbol.for(j0),D0,z0,ze=class C_ extends(z0=Error,D0=W$,z0){constructor({name:t,message:r,cause:n}){super(r),this[D0]=!0,this.name=t,this.cause=n}static isInstance(t){return C_.hasMarker(t,j0)}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}},Z0="AI_APICallError",F0=`vercel.ai.error.${Z0}`,G$=Symbol.for(F0),V0,H0,Et=class extends(H0=ze,V0=G$,H0){constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:i,isRetryable:a=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:Z0,message:e,cause:i}),this[V0]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=a,this.data=l}static isInstance(e){return ze.hasMarker(e,F0)}},B0="AI_EmptyResponseBodyError",J0=`vercel.ai.error.${B0}`,K$=Symbol.for(J0),W0,G0,Y$=class extends(G0=ze,W0=K$,G0){constructor({message:e="Empty response body"}={}){super({name:B0,message:e}),this[W0]=!0}static isInstance(e){return ze.hasMarker(e,J0)}};function K0(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Y0="AI_InvalidArgumentError",Q0=`vercel.ai.error.${Y0}`,Q$=Symbol.for(Q0),X0,em,tm=class extends(em=ze,X0=Q$,em){constructor({message:e,cause:t,argument:r}){super({name:Y0,message:e,cause:t}),this[X0]=!0,this.argument=r}static isInstance(e){return ze.hasMarker(e,Q0)}},rm="AI_InvalidPromptError",nm=`vercel.ai.error.${rm}`,X$=Symbol.for(nm),om,sm,e8=class extends(sm=ze,om=X$,sm){constructor({prompt:e,message:t,cause:r}){super({name:rm,message:`Invalid prompt: ${t}`,cause:r}),this[om]=!0,this.prompt=e}static isInstance(e){return ze.hasMarker(e,nm)}},am="AI_InvalidResponseDataError",im=`vercel.ai.error.${am}`,t8=Symbol.for(im),lm,cm,Tl=class extends(cm=ze,lm=t8,cm){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:am,message:t}),this[lm]=!0,this.data=e}static isInstance(e){return ze.hasMarker(e,im)}},um="AI_JSONParseError",dm=`vercel.ai.error.${um}`,r8=Symbol.for(dm),pm,hm,$s=class extends(hm=ze,pm=r8,hm){constructor({text:e,cause:t}){super({name:um,message:`JSON parsing failed: Text: ${e}.
58
+ Error message: ${K0(t)}`,cause:t}),this[pm]=!0,this.text=e}static isInstance(e){return ze.hasMarker(e,dm)}},fm="AI_LoadAPIKeyError",mm=`vercel.ai.error.${fm}`,n8=Symbol.for(mm),gm,_m,Cs=class extends(_m=ze,gm=n8,_m){constructor({message:e}){super({name:fm,message:e}),this[gm]=!0}static isInstance(e){return ze.hasMarker(e,mm)}},vm="AI_TooManyEmbeddingValuesForCallError",ym=`vercel.ai.error.${vm}`,o8=Symbol.for(ym),wm,bm,s8=class extends(bm=ze,wm=o8,bm){constructor(e){super({name:vm,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[wm]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ze.hasMarker(e,ym)}},Sm="AI_TypeValidationError",$m=`vercel.ai.error.${Sm}`,a8=Symbol.for($m),Cm,km,io=class Eu extends(km=ze,Cm=a8,km){constructor({value:t,cause:r}){super({name:Sm,message:`Type validation failed: Value: ${JSON.stringify(t)}.
59
+ Error message: ${K0(r)}`,cause:r}),this[Cm]=!0,this.value=t}static isInstance(t){return ze.hasMarker(t,$m)}static wrap({value:t,cause:r}){return Eu.isInstance(r)&&r.value===t?r:new Eu({value:t,cause:r})}},Em="AI_UnsupportedFunctionalityError",Tm=`vercel.ai.error.${Em}`,i8=Symbol.for(Tm),Im,Rm,or=class extends(Rm=ze,Im=i8,Rm){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Em,message:t}),this[Im]=!0,this.functionality=e}static isInstance(e){return ze.hasMarker(e,Tm)}};function Qt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function lo(e){return Object.fromEntries([...e.headers])}var l8=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,i=new Array(t);for(let a=0;a<t;a++)i[a]=r[Math.random()*s|0];return i.join("")};if(e==null)return o;if(r.includes(n))throw new tm({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Lt=l8();function Il(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 u8({error:e,url:t,requestBodyValues:r}){if(Il(e))return e;if(e instanceof TypeError&&c8.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Et({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function d8(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 p8(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 xm(e,...t){const r=new Headers(p8(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var h8="3.0.20";function f8({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Cs({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Cs({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 Cs({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Cs({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function m8({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 g8(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 _8=/"__proto__"\s*:/,v8=/"constructor"\s*:/;function Pm(e){const t=JSON.parse(e);return t===null||typeof t!="object"||_8.test(e)===!1&&v8.test(e)===!1?t:y8(t)}function y8(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 Rl(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Pm(e)}try{return Pm(e)}finally{Error.stackTraceLimit=t}}var ks=Symbol.for("vercel.ai.validator");function w8(e){return{[ks]:!0,validate:e}}function b8(e){return typeof e=="object"&&e!==null&&ks in e&&e[ks]===!0&&"validate"in e}function at(e){let t;return()=>(t==null&&(t=e()),t)}function S8(e){return b8(e)?e:typeof e=="function"?e():$8(e)}function $8(e){return w8(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new io({value:t,cause:r.issues})}})}async function wr({value:e,schema:t}){const r=await xl({value:e,schema:t});if(!r.success)throw io.wrap({value:e,cause:r.error});return r.value}async function xl({value:e,schema:t}){const r=S8(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:io.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:io.wrap({value:e,cause:n}),rawValue:e}}}async function C8({text:e,schema:t}){try{const r=Rl(e);return t==null?r:wr({value:r,schema:t})}catch(r){throw $s.isInstance(r)||io.isInstance(r)?r:new $s({text:e,cause:r})}}async function Om({text:e,schema:t}){try{const r=Rl(e);return t==null?{success:!0,value:r,rawValue:r}:await xl({value:r,schema:t})}catch(r){return{success:!1,error:$s.isInstance(r)?r:new $s({text:e,cause:r}),rawValue:void 0}}}function Mm(e){try{return Rl(e),!0}catch{return!1}}function k8({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Pr).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Om({text:r,schema:t}))}}))}async function br({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await xl({value:t[e],schema:r});if(!n.success)throw new tm({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var E8=()=>globalThis.fetch,sr=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Am({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),T8=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Am({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Am=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=E8()})=>{try{const a=await i(e,{method:"POST",headers:xm(t,`ai-sdk/provider-utils/${h8}`,d8()),body:r.content,signal:s}),l=lo(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw Il(u)||Et.isInstance(u)?u:new Et({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:a,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Il(c)||Et.isInstance(c))?c:new Et({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw u8({error:a,url:e,requestBodyValues:r.values})}};function LR(e){return e}function gn({id:e,name:t,inputSchema:r,outputSchema:n}){return({execute:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:r,outputSchema:n,execute:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l})}var I8=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=lo(n);if(i.trim()==="")return{responseHeaders:a,value:new Et({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await C8({text:i,schema:e});return{responseHeaders:a,value:new Et({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:a,value:new Et({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},Pl=e=>async({response:t})=>{const r=lo(t);if(t.body==null)throw new Y$({});return{responseHeaders:r,value:k8({stream:t.body,schema:e})}},_n=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Om({text:o,schema:e}),i=lo(t);if(!s.success)throw new Et({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}},R8=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=lo(e);if(!e.body)throw new Et({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 Et({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function Es(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const r in t)t[r]=Es(t[r])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>Es(t)):e.items=Es(e.items)),e}var x8=(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("/")},P8=Symbol("Let zodToJsonSchema decide on which parser to use"),Nm={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"},O8=e=>typeof e=="string"?{...Nm,name:e}:{...Nm,...e};function bt(){return{}}function M8(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)!==Q.ZodAny&&(s.items=xe(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 A8(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 N8(){return{type:"boolean"}}function qm(e,t){return xe(e.type._def,t)}var q8=(e,t)=>xe(e.innerType._def,t);function Lm(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Lm(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 L8(e)}}var L8=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 U8(e,t){return{...xe(e.innerType._def,t),default:e.defaultValue()}}function j8(e,t){return t.effectStrategy==="input"?xe(e.schema._def,t):bt()}function D8(e){return{type:"string",enum:Array.from(e.values)}}var z8=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Z8(e,t){const r=[xe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),xe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(z8(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...a}=o;s=a}n.push(s)}}),n.length?{allOf:n}:void 0}function F8(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 Ol=void 0,Ut={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:()=>(Ol===void 0&&(Ol=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ol),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 Um(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":jt(r,"email",n.message,t);break;case"format:idn-email":jt(r,"idn-email",n.message,t);break;case"pattern:zod":it(r,Ut.email,n.message,t);break}break;case"url":jt(r,"uri",n.message,t);break;case"uuid":jt(r,"uuid",n.message,t);break;case"regex":it(r,n.regex,n.message,t);break;case"cuid":it(r,Ut.cuid,n.message,t);break;case"cuid2":it(r,Ut.cuid2,n.message,t);break;case"startsWith":it(r,RegExp(`^${Ml(n.value,t)}`),n.message,t);break;case"endsWith":it(r,RegExp(`${Ml(n.value,t)}$`),n.message,t);break;case"datetime":jt(r,"date-time",n.message,t);break;case"date":jt(r,"date",n.message,t);break;case"time":jt(r,"time",n.message,t);break;case"duration":jt(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":{it(r,RegExp(Ml(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&jt(r,"ipv4",n.message,t),n.version!=="v4"&&jt(r,"ipv6",n.message,t);break}case"base64url":it(r,Ut.base64url,n.message,t);break;case"jwt":it(r,Ut.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&it(r,Ut.ipv4Cidr,n.message,t),n.version!=="v4"&&it(r,Ut.ipv6Cidr,n.message,t);break}case"emoji":it(r,Ut.emoji(),n.message,t);break;case"ulid":{it(r,Ut.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{jt(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{it(r,Ut.base64,n.message,t);break}}break}case"nanoid":it(r,Ut.nanoid,n.message,t)}return r}function Ml(e,t){return t.patternStrategy==="escape"?H8(e):e}var V8=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function H8(e){let t="";for(let r=0;r<e.length;r++)V8.has(e[r])||(t+="\\"),t+=e[r];return t}function jt(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 it(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:jm(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=jm(t,n)}function jm(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="",i=!1,a=!1,l=!1;for(let c=0;c<o.length;c++){if(i){s+=o[c],i=!1;continue}if(n.i){if(a){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
58
60
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
59
- ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
61
+ ]))`;continue}}if(n.s&&o[c]==="."){s+=a?`${o[c]}\r
60
62
  `:`[${o[c]}\r
61
- ]`;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 xf(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Q.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Ef(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Q.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=Tf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function G5(e,t){if(t.mapStrategy==="record")return xf(e,t);const r=xe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||vt(),n=xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||vt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function W5(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 K5(){return{not:vt()}}function Y5(){return{type:"null"}}var Qi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Q5(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Qi&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Qi[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 X5(e,t)}var X5=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>xe(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 e8(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Qi[e.innerType._def.typeName],"null"]};const r=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function t8(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 r8(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=o8(i),c=xe(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=n8(e,t);return s!==void 0&&(r.additionalProperties=s),r}function n8(e,t){if(e.catchall._def.typeName!=="ZodNever")return xe(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 o8(e){try{return e.isOptional()}catch{return!0}}var s8=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return xe(e.innerType._def,t);const n=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:vt()},n]}:vt()},a8=(e,t)=>{if(t.pipeStrategy==="input")return xe(e.in._def,t);if(t.pipeStrategy==="output")return xe(e.out._def,t);const r=xe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=xe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function i8(e,t){return xe(e.type._def,t)}function l8(e,t){const n={type:"array",uniqueItems:!0,items:xe(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 c8(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:xe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function u8(){return{not:vt()}}function d8(){return vt()}var p8=(e,t)=>xe(e.innerType._def,t),f8=(e,t,r)=>{switch(t){case Q.ZodString:return Ef(e,r);case Q.ZodNumber:return t8(e);case Q.ZodObject:return r8(e,r);case Q.ZodBigInt:return q5(e);case Q.ZodBoolean:return L5();case Q.ZodDate:return $f(e,r);case Q.ZodUndefined:return u8();case Q.ZodNull:return Y5();case Q.ZodArray:return A5(e,r);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return Q5(e,r);case Q.ZodIntersection:return V5(e,r);case Q.ZodTuple:return c8(e,r);case Q.ZodRecord:return xf(e,r);case Q.ZodLiteral:return H5(e);case Q.ZodEnum:return Z5(e);case Q.ZodNativeEnum:return W5(e);case Q.ZodNullable:return e8(e,r);case Q.ZodOptional:return s8(e,r);case Q.ZodMap:return G5(e,r);case Q.ZodSet:return l8(e,r);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return i8(e,r);case Q.ZodNaN:case Q.ZodNever:return K5();case Q.ZodEffects:return D5(e,r);case Q.ZodAny:return vt();case Q.ZodUnknown:return d8();case Q.ZodDefault:return z5(e,r);case Q.ZodBranded:return Tf(e,r);case Q.ZodReadonly:return p8(e,r);case Q.ZodCatch:return j5(e,r);case Q.ZodPipeline:return a8(e,r);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(n=>{})()}};function xe(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!==M5)return l}if(o&&!r){const l=h8(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=f8(e,e.typeName,t),i=typeof a=="function"?xe(a(),t):a;if(i&&m8(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var h8=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:O5(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`),vt()):t.$refStrategy==="seen"?vt():void 0}},m8=(e,t,r)=>(e.description&&(r.description=e.description),r),g8=e=>{const t=N5(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}]))}},v8=(e,t)=>{var r;const n=g8(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,g])=>{var h;return{...c,[u]:(h=xe(g._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:vt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=xe(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:vt(),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},_8=v8;function y8(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rf(()=>_8(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 w8(e,t){var r;const n=(r=void 0)!=null?r:!1;return Rf(()=>Xo(xu(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await _a(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function b8(e){return"_zod"in e}function Ce(e,t){return b8(e)?w8(e):y8(e)}var k8=Symbol.for("vercel.ai.schema");function Qe(e){let t;return()=>(t==null&&(t=e()),t)}function Rf(e,{validate:t}={}){return{[k8]:!0,_type:void 0,[Qo]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}var{btoa:S8,atob:C8}=globalThis;function T8(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=C8(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function $8(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return S8(t)}function an(e){return e instanceof Uint8Array?$8(e):e}function E8(e){return e?.replace(/\/$/,"")}var Xi=T({error:T({message:v(),type:v().nullish(),param:et().nullish(),code:ne([v(),q()]).nullish()})}),Zt=R5({errorSchema:Xi,errorToMessage:e=>e.error.message});function Pf(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("gpt-3")||e.startsWith("gpt-4")||e.startsWith("chatgpt-4o")||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 I8({prompt:e,systemMessageMode:t="system"}){const r=[],n=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((a,i)=>{var l,c,u;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const g=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${g};base64,${an(a.data)}`,detail:(c=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Ct({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:an(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:an(a.data),format:"mp3"}};default:throw new Ct({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Ct({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(u=a.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${an(a.data)}`}}}else throw new Ct({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of s)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of s){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:r,warnings:n}}function el({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function Of(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 x8=rt(()=>Ce(T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({message:T({role:L("assistant").nullish(),content:v().nullish(),tool_calls:A(T({id:v().nullish(),type:L("function"),function:T({name:v(),arguments:v()})})).nullish(),annotations:A(T({type:L("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:v(),title:v()})})).nullish()}),index:q(),logprobs:T({content:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}))),R8=rt(()=>Ce(ne([T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({delta:T({role:_e(["assistant"]).nullish(),content:v().nullish(),tool_calls:A(T({index:q(),id:v().nullish(),type:L("function").nullish(),function:T({name:v().nullish(),arguments:v().nullish()})})).nullish(),annotations:A(T({type:L("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:v(),title:v()})})).nullish()}).nullish(),logprobs:T({content:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish()}).nullish(),finish_reason:v().nullish(),index:q()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}),Xi]))),P8=rt(()=>Ce(T({logitBias:ve(Ju(),q()).optional(),logprobs:ne([ce(),q()]).optional(),parallelToolCalls:ce().optional(),user:v().optional(),reasoningEffort:_e(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:q().optional(),store:ce().optional(),metadata:ve(v().max(64),v().max(512)).optional(),prediction:ve(v(),et()).optional(),structuredOutputs:ce().optional(),serviceTier:_e(["auto","flex","priority","default"]).optional(),strictJsonSchema:ce().optional(),textVerbosity:_e(["low","medium","high"]).optional(),promptCacheKey:v().optional(),promptCacheRetention:_e(["in_memory","24h"]).optional(),safetyIdentifier:v().optional()})));function O8({tools:e,toolChoice:t,structuredOutputs:r,strictJsonSchema:n}){e=e?.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const i of e)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?n:void 0}});break;default:o.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:s,toolChoice:a,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const i=a;throw new Ct({functionality:`tool choice type: ${i}`})}}}var M8=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:g,providerOptions:h}){var d,p,w,m;const y=[],_=(d=await pr({provider:"openai",providerOptions:h,schema:P8}))!=null?d:{},f=(p=_.structuredOutputs)!=null?p:!0,b=Pf(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!f&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:k,warnings:S}=I8({prompt:e,systemMessageMode:b.systemMessageMode});y.push(...S);const C=(w=_.strictJsonSchema)!=null?w:!1,I={model:this.modelId,logit_bias:_.logitBias,logprobs:_.logprobs===!0||typeof _.logprobs=="number"?!0:void 0,top_logprobs:typeof _.logprobs=="number"?_.logprobs:typeof _.logprobs=="boolean"&&_.logprobs?0:void 0,user:_.user,parallel_tool_calls:_.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?f&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:C,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:_.textVerbosity,max_completion_tokens:_.maxCompletionTokens,store:_.store,metadata:_.metadata,prediction:_.prediction,reasoning_effort:_.reasoningEffort,service_tier:_.serviceTier,prompt_cache_key:_.promptCacheKey,prompt_cache_retention:_.promptCacheRetention,safety_identifier:_.safetyIdentifier,messages:k};b.isReasoningModel?((_.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(I.temperature!=null&&(I.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,y.push({type:"other",message:"logprobs is not supported for reasoning models"}))),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,y.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,y.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,y.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,y.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,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),_.serviceTier==="flex"&&!b.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),_.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),I.service_tier=void 0);const{tools:x,toolChoice:M,toolWarnings:P}=O8({tools:u,toolChoice:g,structuredOutputs:f,strictJsonSchema:C});return{args:{...I,tools:x,tool_choice:M},warnings:[...y,...P]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,h,d,p;const{args:w,warnings:m}=await this.getArgs(e),{responseHeaders:y,value:_,rawValue:f}=await Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:w,failedResponseHandler:Zt,successfulResponseHandler:sn(x8),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=_.choices[0],k=[],S=b.message.content;S!=null&&S.length>0&&k.push({type:"text",text:S});for(const M of(t=b.message.tool_calls)!=null?t:[])k.push({type:"tool-call",toolCallId:(r=M.id)!=null?r:It(),toolName:M.function.name,input:M.function.arguments});for(const M of(n=b.message.annotations)!=null?n:[])k.push({type:"source",sourceType:"url",id:It(),url:M.url_citation.url,title:M.url_citation.title});const C=(o=_.usage)==null?void 0:o.completion_tokens_details,I=(s=_.usage)==null?void 0:s.prompt_tokens_details,x={openai:{}};return C?.accepted_prediction_tokens!=null&&(x.openai.acceptedPredictionTokens=C?.accepted_prediction_tokens),C?.rejected_prediction_tokens!=null&&(x.openai.rejectedPredictionTokens=C?.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(x.openai.logprobs=b.logprobs.content),{content:k,finishReason:Of(b.finish_reason),usage:{inputTokens:(l=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=_.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(h=(g=_.usage)==null?void 0:g.total_tokens)!=null?h:void 0,reasoningTokens:(d=C?.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(p=I?.cached_tokens)!=null?p:void 0},request:{body:w},response:{...el(_),headers:y,body:f},warnings:m,providerMetadata:x}}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 Kt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:n,failedResponseHandler:Zt,successfulResponseHandler:Wi(R8),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,u=!1;const g={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:r})},transform(h,d){var p,w,m,y,_,f,b,k,S,C,I,x,M,P,U,z,F,te,ie,se,ee,pe,V,O;if(e.includeRawChunks&&d.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){i="error",d.enqueue({type:"error",error:h.error});return}const Z=h.value;if("error"in Z){i="error",d.enqueue({type:"error",error:Z.error});return}if(!c){const R=el(Z);Object.values(R).some(Boolean)&&(c=!0,d.enqueue({type:"response-metadata",...el(Z)}))}Z.usage!=null&&(l.inputTokens=(p=Z.usage.prompt_tokens)!=null?p:void 0,l.outputTokens=(w=Z.usage.completion_tokens)!=null?w:void 0,l.totalTokens=(m=Z.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(_=(y=Z.usage.completion_tokens_details)==null?void 0:y.reasoning_tokens)!=null?_:void 0,l.cachedInputTokens=(b=(f=Z.usage.prompt_tokens_details)==null?void 0:f.cached_tokens)!=null?b:void 0,((k=Z.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(g.openai.acceptedPredictionTokens=(S=Z.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((C=Z.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens)!=null&&(g.openai.rejectedPredictionTokens=(I=Z.usage.completion_tokens_details)==null?void 0:I.rejected_prediction_tokens));const j=Z.choices[0];if(j?.finish_reason!=null&&(i=Of(j.finish_reason)),((x=j?.logprobs)==null?void 0:x.content)!=null&&(g.openai.logprobs=j.logprobs.content),j?.delta==null)return;const E=j.delta;if(E.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:E.content})),E.tool_calls!=null)for(const R of E.tool_calls){const $=R.index;if(a[$]==null){if(R.type!=="function")throw new _n({data:R,message:"Expected 'function' type."});if(R.id==null)throw new _n({data:R,message:"Expected 'id' to be a string."});if(((M=R.function)==null?void 0:M.name)==null)throw new _n({data:R,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:R.id,toolName:R.function.name}),a[$]={id:R.id,type:"function",function:{name:R.function.name,arguments:(P=R.function.arguments)!=null?P:""},hasFinished:!1};const G=a[$];((U=G.function)==null?void 0:U.name)!=null&&((z=G.function)==null?void 0:z.arguments)!=null&&(G.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:G.id,delta:G.function.arguments}),kf(G.function.arguments)&&(d.enqueue({type:"tool-input-end",id:G.id}),d.enqueue({type:"tool-call",toolCallId:(F=G.id)!=null?F:It(),toolName:G.function.name,input:G.function.arguments}),G.hasFinished=!0));continue}const H=a[$];H.hasFinished||(((te=R.function)==null?void 0:te.arguments)!=null&&(H.function.arguments+=(se=(ie=R.function)==null?void 0:ie.arguments)!=null?se:""),d.enqueue({type:"tool-input-delta",id:H.id,delta:(ee=R.function.arguments)!=null?ee:""}),((pe=H.function)==null?void 0:pe.name)!=null&&((V=H.function)==null?void 0:V.arguments)!=null&&kf(H.function.arguments)&&(d.enqueue({type:"tool-input-end",id:H.id}),d.enqueue({type:"tool-call",toolCallId:(O=H.id)!=null?O:It(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}if(E.annotations!=null)for(const R of E.annotations)d.enqueue({type:"source",sourceType:"url",id:It(),url:R.url_citation.url,title:R.url_citation.title})},flush(h){u&&h.enqueue({type:"text-end",id:"0"}),h.enqueue({type:"finish",finishReason:i,usage:l,...g!=null?{providerMetadata:g}:{}})}})),request:{body:n},response:{headers:o}}}};function N8({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
63
+ ]`;continue}s+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!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 Dm(e,t){var r,n,o,s,i,a;const l={type:"object",additionalProperties:(r=xe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Q.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Um(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Q.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=qm(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function B8(e,t){if(t.mapStrategy==="record")return Dm(e,t);const r=xe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||bt(),n=xe(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 J8(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 W8(){return{not:bt()}}function G8(){return{type:"null"}}var Al={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function K8(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Al&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const i=Al[s._def.typeName];return i&&!o.includes(i)?[...o,i]: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 i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];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,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._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 Y8(e,t)}var Y8=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>xe(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 Q8(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Al[e.innerType._def.typeName],"null"]};const r=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function X8(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 eC(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const i in o){let a=o[i];if(a===void 0||a._def===void 0)continue;const l=rC(a),c=xe(a._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,l||n.push(i))}n.length&&(r.required=n);const s=tC(e,t);return s!==void 0&&(r.additionalProperties=s),r}function tC(e,t){if(e.catchall._def.typeName!=="ZodNever")return xe(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 rC(e){try{return e.isOptional()}catch{return!0}}var nC=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return xe(e.innerType._def,t);const n=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:bt()},n]}:bt()},oC=(e,t)=>{if(t.pipeStrategy==="input")return xe(e.in._def,t);if(t.pipeStrategy==="output")return xe(e.out._def,t);const r=xe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=xe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function sC(e,t){return xe(e.type._def,t)}function aC(e,t){const n={type:"array",uniqueItems:!0,items:xe(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 iC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:xe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>xe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function lC(){return{not:bt()}}function cC(){return bt()}var uC=(e,t)=>xe(e.innerType._def,t),dC=(e,t,r)=>{switch(t){case Q.ZodString:return Um(e,r);case Q.ZodNumber:return X8(e);case Q.ZodObject:return eC(e,r);case Q.ZodBigInt:return A8(e);case Q.ZodBoolean:return N8();case Q.ZodDate:return Lm(e,r);case Q.ZodUndefined:return lC();case Q.ZodNull:return G8();case Q.ZodArray:return M8(e,r);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return K8(e,r);case Q.ZodIntersection:return Z8(e,r);case Q.ZodTuple:return iC(e,r);case Q.ZodRecord:return Dm(e,r);case Q.ZodLiteral:return F8(e);case Q.ZodEnum:return D8(e);case Q.ZodNativeEnum:return J8(e);case Q.ZodNullable:return Q8(e,r);case Q.ZodOptional:return nC(e,r);case Q.ZodMap:return B8(e,r);case Q.ZodSet:return aC(e,r);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return sC(e,r);case Q.ZodNaN:case Q.ZodNever:return W8();case Q.ZodEffects:return j8(e,r);case Q.ZodAny:return bt();case Q.ZodUnknown:return cC();case Q.ZodDefault:return U8(e,r);case Q.ZodBranded:return qm(e,r);case Q.ZodReadonly:return uC(e,r);case Q.ZodCatch:return q8(e,r);case Q.ZodPipeline:return oC(e,r);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(n=>{})()}};function xe(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!==P8)return l}if(o&&!r){const l=pC(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=dC(e,e.typeName,t),a=typeof i=="function"?xe(i(),t):i;if(a&&hC(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var pC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:x8(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}},hC=(e,t,r)=>(e.description&&(r.description=e.description),r),fC=e=>{const t=O8(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}]))}},mC=(e,t)=>{var r;const n=fC(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,m])=>{var f;return{...c,[u]:(f=xe(m._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?f:bt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=xe(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:bt(),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a);const l=s===void 0?o?{...i,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:i}};return l.$schema="http://json-schema.org/draft-07/schema#",l},gC=mC;function _C(e,t){var r;const n=(r=void 0)!=null?r:!1;return zm(()=>gC(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 vC(e,t){var r;const n=(r=void 0)!=null?r:!1;return zm(()=>Es(Jd(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await si(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function yC(e){return"_zod"in e}function Ee(e,t){return yC(e)?vC(e):_C(e)}var wC=Symbol.for("vercel.ai.schema");function nt(e){let t;return()=>(t==null&&(t=e()),t)}function zm(e,{validate:t}={}){return{[wC]:!0,_type:void 0,[ks]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}var{btoa:bC,atob:SC}=globalThis;function $C(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=SC(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function CC(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return bC(t)}function vn(e){return e instanceof Uint8Array?CC(e):e}function kC(e){return e?.replace(/\/$/,"")}var Nl=C({error:C({message:d(),type:d().nullish(),param:tt().nullish(),code:X([d(),A()]).nullish()})}),Xt=I8({errorSchema:Nl,errorToMessage:e=>e.error.message});function Zm(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("gpt-3")||e.startsWith("gpt-4")||e.startsWith("chatgpt-4o")||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 EC({prompt:e,systemMessageMode:t="system"}){const r=[],n=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{n.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(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((i,a)=>{var l,c,u;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const m=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${m};base64,${vn(i.data)}`,detail:(c=(l=i.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new or({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 or({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new or({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(u=i.filename)!=null?u:`part-${a}.pdf`,file_data:`data:application/pdf;base64,${vn(i.data)}`}}}else throw new or({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const a=[];for(const l of s)switch(l.type){case"text":{i+=l.text;break}case"tool-call":{a.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:i,tool_calls:a.length>0?a:void 0});break}case"tool":{for(const i of s){const a=i.output;let l;switch(a.type){case"text":case"error-text":l=a.value;break;case"content":case"json":case"error-json":l=JSON.stringify(a.value);break}r.push({role:"tool",tool_call_id:i.toolCallId,content:l})}break}default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return{messages:r,warnings:n}}function ql({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function Fm(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 TC=at(()=>Ee(C({id:d().nullish(),created:A().nullish(),model:d().nullish(),choices:R(C({message:C({role:O("assistant").nullish(),content:d().nullish(),tool_calls:R(C({id:d().nullish(),type:O("function"),function:C({name:d(),arguments:d()})})).nullish(),annotations:R(C({type:O("url_citation"),url_citation:C({start_index:A(),end_index:A(),url:d(),title:d()})})).nullish()}),index:A(),logprobs:C({content:R(C({token:d(),logprob:A(),top_logprobs:R(C({token:d(),logprob:A()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:C({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:C({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}))),IC=at(()=>Ee(X([C({id:d().nullish(),created:A().nullish(),model:d().nullish(),choices:R(C({delta:C({role:_e(["assistant"]).nullish(),content:d().nullish(),tool_calls:R(C({index:A(),id:d().nullish(),type:O("function").nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:R(C({type:O("url_citation"),url_citation:C({start_index:A(),end_index:A(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:C({content:R(C({token:d(),logprob:A(),top_logprobs:R(C({token:d(),logprob:A()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:A()})),usage:C({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:C({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}),Nl]))),RC=at(()=>Ee(C({logitBias:oe(cp(),A()).optional(),logprobs:X([te(),A()]).optional(),parallelToolCalls:te().optional(),user:d().optional(),reasoningEffort:_e(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:A().optional(),store:te().optional(),metadata:oe(d().max(64),d().max(512)).optional(),prediction:oe(d(),tt()).optional(),structuredOutputs:te().optional(),serviceTier:_e(["auto","flex","priority","default"]).optional(),strictJsonSchema:te().optional(),textVerbosity:_e(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:_e(["in_memory","24h"]).optional(),safetyIdentifier:d().optional()})));function xC({tools:e,toolChoice:t,structuredOutputs:r,strictJsonSchema:n}){e=e?.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const a of e)switch(a.type){case"function":s.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:r?n:void 0}});break;default:o.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const i=t.type;switch(i){case"auto":case"none":case"required":return{tools:s,toolChoice:i,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const a=i;throw new or({functionality:`tool choice type: ${a}`})}}}var PC=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:i,stopSequences:a,responseFormat:l,seed:c,tools:u,toolChoice:m,providerOptions:f}){var p,h,v,_;const w=[],g=(p=await br({provider:"openai",providerOptions:f,schema:RC}))!=null?p:{},y=(h=g.structuredOutputs)!=null?h:!0,b=Zm(this.modelId);o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!y&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:S,warnings:$}=EC({prompt:e,systemMessageMode:b.systemMessageMode});w.push(...$);const k=(v=g.strictJsonSchema)!=null?v:!1,I={model:this.modelId,logit_bias:g.logitBias,logprobs:g.logprobs===!0||typeof g.logprobs=="number"?!0:void 0,top_logprobs:typeof g.logprobs=="number"?g.logprobs:typeof g.logprobs=="boolean"&&g.logprobs?0:void 0,user:g.user,parallel_tool_calls:g.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:i,response_format:l?.type==="json"?y&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:k,name:(_=l.name)!=null?_:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,seed:c,verbosity:g.textVerbosity,max_completion_tokens:g.maxCompletionTokens,store:g.store,metadata:g.metadata,prediction:g.prediction,reasoning_effort:g.reasoningEffort,service_tier:g.serviceTier,prompt_cache_key:g.promptCacheKey,prompt_cache_retention:g.promptCacheRetention,safety_identifier:g.safetyIdentifier,messages:S};b.isReasoningModel?((g.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(I.temperature!=null&&(I.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,w.push({type:"other",message:"logprobs is not supported for reasoning models"}))),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,w.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,w.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,w.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,w.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,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),g.serviceTier==="flex"&&!b.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),g.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),I.service_tier=void 0);const{tools:P,toolChoice:L,toolWarnings:N}=xC({tools:u,toolChoice:m,structuredOutputs:y,strictJsonSchema:k});return{args:{...I,tools:P,tool_choice:L},warnings:[...w,...N]}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,m,f,p,h;const{args:v,warnings:_}=await this.getArgs(e),{responseHeaders:w,value:g,rawValue:y}=await sr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Qt(this.config.headers(),e.headers),body:v,failedResponseHandler:Xt,successfulResponseHandler:_n(TC),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=g.choices[0],S=[],$=b.message.content;$!=null&&$.length>0&&S.push({type:"text",text:$});for(const L of(t=b.message.tool_calls)!=null?t:[])S.push({type:"tool-call",toolCallId:(r=L.id)!=null?r:Lt(),toolName:L.function.name,input:L.function.arguments});for(const L of(n=b.message.annotations)!=null?n:[])S.push({type:"source",sourceType:"url",id:Lt(),url:L.url_citation.url,title:L.url_citation.title});const k=(o=g.usage)==null?void 0:o.completion_tokens_details,I=(s=g.usage)==null?void 0:s.prompt_tokens_details,P={openai:{}};return k?.accepted_prediction_tokens!=null&&(P.openai.acceptedPredictionTokens=k?.accepted_prediction_tokens),k?.rejected_prediction_tokens!=null&&(P.openai.rejectedPredictionTokens=k?.rejected_prediction_tokens),((i=b.logprobs)==null?void 0:i.content)!=null&&(P.openai.logprobs=b.logprobs.content),{content:S,finishReason:Fm(b.finish_reason),usage:{inputTokens:(l=(a=g.usage)==null?void 0:a.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=g.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(f=(m=g.usage)==null?void 0:m.total_tokens)!=null?f:void 0,reasoningTokens:(p=k?.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(h=I?.cached_tokens)!=null?h:void 0},request:{body:v},response:{...ql(g),headers:w,body:y},warnings:_,providerMetadata:P}}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 sr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Qt(this.config.headers(),e.headers),body:n,failedResponseHandler:Xt,successfulResponseHandler:Pl(IC),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=[];let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,u=!1;const m={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,p){var h,v,_,w,g,y,b,S,$,k,I,P,L,N,j,D,F,ne,ue,ie,re,he,V,M;if(e.includeRawChunks&&p.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){a="error",p.enqueue({type:"error",error:f.error});return}const Z=f.value;if("error"in Z){a="error",p.enqueue({type:"error",error:Z.error});return}if(!c){const x=ql(Z);Object.values(x).some(Boolean)&&(c=!0,p.enqueue({type:"response-metadata",...ql(Z)}))}Z.usage!=null&&(l.inputTokens=(h=Z.usage.prompt_tokens)!=null?h:void 0,l.outputTokens=(v=Z.usage.completion_tokens)!=null?v:void 0,l.totalTokens=(_=Z.usage.total_tokens)!=null?_:void 0,l.reasoningTokens=(g=(w=Z.usage.completion_tokens_details)==null?void 0:w.reasoning_tokens)!=null?g:void 0,l.cachedInputTokens=(b=(y=Z.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?b:void 0,((S=Z.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens)!=null&&(m.openai.acceptedPredictionTokens=($=Z.usage.completion_tokens_details)==null?void 0:$.accepted_prediction_tokens),((k=Z.usage.completion_tokens_details)==null?void 0:k.rejected_prediction_tokens)!=null&&(m.openai.rejectedPredictionTokens=(I=Z.usage.completion_tokens_details)==null?void 0:I.rejected_prediction_tokens));const U=Z.choices[0];if(U?.finish_reason!=null&&(a=Fm(U.finish_reason)),((P=U?.logprobs)==null?void 0:P.content)!=null&&(m.openai.logprobs=U.logprobs.content),U?.delta==null)return;const T=U.delta;if(T.content!=null&&(u||(p.enqueue({type:"text-start",id:"0"}),u=!0),p.enqueue({type:"text-delta",id:"0",delta:T.content})),T.tool_calls!=null)for(const x of T.tool_calls){const E=x.index;if(i[E]==null){if(x.type!=="function")throw new Tl({data:x,message:"Expected 'function' type."});if(x.id==null)throw new Tl({data:x,message:"Expected 'id' to be a string."});if(((L=x.function)==null?void 0:L.name)==null)throw new Tl({data:x,message:"Expected 'function.name' to be a string."});p.enqueue({type:"tool-input-start",id:x.id,toolName:x.function.name}),i[E]={id:x.id,type:"function",function:{name:x.function.name,arguments:(N=x.function.arguments)!=null?N:""},hasFinished:!1};const W=i[E];((j=W.function)==null?void 0:j.name)!=null&&((D=W.function)==null?void 0:D.arguments)!=null&&(W.function.arguments.length>0&&p.enqueue({type:"tool-input-delta",id:W.id,delta:W.function.arguments}),Mm(W.function.arguments)&&(p.enqueue({type:"tool-input-end",id:W.id}),p.enqueue({type:"tool-call",toolCallId:(F=W.id)!=null?F:Lt(),toolName:W.function.name,input:W.function.arguments}),W.hasFinished=!0));continue}const H=i[E];H.hasFinished||(((ne=x.function)==null?void 0:ne.arguments)!=null&&(H.function.arguments+=(ie=(ue=x.function)==null?void 0:ue.arguments)!=null?ie:""),p.enqueue({type:"tool-input-delta",id:H.id,delta:(re=x.function.arguments)!=null?re:""}),((he=H.function)==null?void 0:he.name)!=null&&((V=H.function)==null?void 0:V.arguments)!=null&&Mm(H.function.arguments)&&(p.enqueue({type:"tool-input-end",id:H.id}),p.enqueue({type:"tool-call",toolCallId:(M=H.id)!=null?M:Lt(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}if(T.annotations!=null)for(const x of T.annotations)p.enqueue({type:"source",sourceType:"url",id:Lt(),url:x.url_citation.url,title:x.url_citation.title})},flush(f){u&&f.enqueue({type:"text-end",id:"0"}),f.enqueue({type:"finish",finishReason:a,usage:l,...m!=null?{providerMetadata:m}:{}})}})),request:{body:n},response:{headers:o}}}};function OC({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
62
64
 
63
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new br({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}:
64
- ${a}
65
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new e8({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const i=s.map(a=>{switch(a.type){case"text":return a.text}}).filter(Boolean).join("");n+=`${t}:
66
+ ${i}
65
67
 
66
- `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Ct({functionality:"tool-call messages"})}}).join("");n+=`${r}:
67
- ${a}
68
+ `;break}case"assistant":{const i=s.map(a=>{switch(a.type){case"text":return a.text;case"tool-call":throw new or({functionality:"tool-call messages"})}}).join("");n+=`${r}:
69
+ ${i}
68
70
 
69
- `;break}case"tool":throw new Ct({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
71
+ `;break}case"tool":throw new or({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return n+=`${r}:
70
72
  `,{prompt:n,stopSequences:[`
71
- ${t}:`]}}function Mf({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 Nf(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 A8=rt(()=>Ce(T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({text:v(),finish_reason:v(),logprobs:T({tokens:A(v()),token_logprobs:A(q()),top_logprobs:A(ve(v(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}))),q8=rt(()=>Ce(ne([T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({text:v(),finish_reason:v().nullish(),index:q(),logprobs:T({tokens:A(v()),token_logprobs:A(q()),top_logprobs:A(ve(v(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}),Xi]))),Af=rt(()=>Ce(T({echo:ce().optional(),logitBias:ve(v(),q()).optional(),suffix:v().optional(),user:v().optional(),logprobs:ne([ce(),q()]).optional()}))),L8=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:g,providerOptions:h}){const d=[],p={...await pr({provider:"openai",providerOptions:h,schema:Af}),...await pr({provider:this.providerOptionsName,providerOptions:h,schema:Af})};o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),c?.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:w,stopSequences:m}=N8({prompt:e}),y=[...m??[],...i??[]];return{args:{model:this.modelId,echo:p.echo,logit_bias:p.logitBias,logprobs:p?.logprobs===!0?0:p?.logprobs===!1?void 0:p?.logprobs,suffix:p.suffix,user:p.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:g,prompt:w,stop:y.length>0?y:void 0},warnings:d}}async doGenerate(e){var t,r,n;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:o,failedResponseHandler:Zt,successfulResponseHandler:sn(A8),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(n=i.usage)==null?void 0:n.total_tokens},finishReason:Nf(c.finish_reason),request:{body:o},response:{...Mf(i),headers:a,body:l},providerMetadata:u,warnings:s}}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 Kt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:n,failedResponseHandler:Zt,successfulResponseHandler:Wi(q8),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let 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="error",g.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){a="error",g.enqueue({type:"error",error:h.error});return}c&&(c=!1,g.enqueue({type:"response-metadata",...Mf(h)}),g.enqueue({type:"text-start",id:"0"})),h.usage!=null&&(l.inputTokens=h.usage.prompt_tokens,l.outputTokens=h.usage.completion_tokens,l.totalTokens=h.usage.total_tokens);const d=h.choices[0];d?.finish_reason!=null&&(a=Nf(d.finish_reason)),d?.logprobs!=null&&(i.openai.logprobs=d.logprobs),d?.text!=null&&d.text.length>0&&g.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:n},response:{headers:o}}}},j8=rt(()=>Ce(T({dimensions:q().optional(),user:v().optional()}))),U8=rt(()=>Ce(T({data:A(T({embedding:A(q())})),usage:T({prompt_tokens:q()}).nullish()}))),z8=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new U2({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await pr({provider:"openai",providerOptions:n,schema:j8}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Kt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Dt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Zt,successfulResponseHandler:sn(U8),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},D8=rt(()=>Ce(T({created:q().nullish(),data:A(T({b64_json:v(),revised_prompt:v().nullish()})),background:v().nullish(),output_format:v().nullish(),size:v().nullish(),quality:v().nullish(),usage:T({input_tokens:q().nullish(),output_tokens:q().nullish(),total_tokens:q().nullish(),input_tokens_details:T({image_tokens:q().nullish(),text_tokens:q().nullish()}).nullish()}).nullish()}))),Z8={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},F8=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),V8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=Z8[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,c,u,g;const h=[];n!=null&&h.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&h.push({type:"unsupported-setting",setting:"seed"});const d=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:p,responseHeaders:w}=await Kt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Dt(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:r,...(g=s.openai)!=null?g:{},...F8.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Zt,successfulResponseHandler:sn(D8),abortSignal:i,fetch:this.config.fetch});return{images:p.data.map(m=>m.b64_json),warnings:h,response:{timestamp:d,modelId:this.modelId,headers:w},providerMetadata:{openai:{images:p.data.map(m=>({...m.revised_prompt?{revisedPrompt:m.revised_prompt}:{},...p.created!=null?{created:p.created}:{},...p.size!=null?{size:p.size}:{},...p.quality!=null?{quality:p.quality}:{},...p.background!=null?{background:p.background}:{},...p.output_format!=null?{outputFormat:p.output_format}:{}}))}}}}},H8=Qe(()=>Ce(T({code:v().nullish(),containerId:v()}))),B8=Qe(()=>Ce(T({outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullish()}))),J8=Qe(()=>Ce(T({container:ne([v(),T({fileIds:A(v()).optional()})]).optional()}))),G8=on({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:H8,outputSchema:B8}),W8=(e={})=>G8(e),qf=T({key:v(),type:_e(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ne([v(),q(),ce(),A(v())])}),Lf=T({type:_e(["and","or"]),filters:A(ne([qf,Fu(()=>Lf)]))}),K8=Qe(()=>Ce(T({vectorStoreIds:A(v()),maxNumResults:q().optional(),ranking:T({ranker:v().optional(),scoreThreshold:q().optional()}).optional(),filters:ne([qf,Lf]).optional()}))),Y8=Qe(()=>Ce(T({queries:A(v()),results:A(T({attributes:ve(v(),$e()),fileId:v(),filename:v(),score:q(),text:v()})).nullable()}))),Q8=on({id:"openai.file_search",name:"file_search",inputSchema:T({}),outputSchema:Y8}),X8=Qe(()=>Ce(T({background:_e(["auto","opaque","transparent"]).optional(),inputFidelity:_e(["low","high"]).optional(),inputImageMask:T({fileId:v().optional(),imageUrl:v().optional()}).optional(),model:v().optional(),moderation:_e(["auto"]).optional(),outputCompression:q().int().min(0).max(100).optional(),outputFormat:_e(["png","jpeg","webp"]).optional(),partialImages:q().int().min(0).max(3).optional(),quality:_e(["auto","low","medium","high"]).optional(),size:_e(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),e7=Qe(()=>Ce(T({}))),t7=Qe(()=>Ce(T({result:v()}))),r7=on({id:"openai.image_generation",name:"image_generation",inputSchema:e7,outputSchema:t7}),n7=(e={})=>r7(e),jf=Qe(()=>Ce(T({action:T({type:L("exec"),command:A(v()),timeoutMs:q().optional(),user:v().optional(),workingDirectory:v().optional(),env:ve(v(),v()).optional()})}))),Uf=Qe(()=>Ce(T({output:v()}))),o7=on({id:"openai.local_shell",name:"local_shell",inputSchema:jf,outputSchema:Uf}),s7=Qe(()=>Ce(T({externalWebAccess:ce().optional(),filters:T({allowedDomains:A(v()).optional()}).optional(),searchContextSize:_e(["low","medium","high"]).optional(),userLocation:T({type:L("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),a7=Qe(()=>Ce(T({}))),i7=Qe(()=>Ce(T({action:Ze("type",[T({type:L("search"),query:v().optional()}),T({type:L("openPage"),url:v().nullish()}),T({type:L("findInPage"),url:v().nullish(),pattern:v().nullish()})]),sources:A(Ze("type",[T({type:L("url"),url:v()}),T({type:L("api"),name:v()})])).optional()}))),l7=on({id:"openai.web_search",name:"web_search",inputSchema:a7,outputSchema:i7}),c7=(e={})=>l7(e),u7=Qe(()=>Ce(T({searchContextSize:_e(["low","medium","high"]).optional(),userLocation:T({type:L("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),d7=Qe(()=>Ce(T({}))),p7=Qe(()=>Ce(T({action:Ze("type",[T({type:L("search"),query:v().optional()}),T({type:L("openPage"),url:v().nullish()}),T({type:L("findInPage"),url:v().nullish(),pattern:v().nullish()})])}))),f7=on({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:d7,outputSchema:p7}),h7={codeInterpreter:W8,fileSearch:Q8,imageGeneration:n7,localShell:o7,webSearchPreview:f7,webSearch:c7};function zf(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function m7({prompt:e,systemMessageMode:t,fileIdPrefixes:r,store:n,hasLocalShellTool:o=!1}){var s,a,i,l;const c=[],u=[];for(const{role:g,content:h}of e)switch(g){case"system":{switch(t){case"system":{c.push({role:"system",content:h});break}case"developer":{c.push({role:"developer",content:h});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=t;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{c.push({role:"user",content:h.map((d,p)=>{var w,m,y;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const _=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&zf(d.data,r)?{file_id:d.data}:{image_url:`data:${_};base64,${an(d.data)}`},detail:(m=(w=d.providerOptions)==null?void 0:w.openai)==null?void 0:m.imageDetail}}else{if(d.mediaType==="application/pdf")return d.data instanceof URL?{type:"input_file",file_url:d.data.toString()}:{type:"input_file",...typeof d.data=="string"&&zf(d.data,r)?{file_id:d.data}:{filename:(y=d.filename)!=null?y:`part-${p}.pdf`,file_data:`data:application/pdf;base64,${an(d.data)}`}};throw new Ct({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},p={};for(const w of h)switch(w.type){case"text":{const m=(a=(s=w.providerOptions)==null?void 0:s.openai)==null?void 0:a.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:w.text}],id:m});break}case"tool-call":{if(p[w.toolCallId]=w,w.providerExecuted)break;const m=(l=(i=w.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}if(o&&w.toolName==="local_shell"){const y=await dr({value:w.input,schema:jf});c.push({type:"local_shell_call",call_id:w.toolCallId,id:m,action:{type:"exec",command:y.action.command,timeout_ms:y.action.timeoutMs,user:y.action.user,working_directory:y.action.workingDirectory,env:y.action.env}});break}c.push({type:"function_call",call_id:w.toolCallId,name:w.toolName,arguments:JSON.stringify(w.input),id:m});break}case"tool-result":{n?c.push({type:"item_reference",id:w.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${w.toolName} are not sent to the API when store is false`});break}case"reasoning":{const m=await pr({provider:"openai",providerOptions:w.providerOptions,schema:g7}),y=m?.itemId;if(y!=null){const _=d[y];if(n)_===void 0&&(c.push({type:"item_reference",id:y}),d[y]={type:"reasoning",id:y,summary:[]});else{const f=[];w.text.length>0?f.push({type:"summary_text",text:w.text}):_!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(w)}.`}),_===void 0?(d[y]={type:"reasoning",id:y,encrypted_content:m?.reasoningEncryptedContent,summary:f},c.push(d[y])):(_.summary.push(...f),m?.reasoningEncryptedContent!=null&&(_.encrypted_content=m.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(w)}.`});break}}break}case"tool":{for(const d of h){const p=d.output;if(o&&d.toolName==="local_shell"&&p.type==="json"){const m=await dr({value:p.value,schema:Uf});c.push({type:"local_shell_call_output",call_id:d.toolCallId,output:m.output});break}let w;switch(p.type){case"text":case"error-text":w=p.value;break;case"json":case"error-json":w=JSON.stringify(p.value);break;case"content":w=p.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}c.push({type:"function_call_output",call_id:d.toolCallId,output:w})}break}default:{const d=g;throw new Error(`Unsupported role: ${d}`)}}return{input:c,warnings:u}}var g7=T({itemId:v().nullish(),reasoningEncryptedContent:v().nullish()});function Df({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":"unknown"}}var v7=rt(()=>Ce(ne([T({type:L("response.output_text.delta"),item_id:v(),delta:v(),logprobs:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish()}),T({type:_e(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:v()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish()}).nullish()}),service_tier:v().nullish()})}),T({type:L("response.created"),response:T({id:v(),created_at:q(),model:v(),service_tier:v().nullish()})}),T({type:L("response.output_item.added"),output_index:q(),item:Ze("type",[T({type:L("message"),id:v()}),T({type:L("reasoning"),id:v(),encrypted_content:v().nullish()}),T({type:L("function_call"),id:v(),call_id:v(),name:v(),arguments:v()}),T({type:L("web_search_call"),id:v(),status:v()}),T({type:L("computer_call"),id:v(),status:v()}),T({type:L("file_search_call"),id:v()}),T({type:L("image_generation_call"),id:v()}),T({type:L("code_interpreter_call"),id:v(),container_id:v(),code:v().nullable(),outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullable(),status:v()})])}),T({type:L("response.output_item.done"),output_index:q(),item:Ze("type",[T({type:L("message"),id:v()}),T({type:L("reasoning"),id:v(),encrypted_content:v().nullish()}),T({type:L("function_call"),id:v(),call_id:v(),name:v(),arguments:v(),status:L("completed")}),T({type:L("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullable()}),T({type:L("image_generation_call"),id:v(),result:v()}),T({type:L("web_search_call"),id:v(),status:v(),action:Ze("type",[T({type:L("search"),query:v().nullish(),sources:A(Ze("type",[T({type:L("url"),url:v()}),T({type:L("api"),name:v()})])).nullish()}),T({type:L("open_page"),url:v().nullish()}),T({type:L("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),T({type:L("file_search_call"),id:v(),queries:A(v()),results:A(T({attributes:ve(v(),$e()),file_id:v(),filename:v(),score:q(),text:v()})).nullish()}),T({type:L("local_shell_call"),id:v(),call_id:v(),action:T({type:L("exec"),command:A(v()),timeout_ms:q().optional(),user:v().optional(),working_directory:v().optional(),env:ve(v(),v()).optional()})}),T({type:L("computer_call"),id:v(),status:L("completed")})])}),T({type:L("response.function_call_arguments.delta"),item_id:v(),output_index:q(),delta:v()}),T({type:L("response.image_generation_call.partial_image"),item_id:v(),output_index:q(),partial_image_b64:v()}),T({type:L("response.code_interpreter_call_code.delta"),item_id:v(),output_index:q(),delta:v()}),T({type:L("response.code_interpreter_call_code.done"),item_id:v(),output_index:q(),code:v()}),T({type:L("response.output_text.annotation.added"),annotation:Ze("type",[T({type:L("url_citation"),start_index:q(),end_index:q(),url:v(),title:v()}),T({type:L("file_citation"),file_id:v(),filename:v().nullish(),index:q().nullish(),start_index:q().nullish(),end_index:q().nullish(),quote:v().nullish()})])}),T({type:L("response.reasoning_summary_part.added"),item_id:v(),summary_index:q()}),T({type:L("response.reasoning_summary_text.delta"),item_id:v(),summary_index:q(),delta:v()}),T({type:L("response.reasoning_summary_part.done"),item_id:v(),summary_index:q()}),T({type:L("error"),sequence_number:q(),error:T({type:v(),code:v(),message:v(),param:v().nullish()})}),T({type:v()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),_7=rt(()=>Ce(T({id:v().optional(),created_at:q().optional(),error:T({message:v(),type:v(),param:v().nullish(),code:v()}).nullish(),model:v().optional(),output:A(Ze("type",[T({type:L("message"),role:L("assistant"),id:v(),content:A(T({type:L("output_text"),text:v(),logprobs:A(T({token:v(),logprob:q(),top_logprobs:A(T({token:v(),logprob:q()}))})).nullish(),annotations:A(Ze("type",[T({type:L("url_citation"),start_index:q(),end_index:q(),url:v(),title:v()}),T({type:L("file_citation"),file_id:v(),filename:v().nullish(),index:q().nullish(),start_index:q().nullish(),end_index:q().nullish(),quote:v().nullish()}),T({type:L("container_file_citation"),container_id:v(),file_id:v(),filename:v().nullish(),start_index:q().nullish(),end_index:q().nullish(),index:q().nullish()}),T({type:L("file_path"),file_id:v(),index:q().nullish()})]))}))}),T({type:L("web_search_call"),id:v(),status:v(),action:Ze("type",[T({type:L("search"),query:v().nullish(),sources:A(Ze("type",[T({type:L("url"),url:v()}),T({type:L("api"),name:v()})])).nullish()}),T({type:L("open_page"),url:v().nullish()}),T({type:L("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),T({type:L("file_search_call"),id:v(),queries:A(v()),results:A(T({attributes:ve(v(),ne([v(),q(),ce()])),file_id:v(),filename:v(),score:q(),text:v()})).nullish()}),T({type:L("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:A(Ze("type",[T({type:L("logs"),logs:v()}),T({type:L("image"),url:v()})])).nullable()}),T({type:L("image_generation_call"),id:v(),result:v()}),T({type:L("local_shell_call"),id:v(),call_id:v(),action:T({type:L("exec"),command:A(v()),timeout_ms:q().optional(),user:v().optional(),working_directory:v().optional(),env:ve(v(),v()).optional()})}),T({type:L("function_call"),call_id:v(),name:v(),arguments:v(),id:v()}),T({type:L("computer_call"),id:v(),status:v().optional()}),T({type:L("reasoning"),id:v(),encrypted_content:v().nullish(),summary:A(T({type:L("summary_text"),text:v()}))})])).optional(),service_tier:v().nullish(),incomplete_details:T({reason:v()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish()}).nullish()}).optional()}))),Zf=20,y7=rt(()=>Ce(T({conversation:v().nullish(),include:A(_e(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:v().nullish(),logprobs:ne([ce(),q().min(1).max(Zf)]).optional(),maxToolCalls:q().nullish(),metadata:et().nullish(),parallelToolCalls:ce().nullish(),previousResponseId:v().nullish(),promptCacheKey:v().nullish(),promptCacheRetention:_e(["in_memory","24h"]).nullish(),reasoningEffort:v().nullish(),reasoningSummary:v().nullish(),safetyIdentifier:v().nullish(),serviceTier:_e(["auto","flex","priority","default"]).nullish(),store:ce().nullish(),strictJsonSchema:ce().nullish(),textVerbosity:_e(["low","medium","high"]).nullish(),truncation:_e(["auto","disabled"]).nullish(),user:v().nullish()})));async function w7({tools:e,toolChoice:t,strictJsonSchema:r}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await dr({value:a.args,schema:K8});o.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await dr({value:a.args,schema:u7});o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await dr({value:a.args,schema:s7});o.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,external_web_access:i.externalWebAccess,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await dr({value:a.args,schema:J8});o.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await dr({value:a.args,schema:X8});o.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:n};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:n};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const a=s;throw new Ct({functionality:`tool choice type: ${a}`})}}}var b7=class{constructor(e,t){this.specificationVersion="v2",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:h}){var d,p,w,m;const y=[],_=Pf(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),s!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const f=await pr({provider:"openai",providerOptions:c,schema:y7});f?.conversation&&f?.previousResponseId&&y.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:k}=await m7({prompt:l,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=f?.store)!=null?d:!0,hasLocalShellTool:x("openai.local_shell")});y.push(...k);const S=(p=f?.strictJsonSchema)!=null?p:!1;let C=f?.include;function I(se){C==null?C=[se]:C.includes(se)||(C=[...C,se])}function x(se){return u?.find(ee=>ee.type==="provider-defined"&&ee.id===se)!=null}const M=typeof f?.logprobs=="number"?f?.logprobs:f?.logprobs===!0?Zf:void 0;M&&I("message.output_text.logprobs");const P=(w=u?.find(se=>se.type==="provider-defined"&&(se.id==="openai.web_search"||se.id==="openai.web_search_preview")))==null?void 0:w.name;P&&I("web_search_call.action.sources"),x("openai.code_interpreter")&&I("code_interpreter_call.outputs");const U=f?.store;U===!1&&_.isReasoningModel&&I("reasoning.encrypted_content");const z={model:this.modelId,input:b,temperature:t,top_p:n,max_output_tokens:e,...(h?.type==="json"||f?.textVerbosity)&&{text:{...h?.type==="json"&&{format:h.schema!=null?{type:"json_schema",strict:S,name:(m=h.name)!=null?m:"response",description:h.description,schema:h.schema}:{type:"json_object"}},...f?.textVerbosity&&{verbosity:f.textVerbosity}}},conversation:f?.conversation,max_tool_calls:f?.maxToolCalls,metadata:f?.metadata,parallel_tool_calls:f?.parallelToolCalls,previous_response_id:f?.previousResponseId,store:U,user:f?.user,instructions:f?.instructions,service_tier:f?.serviceTier,include:C,prompt_cache_key:f?.promptCacheKey,prompt_cache_retention:f?.promptCacheRetention,safety_identifier:f?.safetyIdentifier,top_logprobs:M,truncation:f?.truncation,..._.isReasoningModel&&(f?.reasoningEffort!=null||f?.reasoningSummary!=null)&&{reasoning:{...f?.reasoningEffort!=null&&{effort:f.reasoningEffort},...f?.reasoningSummary!=null&&{summary:f.reasoningSummary}}}};_.isReasoningModel?f?.reasoningEffort==="none"&&_.supportsNonReasoningParameters||(z.temperature!=null&&(z.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(f?.reasoningEffort!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),f?.reasoningSummary!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),f?.serviceTier==="flex"&&!_.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete z.service_tier),f?.serviceTier==="priority"&&!_.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete z.service_tier);const{tools:F,toolChoice:te,toolWarnings:ie}=await w7({tools:u,toolChoice:g,strictJsonSchema:S});return{webSearchToolName:P,args:{...z,tools:F,tool_choice:te},warnings:[...y,...ie],store:U}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,h,d,p,w,m,y,_,f,b,k,S,C,I,x,M,P,U;const{args:z,warnings:F,webSearchToolName:te}=await this.getArgs(e),ie=this.config.url({path:"/responses",modelId:this.modelId}),se=this.config.provider.replace(".responses",""),{responseHeaders:ee,value:pe,rawValue:V}=await Kt({url:ie,headers:Dt(this.config.headers(),e.headers),body:z,failedResponseHandler:Zt,successfulResponseHandler:sn(_7),abortSignal:e.abortSignal,fetch:this.config.fetch});if(pe.error)throw new Pe({message:pe.error.message,url:ie,requestBodyValues:z,statusCode:400,responseHeaders:ee,responseBody:V,isRetryable:!1});const O=[],Z=[];let j=!1;for(const $ of pe.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const H of $.summary)O.push({type:"reasoning",text:H.text,providerMetadata:{[se]:{itemId:$.id,reasoningEncryptedContent:(t=$.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{O.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[se]:{itemId:$.id}}});break}case"message":{for(const H of $.content){(n=(r=e.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&H.logprobs&&Z.push(H.logprobs),O.push({type:"text",text:H.text,providerMetadata:{[se]:{itemId:$.id}}});for(const G of H.annotations)G.type==="url_citation"?O.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:It(),url:G.url,title:G.title}):G.type==="file_citation"?O.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:It(),mediaType:"text/plain",title:(g=(u=G.quote)!=null?u:G.filename)!=null?g:"Document",filename:(h=G.filename)!=null?h:G.file_id,...G.file_id?{providerMetadata:{[se]:{fileId:G.file_id}}}:{}}):G.type==="container_file_citation"?O.push({type:"source",sourceType:"document",id:(w=(p=(d=this.config).generateId)==null?void 0:p.call(d))!=null?w:It(),mediaType:"text/plain",title:(y=(m=G.filename)!=null?m:G.file_id)!=null?y:"Document",filename:(_=G.filename)!=null?_:G.file_id,providerMetadata:{[se]:{fileId:G.file_id,containerId:G.container_id,...G.index!=null?{index:G.index}:{}}}}):G.type==="file_path"&&O.push({type:"source",sourceType:"document",id:(k=(b=(f=this.config).generateId)==null?void 0:b.call(f))!=null?k:It(),mediaType:"application/octet-stream",title:G.file_id,filename:G.file_id,providerMetadata:{[se]:{fileId:G.file_id,...G.index!=null?{index:G.index}:{}}}})}break}case"function_call":{j=!0,O.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[se]:{itemId:$.id}}});break}case"web_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:te??"web_search",input:JSON.stringify({}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:te??"web_search",result:Vf($.action),providerExecuted:!0});break}case"computer_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(C=(S=$.results)==null?void 0:S.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?C:null},providerExecuted:!0});break}case"code_interpreter_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const E={[se]:{...pe.id!=null?{responseId:pe.id}:{}}};Z.length>0&&(E[se].logprobs=Z),typeof pe.service_tier=="string"&&(E[se].serviceTier=pe.service_tier);const R=pe.usage;return{content:O,finishReason:Df({finishReason:(I=pe.incomplete_details)==null?void 0:I.reason,hasFunctionCall:j}),usage:{inputTokens:R.input_tokens,outputTokens:R.output_tokens,totalTokens:R.input_tokens+R.output_tokens,reasoningTokens:(M=(x=R.output_tokens_details)==null?void 0:x.reasoning_tokens)!=null?M:void 0,cachedInputTokens:(U=(P=R.input_tokens_details)==null?void 0:P.cached_tokens)!=null?U:void 0},request:{body:z},response:{id:pe.id,timestamp:new Date(pe.created_at*1e3),modelId:pe.model,headers:ee,body:V},providerMetadata:E,warnings:F}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,store:o}=await this.getArgs(e),{responseHeaders:s,value:a}=await Kt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Zt,successfulResponseHandler:Wi(v7),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=this,l=this.config.provider.replace(".responses","");let c="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},g=[];let h=null;const d={},p=[];let w=!1;const m={};let y;return{stream:a.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,f){var b,k,S,C,I,x,M,P,U,z,F,te,ie,se,ee,pe,V,O,Z,j,E,R;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){c="error",f.enqueue({type:"error",error:_.error});return}const $=_.value;if(Ff($))$.item.type==="function_call"?(d[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},f.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(d[$.output_index]={toolName:n??"web_search",toolCallId:$.item.id},f.enqueue({type:"tool-input-start",id:$.item.id,toolName:n??"web_search",providerExecuted:!0}),f.enqueue({type:"tool-input-end",id:$.item.id}),f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(d[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},f.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(d[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},f.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),f.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(p.splice(0,p.length),f.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id}}})):Ff($)&&$.item.type==="reasoning"&&(m[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},f.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(S7($)){if($.item.type==="message")f.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id,...p.length>0&&{annotations:p}}}});else if($.item.type==="function_call")d[$.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:$.item.call_id}),f.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")d[$.output_index]=void 0,f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:n??"web_search",result:Vf($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")d[$.output_index]=void 0,f.enqueue({type:"tool-input-end",id:$.item.id}),f.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")d[$.output_index]=void 0,f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(S=(k=$.item.results)==null?void 0:k.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?S:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")d[$.output_index]=void 0,f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")f.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")d[$.output_index]=void 0,f.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const H=m[$.item.id],G=Object.entries(H.summaryParts).filter(([fe,ae])=>ae==="active"||ae==="can-conclude").map(([fe])=>fe);for(const fe of G)f.enqueue({type:"reasoning-end",id:`${$.item.id}:${fe}`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(C=$.item.encrypted_content)!=null?C:null}}});delete m[$.item.id]}}else if($7($)){const H=d[$.output_index];H!=null&&f.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:$.delta})}else if(E7($)){const H=d[$.output_index];H!=null&&f.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(I7($)){const H=d[$.output_index];H!=null&&(f.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:'"}'}),f.enqueue({type:"tool-input-end",id:H.toolCallId}),f.enqueue({type:"tool-call",toolCallId:H.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:H.codeInterpreter.containerId}),providerExecuted:!0}))}else if(T7($))h=$.response.id,f.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(k7($))f.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(x=(I=e.providerOptions)==null?void 0:I.openai)!=null&&x.logprobs&&$.logprobs&&g.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const H=m[$.item_id];H.summaryParts[$.summary_index]="active";for(const G of Object.keys(H.summaryParts))H.summaryParts[G]==="can-conclude"&&(f.enqueue({type:"reasoning-end",id:`${$.item_id}:${G}`,providerMetadata:{[l]:{itemId:$.item_id}}}),H.summaryParts[G]="concluded");f.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id,reasoningEncryptedContent:(P=(M=m[$.item_id])==null?void 0:M.encryptedContent)!=null?P:null}}})}}else $.type==="response.reasoning_summary_text.delta"?f.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[l]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?o?(f.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id}}}),m[$.item_id].summaryParts[$.summary_index]="concluded"):m[$.item_id].summaryParts[$.summary_index]="can-conclude":C7($)?(c=Df({finishReason:(U=$.response.incomplete_details)==null?void 0:U.reason,hasFunctionCall:w}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(F=(z=$.response.usage.output_tokens_details)==null?void 0:z.reasoning_tokens)!=null?F:void 0,u.cachedInputTokens=(ie=(te=$.response.usage.input_tokens_details)==null?void 0:te.cached_tokens)!=null?ie:void 0,typeof $.response.service_tier=="string"&&(y=$.response.service_tier)):x7($)?(p.push($.annotation),$.annotation.type==="url_citation"?f.enqueue({type:"source",sourceType:"url",id:(pe=(ee=(se=i.config).generateId)==null?void 0:ee.call(se))!=null?pe:It(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&f.enqueue({type:"source",sourceType:"document",id:(Z=(O=(V=i.config).generateId)==null?void 0:O.call(V))!=null?Z:It(),mediaType:"text/plain",title:(E=(j=$.annotation.quote)!=null?j:$.annotation.filename)!=null?E:"Document",filename:(R=$.annotation.filename)!=null?R:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[l]:{fileId:$.annotation.file_id}}}:{}})):R7($)&&f.enqueue({type:"error",error:$})},flush(_){const f={[l]:{responseId:h}};g.length>0&&(f[l].logprobs=g),y!==void 0&&(f[l].serviceTier=y),_.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:f})}})),request:{body:t},response:{headers:s}}}};function k7(e){return e.type==="response.output_text.delta"}function S7(e){return e.type==="response.output_item.done"}function C7(e){return e.type==="response.completed"||e.type==="response.incomplete"}function T7(e){return e.type==="response.created"}function $7(e){return e.type==="response.function_call_arguments.delta"}function E7(e){return e.type==="response.code_interpreter_call_code.delta"}function I7(e){return e.type==="response.code_interpreter_call_code.done"}function Ff(e){return e.type==="response.output_item.added"}function x7(e){return e.type==="response.output_text.annotation.added"}function R7(e){return e.type==="error"}function Vf(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}}}}var P7=rt(()=>Ce(T({instructions:v().nullish(),speed:q().min(.25).max(4).default(1).nullish()}))),O7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await pr({provider:"openai",providerOptions:a,schema:P7}),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-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const g in u){const h=u[g];h!==void 0&&(c[g]=h)}}return s&&i.push({type:"unsupported-setting",setting:"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 Kt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:s,failedResponseHandler:Zt,successfulResponseHandler:P5(),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}}}},M7=rt(()=>Ce(T({text:v(),language:v().nullish(),duration:q().nullish(),words:A(T({word:v(),start:q(),end:q()})).nullish(),segments:A(T({id:q(),seek:q(),start:q(),end:q(),text:v(),tokens:A(q()),temperature:q(),avg_logprob:q(),compression_ratio:q(),no_speech_prob:q()})).nullish()}))),N7=rt(()=>Ce(T({include:A(v()).optional(),language:v().optional(),prompt:v().optional(),temperature:q().min(0).max(1).default(0).optional(),timestampGranularities:A(_e(["word","segment"])).default(["segment"]).optional()}))),Hf={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"},A7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await pr({provider:"openai",providerOptions:r,schema:N7}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([T8(e)]);s.append("model",this.modelId);const i=_5(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:h,responseHeaders:d,rawValue:p}=await x5({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Zt,successfulResponseHandler:sn(M7),abortSignal:e.abortSignal,fetch:this.config.fetch}),w=h.language!=null&&h.language in Hf?Hf[h.language]:void 0;return{text:h.text,segments:(i=(a=(o=h.segments)==null?void 0:o.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?a:(s=h.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:w,durationInSeconds:(l=h.duration)!=null?l:void 0,warnings:g,response:{timestamp:c,modelId:this.modelId,headers:d,body:p}}}},q7="2.0.88";function Bf(e={}){var t,r;const n=(t=E8(v5({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>yf({Authorization:`Bearer ${g5({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${q7}`),a=w=>new M8(w,{provider:`${o}.chat`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),i=w=>new L8(w,{provider:`${o}.completion`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),l=w=>new z8(w,{provider:`${o}.embedding`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),c=w=>new V8(w,{provider:`${o}.image`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),u=w=>new A7(w,{provider:`${o}.transcription`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),g=w=>new O7(w,{provider:`${o}.speech`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),h=w=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(w)},d=w=>new b7(w,{provider:`${o}.responses`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(w){return h(w)};return p.languageModel=h,p.chat=a,p.completion=i,p.responses=d,p.embedding=l,p.textEmbedding=l,p.textEmbeddingModel=l,p.image=c,p.imageModel=c,p.transcription=u,p.transcriptionModel=u,p.speech=g,p.speechModel=g,p.tools=h7,p}Bf();function Wn(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function L7(e){const t=[];for(const{role:r,content:n,...o}of e){const s=Wn({...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,...Wn(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=Wn(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,${Jy(a.data)}`},...i}}else throw new Ct({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=Wn(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=Wn(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 Jf({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 Gf(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 tl=T({user:v().optional(),reasoningEffort:v().optional(),textVerbosity:v().optional()}),j7=T({error:T({message:v(),type:v().nullish(),param:et().nullish(),code:ne([v(),q()]).nullish()})}),U7={errorSchema:j7,errorToMessage:e=>e.error.message};function z7({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 Ct({functionality:`tool choice type: ${s}`})}}}var D7=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:U7;this.chunkSchema=F7(o.errorSchema),this.failedResponseHandler=$r(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:h}){var d,p,w,m;const y=[],_=Object.assign((d=await ed({provider:"openai-compatible",providerOptions:i,schema:tl}))!=null?d:{},(p=await ed({provider:this.providerOptionsName,providerOptions:i,schema:tl}))!=null?p:{});o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:f,toolChoice:b,toolWarnings:k}=z7({tools:h,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(([S])=>!Object.keys(tl.shape).includes(S))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:L7(e),tools:f,tool_choice:b},warnings:[...y,...k]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,g,h,d,p,w,m,y;const{args:_,warnings:f}=await this.getArgs({...e}),b=JSON.stringify(_),{responseHeaders:k,value:S,rawValue:C}=await Jr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Hr(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Gr(Z7),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=S.choices[0],x=[],M=I.message.content;M!=null&&M.length>0&&x.push({type:"text",text:M});const P=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(P!=null&&P.length>0&&x.push({type:"reasoning",text:P}),I.message.tool_calls!=null)for(const F of I.message.tool_calls)x.push({type:"tool-call",toolCallId:(r=F.id)!=null?r:In(),toolName:F.function.name,input:F.function.arguments});const U={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:C}))},z=(s=S.usage)==null?void 0:s.completion_tokens_details;return z?.accepted_prediction_tokens!=null&&(U[this.providerOptionsName].acceptedPredictionTokens=z?.accepted_prediction_tokens),z?.rejected_prediction_tokens!=null&&(U[this.providerOptionsName].rejectedPredictionTokens=z?.rejected_prediction_tokens),{content:x,finishReason:Gf(I.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=S.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(g=(u=S.usage)==null?void 0:u.total_tokens)!=null?g:void 0,reasoningTokens:(p=(d=(h=S.usage)==null?void 0:h.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(y=(m=(w=S.usage)==null?void 0:w.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?y:void 0},providerMetadata:U,request:{body:b},response:{...Jf(S),headers:k,body:C},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 Jr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Hr(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:rd(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 h=this.providerOptionsName;let d=!1,p=!1;return{stream:i.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,m){var y,_,f,b,k,S,C,I,x,M,P,U,z;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",m.enqueue({type:"error",error:w.error});return}const F=w.value;if(s?.processChunk(w.rawValue),"error"in F){c="error",m.enqueue({type:"error",error:F.error.message});return}if(g&&(g=!1,m.enqueue({type:"response-metadata",...Jf(F)})),F.usage!=null){const{prompt_tokens:ee,completion_tokens:pe,total_tokens:V,prompt_tokens_details:O,completion_tokens_details:Z}=F.usage;u.promptTokens=ee??void 0,u.completionTokens=pe??void 0,u.totalTokens=V??void 0,Z?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=Z?.reasoning_tokens),Z?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=Z?.accepted_prediction_tokens),Z?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=Z?.rejected_prediction_tokens),O?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=O?.cached_tokens)}const te=F.choices[0];if(te?.finish_reason!=null&&(c=Gf(te.finish_reason)),te?.delta==null)return;const ie=te.delta,se=(y=ie.reasoning_content)!=null?y:ie.reasoning;if(se&&(d||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:se})),ie.content&&(p||(m.enqueue({type:"text-start",id:"txt-0"}),p=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:ie.content})),ie.tool_calls!=null)for(const ee of ie.tool_calls){const pe=ee.index;if(l[pe]==null){if(ee.id==null)throw new _n({data:ee,message:"Expected 'id' to be a string."});if(((_=ee.function)==null?void 0:_.name)==null)throw new _n({data:ee,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:ee.id,toolName:ee.function.name}),l[pe]={id:ee.id,type:"function",function:{name:ee.function.name,arguments:(f=ee.function.arguments)!=null?f:""},hasFinished:!1};const O=l[pe];((b=O.function)==null?void 0:b.name)!=null&&((k=O.function)==null?void 0:k.arguments)!=null&&(O.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:O.id,delta:O.function.arguments}),Xu(O.function.arguments)&&(m.enqueue({type:"tool-input-end",id:O.id}),m.enqueue({type:"tool-call",toolCallId:(S=O.id)!=null?S:In(),toolName:O.function.name,input:O.function.arguments}),O.hasFinished=!0));continue}const V=l[pe];V.hasFinished||(((C=ee.function)==null?void 0:C.arguments)!=null&&(V.function.arguments+=(x=(I=ee.function)==null?void 0:I.arguments)!=null?x:""),m.enqueue({type:"tool-input-delta",id:V.id,delta:(M=ee.function.arguments)!=null?M:""}),((P=V.function)==null?void 0:P.name)!=null&&((U=V.function)==null?void 0:U.arguments)!=null&&Xu(V.function.arguments)&&(m.enqueue({type:"tool-input-end",id:V.id}),m.enqueue({type:"tool-call",toolCallId:(z=V.id)!=null?z:In(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(w){var m,y,_,f,b,k;d&&w.enqueue({type:"reasoning-end",id:"reasoning-0"}),p&&w.enqueue({type:"text-end",id:"txt-0"});for(const C of l.filter(I=>!I.hasFinished))w.enqueue({type:"tool-input-end",id:C.id}),w.enqueue({type:"tool-call",toolCallId:(m=C.id)!=null?m:In(),toolName:C.function.name,input:C.function.arguments});const S={[h]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(S[h].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(S[h].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),w.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(y=u.promptTokens)!=null?y:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(f=u.totalTokens)!=null?f:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:S})}})),request:{body:o},response:{headers:a}}}},Wf=T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish(),Z7=T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({message:T({role:L("assistant").nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:A(T({id:v().nullish(),function:T({name:v(),arguments:v()})})).nullish()}),finish_reason:v().nullish()})),usage:Wf}),F7=e=>ne([T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({delta:T({role:_e(["assistant"]).nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:A(T({index:q(),id:v().nullish(),function:T({name:v().nullish(),arguments:v().nullish()})})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:Wf}),e]);T({echo:ce().optional(),logitBias:ve(v(),q()).optional(),suffix:v().optional(),user:v().optional()});var V7=T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()});T({id:v().nullish(),created:q().nullish(),model:v().nullish(),choices:A(T({text:v(),finish_reason:v()})),usage:V7.nullish()}),T({dimensions:q().optional(),user:v().optional()}),T({data:A(T({embedding:A(q())})),usage:T({prompt_tokens:q()}).nullish(),providerMetadata:ve(v(),ve(v(),et())).optional()}),T({data:A(T({b64_json:v()}))});var Kf=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}}},H7={extractMetadata:async({parsedBody:e})=>{const t=await Tt({value:e,schema:B7});return!t.success||t.value.usage==null?void 0:Kf(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Tt({value:t,schema:J7});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:()=>Kf(e)}}},Yf=T({prompt_cache_hit_tokens:q().nullish(),prompt_cache_miss_tokens:q().nullish()}),B7=T({usage:Yf.nullish()}),J7=T({choices:A(T({finish_reason:v().nullish()})).nullish(),usage:Yf.nullish()}),G7="1.0.30";function Qf(e={}){var t;const r=cd((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>cr({Authorization:`Bearer ${Z_({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${G7}`);class o extends D7{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const h=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:h}}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:H7}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new Oc({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Oc({modelId:i,modelType:"imageModel"})},a}Qf();const W7=(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})},K7=(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 Y7{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=K7("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Or.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];W7("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 es(e){return!!e._zod}function fr(e,t){return es(e)?Qc(e,t):e.safeParse(t)}function Xf(e){var t,r;if(!e)return;let n;if(es(e)?n=(r=(t=e._zod)===null||t===void 0?void 0:t.def)===null||r===void 0?void 0:r.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function Q7(e){var t;if(es(e)){const a=(t=e._zod)===null||t===void 0?void 0:t.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const o=e.value;if(o!==void 0)return o}function Ar(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function eh(e){const t=Xf(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Q7(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function th(e,t){const r=fr(e,t);if(!r.success)throw r.error;return r.data}const X7=6e4;class ek{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(di,r=>{this._oncancel(r)}),this.setNotificationHandler(fi,r=>{this._onprogress(r)}),this.setRequestHandler(pi,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(hi,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new de(ge.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(gi,async(r,n)=>{const o=async()=>{var s;const a=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(l.type==="response"||l.type==="error"){const c=l.message,u=c.id,g=this._requestResolvers.get(u);if(g)if(this._requestResolvers.delete(u),l.type==="response")g(c);else{const h=c,d=new de(h.error.code,h.error.message,h.error.data);g(d)}else{const h=l.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${u}`))}continue}await((s=this._transport)===null||s===void 0?void 0:s.send(l.message,{relatedRequestId:n.requestId}))}}const i=await this._taskStore.getTask(a,n.sessionId);if(!i)throw new de(ge.InvalidParams,`Task not found: ${a}`);if(!Ar(i.status))return await this._waitForTaskUpdate(a,n.signal),await o();if(Ar(i.status)){const l=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...l,_meta:{...l._meta,[Wt]:{taskId:a}}}}return await o()};return await o()}),this.setRequestHandler(vi,async(r,n)=>{var o;try{const{tasks:s,nextCursor:a}=await this._taskStore.listTasks((o=r.params)===null||o===void 0?void 0:o.cursor,n.sessionId);return{tasks:s,nextCursor:a,_meta:{}}}catch(s){throw new de(ge.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler($4,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new de(ge.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ar(o.status))throw new de(ge.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 de(ge.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof de?o:new de(ge.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){const r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.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),de.fromError(ge.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){var r,n,o;this._transport=t;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};const a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=l=>{a?.(l),this._onerror(l)};const i=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(l,c)=>{i?.(l,c),Dn(l)||u4(l)?this._onresponse(l):ui(l)?this._onrequest(l,c):c4(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var t;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const n=de.fromError(ge.ConnectionClosed,"Connection closed");this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);for(const o of r.values())o(n)}_onerror(t){var r;(r=this.onerror)===null||r===void 0||r.call(this,t)}_onnotification(t){var r;const n=(r=this._notificationHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){var n,o,s,a,i,l;const c=(n=this._requestHandlers.get(t.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,u=this._transport,g=(a=(s=(o=t.params)===null||o===void 0?void 0:o._meta)===null||s===void 0?void 0:s[Wt])===null||a===void 0?void 0:a.taskId;if(c===void 0){const m={jsonrpc:"2.0",id:t.id,error:{code:ge.MethodNotFound,message:"Method not found"}};g&&this._taskMessageQueue?this._enqueueTaskMessage(g,{type:"error",message:m,timestamp:Date.now()},u?.sessionId).catch(y=>this._onerror(new Error(`Failed to enqueue error response: ${y}`))):u?.send(m).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)));return}const h=new AbortController;this._requestHandlerAbortControllers.set(t.id,h);const d=(i=t.params)===null||i===void 0?void 0:i.task,p=this._taskStore?this.requestTaskStore(t,u?.sessionId):void 0,w={signal:h.signal,sessionId:u?.sessionId,_meta:(l=t.params)===null||l===void 0?void 0:l._meta,sendNotification:async m=>{const y={relatedRequestId:t.id};g&&(y.relatedTask={taskId:g}),await this.notification(m,y)},sendRequest:async(m,y,_)=>{var f,b;const k={..._,relatedRequestId:t.id};g&&!k.relatedTask&&(k.relatedTask={taskId:g});const S=(b=(f=k.relatedTask)===null||f===void 0?void 0:f.taskId)!==null&&b!==void 0?b:g;return S&&p&&await p.updateTaskStatus(S,"input_required"),await this.request(m,y,k)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:g,taskStore:p,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{d&&this.assertTaskHandlerCapability(t.method)}).then(()=>c(t,w)).then(async m=>{if(h.signal.aborted)return;const y={result:m,jsonrpc:"2.0",id:t.id};g&&this._taskMessageQueue?await this._enqueueTaskMessage(g,{type:"response",message:y,timestamp:Date.now()},u?.sessionId):await u?.send(y)},async m=>{var y;if(h.signal.aborted)return;const _={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(m.code)?m.code:ge.InternalError,message:(y=m.message)!==null&&y!==void 0?y:"Internal error",...m.data!==void 0&&{data:m.data}}};g&&this._taskMessageQueue?await this._enqueueTaskMessage(g,{type:"error",message:_,timestamp:Date.now()},u?.sessionId):await u?.send(_)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).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),Dn(t))n(t);else{const a=new de(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(Dn(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),Dn(t))o(t);else{const a=de.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}async*requestStream(t,r,n){var o,s,a,i;const{task:l}=n??{};if(!l){try{yield{type:"result",result:await this.request(t,r,n)}}catch(u){yield{type:"error",error:u instanceof de?u:new de(ge.InternalError,String(u))}}return}let c;try{const u=await this.request(t,Bn,n);if(u.task)c=u.task.taskId,yield{type:"taskCreated",task:u.task};else throw new de(ge.InternalError,"Task creation did not return a task");for(;;){const g=await this.getTask({taskId:c},n);if(yield{type:"taskStatus",task:g},Ar(g.status)){g.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)}:g.status==="failed"?yield{type:"error",error:new de(ge.InternalError,`Task ${c} failed`)}:g.status==="cancelled"&&(yield{type:"error",error:new de(ge.InternalError,`Task ${c} was cancelled`)});return}if(g.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)};return}const h=(a=(o=g.pollInterval)!==null&&o!==void 0?o:(s=this._options)===null||s===void 0?void 0:s.defaultTaskPollInterval)!==null&&a!==void 0?a:1e3;await new Promise(d=>setTimeout(d,h)),(i=n?.signal)===null||i===void 0||i.throwIfAborted()}}catch(u){yield{type:"error",error:u instanceof de?u:new de(ge.InternalError,String(u))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{var g,h,d,p,w,m,y;const _=x=>{u(x)};if(!this._transport){_(new Error("Not connected"));return}if(((g=this._options)===null||g===void 0?void 0:g.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(x){_(x);return}(h=n?.signal)===null||h===void 0||h.throwIfAborted();const f=this._requestMessageId++,b={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),b.params={...t.params,_meta:{...((d=t.params)===null||d===void 0?void 0:d._meta)||{},progressToken:f}}),i&&(b.params={...b.params,task:i}),l&&(b.params={...b.params,_meta:{...((p=b.params)===null||p===void 0?void 0:p._meta)||{},[Wt]:l}});const k=x=>{var M;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),(M=this._transport)===null||M===void 0||M.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(U=>this._onerror(new Error(`Failed to send cancellation: ${U}`)));const P=x instanceof de?x:new de(ge.RequestTimeout,String(x));u(P)};this._responseHandlers.set(f,x=>{var M;if(!(!((M=n?.signal)===null||M===void 0)&&M.aborted)){if(x instanceof Error)return u(x);try{const P=fr(r,x.result);P.success?c(P.data):u(P.error)}catch(P){u(P)}}}),(w=n?.signal)===null||w===void 0||w.addEventListener("abort",()=>{var x;k((x=n?.signal)===null||x===void 0?void 0:x.reason)});const S=(m=n?.timeout)!==null&&m!==void 0?m:X7,C=()=>k(de.fromError(ge.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(f,S,n?.maxTotalTimeout,C,(y=n?.resetTimeoutOnProgress)!==null&&y!==void 0?y:!1);const I=l?.taskId;if(I){const x=M=>{const P=this._responseHandlers.get(f);P?P(M):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,x),this._enqueueTaskMessage(I,{type:"request",message:b,timestamp:Date.now()}).catch(M=>{this._cleanupTimeout(f),u(M)})}else this._transport.send(b,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(x=>{this._cleanupTimeout(f),u(x)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},mi,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},_i,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},E4,r)}async notification(t,r){var n,o,s,a,i;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const l=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(l){const h={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...((o=t.params)===null||o===void 0?void 0:o._meta)||{},[Wt]:r.relatedTask}}};await this._enqueueTaskMessage(l,{type:"notification",message:h,timestamp:Date.now()});return}if(((a=(s=this._options)===null||s===void 0?void 0:s.debouncedNotificationMethods)!==null&&a!==void 0?a:[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var h,d;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let p={...t,jsonrpc:"2.0"};r?.relatedTask&&(p={...p,params:{...p.params,_meta:{...((h=p.params)===null||h===void 0?void 0:h._meta)||{},[Wt]:r.relatedTask}}}),(d=this._transport)===null||d===void 0||d.send(p,r).catch(w=>this._onerror(w))});return}let g={...t,jsonrpc:"2.0"};r?.relatedTask&&(g={...g,params:{...g.params,_meta:{...((i=g.params)===null||i===void 0?void 0:i._meta)||{},[Wt]:r.relatedTask}}}),await this._transport.send(g,r)}setRequestHandler(t,r){const n=eh(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=th(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=eh(t);this._notificationHandlers.set(n,o=>{const s=th(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){var o;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=(o=this._options)===null||o===void 0?void 0:o.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,s)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&ui(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new de(ge.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){var n,o,s;let a=(o=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&o!==void 0?o:1e3;try{const i=await((s=this._taskStore)===null||s===void 0?void 0:s.getTask(t));i?.pollInterval&&(a=i.pollInterval)}catch{}return new Promise((i,l)=>{if(r.aborted){l(new de(ge.InvalidRequest,"Request cancelled"));return}const c=setTimeout(i,a);r.addEventListener("abort",()=>{clearTimeout(c),l(new de(ge.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 de(ge.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=Fo.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Ar(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 de(ge.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Ar(i.status))throw new de(ge.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=Fo.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Ar(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function rh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tk(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];rh(a)&&rh(s)?r[o]={...a,...s}:r[o]=s}return r}var ts={exports:{}},rl={},Yt={},qr={},nl={},ol={},sl={},nh;function rs(){return nh||(nh=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,b)=>`${f}${b}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((f,b)=>(b instanceof r&&(f[b.str]=(f[b.str]||0)+1),f),{})}}e._Code=n,e.nil=new n("");function o(y,..._){const f=[y[0]];let b=0;for(;b<_.length;)i(f,_[b]),f.push(y[++b]);return new n(f)}e._=o;const s=new n("+");function a(y,..._){const f=[d(y[0])];let b=0;for(;b<_.length;)f.push(s),i(f,_[b]),f.push(s,d(y[++b]));return l(f),new n(f)}e.str=a;function i(y,_){_ instanceof n?y.push(..._._items):_ instanceof r?y.push(_):y.push(g(_))}e.addCodeArg=i;function l(y){let _=1;for(;_<y.length-1;){if(y[_]===s){const f=c(y[_-1],y[_+1]);if(f!==void 0){y.splice(_-1,3,f);continue}y[_++]="+"}_++}}function c(y,_){if(_==='""')return y;if(y==='""')return _;if(typeof y=="string")return _ instanceof r||y[y.length-1]!=='"'?void 0:typeof _!="string"?`${y.slice(0,-1)}${_}"`:_[0]==='"'?y.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(y instanceof r))return`"${y}${_.slice(1)}`}function u(y,_){return _.emptyStr()?y:y.emptyStr()?_:a`${y}${_}`}e.strConcat=u;function g(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:d(Array.isArray(y)?y.join(","):y)}function h(y){return new n(d(y))}e.stringify=h;function d(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=d;function p(y){return typeof y=="string"&&e.IDENTIFIER.test(y)?new n(`.${y}`):o`[${y}]`}e.getProperty=p;function w(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new n(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=w;function m(y){return new n(y.toString())}e.regexpCode=m})(sl)),sl}var al={},oh;function sh(){return oh||(oh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=rs();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 h=this.toName(c),{prefix:d}=h,p=(g=u.key)!==null&&g!==void 0?g:u.ref;let w=this._values[d];if(w){const _=w.get(p);if(_)return _}else w=this._values[d]=new Map;w.set(p,h);const m=this._scope[d]||(this._scope[d]=[]),y=m.length;return m[y]=u.ref,h.setValue(u,{property:d,itemIndex:y}),h}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,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},u,g)}_reduceValues(c,u,g={},h){let d=t.nil;for(const p in c){const w=c[p];if(!w)continue;const m=g[p]=g[p]||new Map;w.forEach(y=>{if(m.has(y))return;m.set(y,n.Started);let _=u(y);if(_){const f=this.opts.es5?e.varKinds.var:e.varKinds.const;d=(0,t._)`${d}${f} ${y} = ${_};${this.opts._n}`}else if(_=h?.(y))d=(0,t._)`${d}${_}${this.opts._n}`;else throw new r(y);m.set(y,n.Completed)})}return d}}e.ValueScope=i})(al)),al}var ah;function ye(){return ah||(ah=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=rs(),r=sh();var n=rs();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=sh();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,R){return this}}class a extends s{constructor(E,R,$){super(),this.varKind=E,this.name=R,this.rhs=$}render({es5:E,_n:R}){const $=E?r.varKinds.var:this.varKind,H=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${H};`+R}optimizeNames(E,R){if(E[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,E,R)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(E,R,$){super(),this.lhs=E,this.rhs=R,this.sideEffects=$}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,R){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,E,R),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return z(E,this.rhs)}}class l extends i{constructor(E,R,$,H){super(E,$,H),this.op=R}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 g extends s{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class h extends s{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,R){return this.code=F(this.code,E,R),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class d extends s{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((R,$)=>R+$.render(E),"")}optimizeNodes(){const{nodes:E}=this;let R=E.length;for(;R--;){const $=E[R].optimizeNodes();Array.isArray($)?E.splice(R,1,...$):$?E[R]=$:E.splice(R,1)}return E.length>0?this:void 0}optimizeNames(E,R){const{nodes:$}=this;let H=$.length;for(;H--;){const G=$[H];G.optimizeNames(E,R)||(te(E,G.names),$.splice(H,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((E,R)=>U(E,R.names),{})}}class p extends d{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class w extends d{}class m extends p{}m.kind="else";class y extends p{constructor(E,R){super(R),this.condition=E}render(E){let R=`if(${this.condition})`+super.render(E);return this.else&&(R+="else "+this.else.render(E)),R}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let R=this.else;if(R){const $=R.optimizeNodes();R=this.else=Array.isArray($)?new m($):$}if(R)return E===!1?R instanceof y?R:R.nodes:this.nodes.length?this:new y(ie(E),R instanceof y?[R]:R.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,R){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(E,R),!!(super.optimizeNames(E,R)||this.else))return this.condition=F(this.condition,E,R),this}get names(){const E=super.names;return z(E,this.condition),this.else&&U(E,this.else.names),E}}y.kind="if";class _ extends p{}_.kind="for";class f extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iteration=F(this.iteration,E,R),this}get names(){return U(super.names,this.iteration.names)}}class b extends _{constructor(E,R,$,H){super(),this.varKind=E,this.name=R,this.from=$,this.to=H}render(E){const R=E.es5?r.varKinds.var:this.varKind,{name:$,from:H,to:G}=this;return`for(${R} ${$}=${H}; ${$}<${G}; ${$}++)`+super.render(E)}get names(){const E=z(super.names,this.from);return z(E,this.to)}}class k extends _{constructor(E,R,$,H){super(),this.loop=E,this.varKind=R,this.name=$,this.iterable=H}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iterable=F(this.iterable,E,R),this}get names(){return U(super.names,this.iterable.names)}}class S extends p{constructor(E,R,$){super(),this.name=E,this.args=R,this.async=$}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}S.kind="func";class C extends d{render(E){return"return "+super.render(E)}}C.kind="return";class I extends p{render(E){let R="try"+super.render(E);return this.catch&&(R+=this.catch.render(E)),this.finally&&(R+=this.finally.render(E)),R}optimizeNodes(){var E,R;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(E,R){var $,H;return super.optimizeNames(E,R),($=this.catch)===null||$===void 0||$.optimizeNames(E,R),(H=this.finally)===null||H===void 0||H.optimizeNames(E,R),this}get names(){const E=super.names;return this.catch&&U(E,this.catch.names),this.finally&&U(E,this.finally.names),E}}class x extends p{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}x.kind="catch";class M extends p{render(E){return"finally"+super.render(E)}}M.kind="finally";class P{constructor(E,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
72
- `:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,R){const $=this._extScope.value(E,R);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(E,R){return this._extScope.getValue(E,R)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,R,$,H){const G=this._scope.toName(R);return $!==void 0&&H&&(this._constants[G.str]=$),this._leafNode(new a(E,G,$)),G}const(E,R,$){return this._def(r.varKinds.const,E,R,$)}let(E,R,$){return this._def(r.varKinds.let,E,R,$)}var(E,R,$){return this._def(r.varKinds.var,E,R,$)}assign(E,R,$){return this._leafNode(new i(E,R,$))}add(E,R){return this._leafNode(new l(E,e.operators.ADD,R))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new h(E)),this}object(...E){const R=["{"];for(const[$,H]of E)R.length>1&&R.push(","),R.push($),($!==H||this.opts.es5)&&(R.push(":"),(0,t.addCodeArg)(R,H));return R.push("}"),new t._Code(R)}if(E,R,$){if(this._blockNode(new y(E)),R&&$)this.code(R).else().code($).endIf();else if(R)this.code(R).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new y(E))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(y,m)}_for(E,R){return this._blockNode(E),R&&this.code(R).endFor(),this}for(E,R){return this._for(new f(E),R)}forRange(E,R,$,H,G=this.opts.es5?r.varKinds.var:r.varKinds.let){const fe=this._scope.toName(E);return this._for(new b(G,fe,R,$),()=>H(fe))}forOf(E,R,$,H=r.varKinds.const){const G=this._scope.toName(E);if(this.opts.es5){const fe=R instanceof t.Name?R:this.var("_arr",R);return this.forRange("_i",0,(0,t._)`${fe}.length`,ae=>{this.var(G,(0,t._)`${fe}[${ae}]`),$(G)})}return this._for(new k("of",H,G,R),()=>$(G))}forIn(E,R,$,H=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${R})`,$);const G=this._scope.toName(E);return this._for(new k("in",H,G,R),()=>$(G))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const R=new C;if(this._blockNode(R),this.code(E),R.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(E,R,$){if(!R&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const H=new I;if(this._blockNode(H),this.code(E),R){const G=this.name("e");this._currNode=H.catch=new x(G),R(G)}return $&&(this._currNode=H.finally=new M,this.code($)),this._endBlockNode(x,M)}throw(E){return this._leafNode(new g(E))}block(E,R){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(R),this}endBlock(E){const R=this._blockStarts.pop();if(R===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-R;if($<0||E!==void 0&&$!==E)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${E} expected`);return this._nodes.length=R,this}func(E,R=t.nil,$,H){return this._blockNode(new S(E,R,$)),H&&this.code(H).endFunc(),this}endFunc(){return this._endBlockNode(S)}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,R){const $=this._currNode;if($ instanceof E||R&&$ instanceof R)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${R?`${E.kind}/${R.kind}`:E.kind}"`)}_elseNode(E){const R=this._currNode;if(!(R instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=R.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const R=this._nodes;R[R.length-1]=E}}e.CodeGen=P;function U(j,E){for(const R in E)j[R]=(j[R]||0)+(E[R]||0);return j}function z(j,E){return E instanceof t._CodeOrName?U(j,E.names):j}function F(j,E,R){if(j instanceof t.Name)return $(j);if(!H(j))return j;return new t._Code(j._items.reduce((G,fe)=>(fe instanceof t.Name&&(fe=$(fe)),fe instanceof t._Code?G.push(...fe._items):G.push(fe),G),[]));function $(G){const fe=R[G.str];return fe===void 0||E[G.str]!==1?G:(delete E[G.str],fe)}function H(G){return G instanceof t._Code&&G._items.some(fe=>fe instanceof t.Name&&E[fe.str]===1&&R[fe.str]!==void 0)}}function te(j,E){for(const R in E)j[R]=(j[R]||0)-(E[R]||0)}function ie(j){return typeof j=="boolean"||typeof j=="number"||j===null?!j:(0,t._)`!${Z(j)}`}e.not=ie;const se=O(e.operators.AND);function ee(...j){return j.reduce(se)}e.and=ee;const pe=O(e.operators.OR);function V(...j){return j.reduce(pe)}e.or=V;function O(j){return(E,R)=>E===t.nil?R:R===t.nil?E:(0,t._)`${Z(E)} ${j} ${Z(R)}`}function Z(j){return j instanceof t.Name?j:(0,t._)`(${j})`}})(ol)),ol}var we={},ih;function Se(){if(ih)return we;ih=1,Object.defineProperty(we,"__esModule",{value:!0}),we.checkStrictMode=we.getErrorPath=we.Type=we.useFunc=we.setEvaluated=we.evaluatedPropsToName=we.mergeEvaluated=we.eachItem=we.unescapeJsonPointer=we.escapeJsonPointer=we.escapeFragment=we.unescapeFragment=we.schemaRefOrVal=we.schemaHasRulesButRef=we.schemaHasRules=we.checkUnknownRules=we.alwaysValidSchema=we.toHash=void 0;const e=ye(),t=rs();function r(k){const S={};for(const C of k)S[C]=!0;return S}we.toHash=r;function n(k,S){return typeof S=="boolean"?S:Object.keys(S).length===0?!0:(o(k,S),!s(S,k.self.RULES.all))}we.alwaysValidSchema=n;function o(k,S=k.schema){const{opts:C,self:I}=k;if(!C.strictSchema||typeof S=="boolean")return;const x=I.RULES.keywords;for(const M in S)x[M]||b(k,`unknown keyword: "${M}"`)}we.checkUnknownRules=o;function s(k,S){if(typeof k=="boolean")return!k;for(const C in k)if(S[C])return!0;return!1}we.schemaHasRules=s;function a(k,S){if(typeof k=="boolean")return!k;for(const C in k)if(C!=="$ref"&&S.all[C])return!0;return!1}we.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:S},C,I,x){if(!x){if(typeof C=="number"||typeof C=="boolean")return C;if(typeof C=="string")return(0,e._)`${C}`}return(0,e._)`${k}${S}${(0,e.getProperty)(I)}`}we.schemaRefOrVal=i;function l(k){return g(decodeURIComponent(k))}we.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}we.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}we.escapeJsonPointer=u;function g(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}we.unescapeJsonPointer=g;function h(k,S){if(Array.isArray(k))for(const C of k)S(C);else S(k)}we.eachItem=h;function d({mergeNames:k,mergeToName:S,mergeValues:C,resultToName:I}){return(x,M,P,U)=>{const z=P===void 0?M:P instanceof e.Name?(M instanceof e.Name?k(x,M,P):S(x,M,P),P):M instanceof e.Name?(S(x,P,M),M):C(M,P);return U===e.Name&&!(z instanceof e.Name)?I(x,z):z}}we.mergeEvaluated={props:d({mergeNames:(k,S,C)=>k.if((0,e._)`${C} !== true && ${S} !== undefined`,()=>{k.if((0,e._)`${S} === true`,()=>k.assign(C,!0),()=>k.assign(C,(0,e._)`${C} || {}`).code((0,e._)`Object.assign(${C}, ${S})`))}),mergeToName:(k,S,C)=>k.if((0,e._)`${C} !== true`,()=>{S===!0?k.assign(C,!0):(k.assign(C,(0,e._)`${C} || {}`),w(k,C,S))}),mergeValues:(k,S)=>k===!0?!0:{...k,...S},resultToName:p}),items:d({mergeNames:(k,S,C)=>k.if((0,e._)`${C} !== true && ${S} !== undefined`,()=>k.assign(C,(0,e._)`${S} === true ? true : ${C} > ${S} ? ${C} : ${S}`)),mergeToName:(k,S,C)=>k.if((0,e._)`${C} !== true`,()=>k.assign(C,S===!0?!0:(0,e._)`${C} > ${S} ? ${C} : ${S}`)),mergeValues:(k,S)=>k===!0?!0:Math.max(k,S),resultToName:(k,S)=>k.var("items",S)})};function p(k,S){if(S===!0)return k.var("props",!0);const C=k.var("props",(0,e._)`{}`);return S!==void 0&&w(k,C,S),C}we.evaluatedPropsToName=p;function w(k,S,C){Object.keys(C).forEach(I=>k.assign((0,e._)`${S}${(0,e.getProperty)(I)}`,!0))}we.setEvaluated=w;const m={};function y(k,S){return k.scopeValue("func",{ref:S,code:m[S.code]||(m[S.code]=new t._Code(S.code))})}we.useFunc=y;var _;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(_||(we.Type=_={}));function f(k,S,C){if(k instanceof e.Name){const I=S===_.Num;return C?I?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:I?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return C?(0,e.getProperty)(k).toString():"/"+u(k)}we.getErrorPath=f;function b(k,S,C=k.opts.strictSchema){if(C){if(S=`strict mode: ${S}`,C===!0)throw new Error(S);k.self.logger.warn(S)}}return we.checkStrictMode=b,we}var ns={},lh;function hr(){if(lh)return ns;lh=1,Object.defineProperty(ns,"__esModule",{value:!0});const e=ye(),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 ns.default=t,ns}var ch;function os(){return ch||(ch=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=ye(),r=Se(),n=hr();e.keywordError={message:({keyword:m})=>(0,t.str)`must pass "${m}" keyword validation`},e.keyword$DataError={message:({keyword:m,schemaType:y})=>y?(0,t.str)`"${m}" keyword must be ${y} ($data)`:(0,t.str)`"${m}" keyword is invalid ($data)`};function o(m,y=e.keywordError,_,f){const{it:b}=m,{gen:k,compositeRule:S,allErrors:C}=b,I=g(m,y,_);f??(S||C)?l(k,I):c(b,(0,t._)`[${I}]`)}e.reportError=o;function s(m,y=e.keywordError,_){const{it:f}=m,{gen:b,compositeRule:k,allErrors:S}=f,C=g(m,y,_);l(b,C),k||S||c(f,n.default.vErrors)}e.reportExtraError=s;function a(m,y){m.assign(n.default.errors,y),m.if((0,t._)`${n.default.vErrors} !== null`,()=>m.if(y,()=>m.assign((0,t._)`${n.default.vErrors}.length`,y),()=>m.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:m,keyword:y,schemaValue:_,data:f,errsCount:b,it:k}){if(b===void 0)throw new Error("ajv implementation error");const S=m.name("err");m.forRange("i",b,n.default.errors,C=>{m.const(S,(0,t._)`${n.default.vErrors}[${C}]`),m.if((0,t._)`${S}.instancePath === undefined`,()=>m.assign((0,t._)`${S}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),m.assign((0,t._)`${S}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${y}`),k.opts.verbose&&(m.assign((0,t._)`${S}.schema`,_),m.assign((0,t._)`${S}.data`,f))})}e.extendErrors=i;function l(m,y){const _=m.const("err",y);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,y){const{gen:_,validateName:f,schemaEnv:b}=m;b.$async?_.throw((0,t._)`new ${m.ValidationError}(${y})`):(_.assign((0,t._)`${f}.errors`,y),_.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,y,_){const{createErrors:f}=m.it;return f===!1?(0,t._)`{}`:h(m,y,_)}function h(m,y,_={}){const{gen:f,it:b}=m,k=[d(b,_),p(m,_)];return w(m,y,k),f.object(...k)}function d({errorPath:m},{instancePath:y}){const _=y?(0,t.str)`${m}${(0,r.getErrorPath)(y,r.Type.Str)}`:m;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function p({keyword:m,it:{errSchemaPath:y}},{schemaPath:_,parentSchema:f}){let b=f?y:(0,t.str)`${y}/${m}`;return _&&(b=(0,t.str)`${b}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,b]}function w(m,{params:y,message:_},f){const{keyword:b,data:k,schemaValue:S,it:C}=m,{opts:I,propertyName:x,topSchemaRef:M,schemaPath:P}=C;f.push([u.keyword,b],[u.params,typeof y=="function"?y(m):y||(0,t._)`{}`]),I.messages&&f.push([u.message,typeof _=="function"?_(m):_]),I.verbose&&f.push([u.schema,S],[u.parentSchema,(0,t._)`${M}${P}`],[n.default.data,k]),x&&f.push([u.propertyName,x])}})(nl)),nl}var uh;function rk(){if(uh)return qr;uh=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.boolOrEmptySchema=qr.topBoolOrEmptySchema=void 0;const e=os(),t=ye(),r=hr(),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))}qr.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}qr.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 qr}var Ge={},Lr={},dh;function ph(){if(dh)return Lr;dh=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.getRules=Lr.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)}Lr.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 Lr.getRules=n,Lr}var Qt={},fh;function hh(){if(fh)return Qt;fh=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.shouldUseRule=Qt.shouldUseGroup=Qt.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}Qt.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Qt.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 Qt.shouldUseRule=r,Qt}var mh;function ss(){if(mh)return Ge;mh=1,Object.defineProperty(Ge,"__esModule",{value:!0}),Ge.reportTypeError=Ge.checkDataTypes=Ge.checkDataType=Ge.coerceAndCheckDataType=Ge.getJSONTypes=Ge.getSchemaTypes=Ge.DataType=void 0;const e=ph(),t=hh(),r=os(),n=ye(),o=Se();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||(Ge.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}Ge.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(","))}Ge.getJSONTypes=i;function l(_,f){const{gen:b,data:k,opts:S}=_,C=u(f,S.coerceTypes),I=f.length>0&&!(C.length===0&&f.length===1&&(0,t.schemaHasRulesForType)(_,f[0]));if(I){const x=p(f,k,S.strictNumbers,s.Wrong);b.if(x,()=>{C.length?g(_,f,C):m(_)})}return I}Ge.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,f){return f?_.filter(b=>c.has(b)||f==="array"&&b==="array"):[]}function g(_,f,b){const{gen:k,data:S,opts:C}=_,I=k.let("dataType",(0,n._)`typeof ${S}`),x=k.let("coerced",(0,n._)`undefined`);C.coerceTypes==="array"&&k.if((0,n._)`${I} == 'object' && Array.isArray(${S}) && ${S}.length == 1`,()=>k.assign(S,(0,n._)`${S}[0]`).assign(I,(0,n._)`typeof ${S}`).if(p(f,S,C.strictNumbers),()=>k.assign(x,S))),k.if((0,n._)`${x} !== undefined`);for(const P of b)(c.has(P)||P==="array"&&C.coerceTypes==="array")&&M(P);k.else(),m(_),k.endIf(),k.if((0,n._)`${x} !== undefined`,()=>{k.assign(S,x),h(_,x)});function M(P){switch(P){case"string":k.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(x,(0,n._)`"" + ${S}`).elseIf((0,n._)`${S} === null`).assign(x,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${I} == "boolean" || ${S} === null
73
- || (${I} == "string" && ${S} && ${S} == +${S})`).assign(x,(0,n._)`+${S}`);return;case"integer":k.elseIf((0,n._)`${I} === "boolean" || ${S} === null
74
- || (${I} === "string" && ${S} && ${S} == +${S} && !(${S} % 1))`).assign(x,(0,n._)`+${S}`);return;case"boolean":k.elseIf((0,n._)`${S} === "false" || ${S} === 0 || ${S} === null`).assign(x,!1).elseIf((0,n._)`${S} === "true" || ${S} === 1`).assign(x,!0);return;case"null":k.elseIf((0,n._)`${S} === "" || ${S} === 0 || ${S} === false`),k.assign(x,null);return;case"array":k.elseIf((0,n._)`${I} === "string" || ${I} === "number"
75
- || ${I} === "boolean" || ${S} === null`).assign(x,(0,n._)`[${S}]`)}}}function h({gen:_,parentData:f,parentDataProperty:b},k){_.if((0,n._)`${f} !== undefined`,()=>_.assign((0,n._)`${f}[${b}]`,k))}function d(_,f,b,k=s.Correct){const S=k===s.Correct?n.operators.EQ:n.operators.NEQ;let C;switch(_){case"null":return(0,n._)`${f} ${S} null`;case"array":C=(0,n._)`Array.isArray(${f})`;break;case"object":C=(0,n._)`${f} && typeof ${f} == "object" && !Array.isArray(${f})`;break;case"integer":C=I((0,n._)`!(${f} % 1) && !isNaN(${f})`);break;case"number":C=I();break;default:return(0,n._)`typeof ${f} ${S} ${_}`}return k===s.Correct?C:(0,n.not)(C);function I(x=n.nil){return(0,n.and)((0,n._)`typeof ${f} == "number"`,x,b?(0,n._)`isFinite(${f})`:n.nil)}}Ge.checkDataType=d;function p(_,f,b,k){if(_.length===1)return d(_[0],f,b,k);let S;const C=(0,o.toHash)(_);if(C.array&&C.object){const I=(0,n._)`typeof ${f} != "object"`;S=C.null?I:(0,n._)`!${f} || ${I}`,delete C.null,delete C.array,delete C.object}else S=n.nil;C.number&&delete C.integer;for(const I in C)S=(0,n.and)(S,d(I,f,b,k));return S}Ge.checkDataTypes=p;const w={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:f})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${f}}`};function m(_){const f=y(_);(0,r.reportError)(f,w)}Ge.reportTypeError=m;function y(_){const{gen:f,data:b,schema:k}=_,S=(0,o.schemaRefOrVal)(_,k,"type");return{gen:f,keyword:"type",data:b,schema:k.type,schemaCode:S,schemaValue:S,parentSchema:k,params:{},it:_}}return Ge}var Kn={},gh;function nk(){if(gh)return Kn;gh=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.assignDefaults=void 0;const e=ye(),t=Se();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))}Kn.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 h=(0,e._)`${g} === undefined`;u.useDefaults==="empty"&&(h=(0,e._)`${h} || ${g} === null || ${g} === ""`),i.if(h,(0,e._)`${g} = ${(0,e.stringify)(a)}`)}return Kn}var Pt={},Re={},vh;function Ot(){if(vh)return Re;vh=1,Object.defineProperty(Re,"__esModule",{value:!0}),Re.validateUnion=Re.validateArray=Re.usePattern=Re.callValidateCode=Re.schemaProperties=Re.allSchemaProperties=Re.noPropertyInData=Re.propertyInData=Re.isOwnProperty=Re.hasPropFunc=Re.reportMissingProp=Re.checkMissingProp=Re.checkReportMissingProp=void 0;const e=ye(),t=Se(),r=hr(),n=Se();function o(_,f){const{gen:b,data:k,it:S}=_;b.if(u(b,k,f,S.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${f}`},!0),_.error()})}Re.checkReportMissingProp=o;function s({gen:_,data:f,it:{opts:b}},k,S){return(0,e.or)(...k.map(C=>(0,e.and)(u(_,f,C,b.ownProperties),(0,e._)`${S} = ${C}`)))}Re.checkMissingProp=s;function a(_,f){_.setParams({missingProperty:f},!0),_.error()}Re.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Re.hasPropFunc=i;function l(_,f,b){return(0,e._)`${i(_)}.call(${f}, ${b})`}Re.isOwnProperty=l;function c(_,f,b,k){const S=(0,e._)`${f}${(0,e.getProperty)(b)} !== undefined`;return k?(0,e._)`${S} && ${l(_,f,b)}`:S}Re.propertyInData=c;function u(_,f,b,k){const S=(0,e._)`${f}${(0,e.getProperty)(b)} === undefined`;return k?(0,e.or)(S,(0,e.not)(l(_,f,b))):S}Re.noPropertyInData=u;function g(_){return _?Object.keys(_).filter(f=>f!=="__proto__"):[]}Re.allSchemaProperties=g;function h(_,f){return g(f).filter(b=>!(0,t.alwaysValidSchema)(_,f[b]))}Re.schemaProperties=h;function d({schemaCode:_,data:f,it:{gen:b,topSchemaRef:k,schemaPath:S,errorPath:C},it:I},x,M,P){const U=P?(0,e._)`${_}, ${f}, ${k}${S}`:f,z=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,C)],[r.default.parentData,I.parentData],[r.default.parentDataProperty,I.parentDataProperty],[r.default.rootData,r.default.rootData]];I.opts.dynamicRef&&z.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const F=(0,e._)`${U}, ${b.object(...z)}`;return M!==e.nil?(0,e._)`${x}.call(${M}, ${F})`:(0,e._)`${x}(${F})`}Re.callValidateCode=d;const p=(0,e._)`new RegExp`;function w({gen:_,it:{opts:f}},b){const k=f.unicodeRegExp?"u":"",{regExp:S}=f.code,C=S(b,k);return _.scopeValue("pattern",{key:C.toString(),ref:C,code:(0,e._)`${S.code==="new RegExp"?p:(0,n.useFunc)(_,S)}(${b}, ${k})`})}Re.usePattern=w;function m(_){const{gen:f,data:b,keyword:k,it:S}=_,C=f.name("valid");if(S.allErrors){const x=f.let("valid",!0);return I(()=>f.assign(x,!1)),x}return f.var(C,!0),I(()=>f.break()),C;function I(x){const M=f.const("len",(0,e._)`${b}.length`);f.forRange("i",0,M,P=>{_.subschema({keyword:k,dataProp:P,dataPropType:t.Type.Num},C),f.if((0,e.not)(C),x)})}}Re.validateArray=m;function y(_){const{gen:f,schema:b,keyword:k,it:S}=_;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(M=>(0,t.alwaysValidSchema)(S,M))&&!S.opts.unevaluated)return;const I=f.let("valid",!1),x=f.name("_valid");f.block(()=>b.forEach((M,P)=>{const U=_.subschema({keyword:k,schemaProp:P,compositeRule:!0},x);f.assign(I,(0,e._)`${I} || ${x}`),_.mergeValidEvaluated(U,x)||f.if((0,e.not)(I))})),_.result(I,()=>_.reset(),()=>_.error(!0))}return Re.validateUnion=y,Re}var _h;function ok(){if(_h)return Pt;_h=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;const e=ye(),t=hr(),r=Ot(),n=os();function o(h,d){const{gen:p,keyword:w,schema:m,parentSchema:y,it:_}=h,f=d.macro.call(_.self,m,y,_),b=c(p,w,f);_.opts.validateSchema!==!1&&_.self.validateSchema(f,!0);const k=p.name("valid");h.subschema({schema:f,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${w}`,topSchemaRef:b,compositeRule:!0},k),h.pass(k,()=>h.error(!0))}Pt.macroKeywordCode=o;function s(h,d){var p;const{gen:w,keyword:m,schema:y,parentSchema:_,$data:f,it:b}=h;l(b,d);const k=!f&&d.compile?d.compile.call(b.self,y,_,b):d.validate,S=c(w,m,k),C=w.let("valid");h.block$data(C,I),h.ok((p=d.valid)!==null&&p!==void 0?p:C);function I(){if(d.errors===!1)P(),d.modifying&&a(h),U(()=>h.error());else{const z=d.async?x():M();d.modifying&&a(h),U(()=>i(h,z))}}function x(){const z=w.let("ruleErrs",null);return w.try(()=>P((0,e._)`await `),F=>w.assign(C,!1).if((0,e._)`${F} instanceof ${b.ValidationError}`,()=>w.assign(z,(0,e._)`${F}.errors`),()=>w.throw(F))),z}function M(){const z=(0,e._)`${S}.errors`;return w.assign(z,null),P(e.nil),z}function P(z=d.async?(0,e._)`await `:e.nil){const F=b.opts.passContext?t.default.this:t.default.self,te=!("compile"in d&&!f||d.schema===!1);w.assign(C,(0,e._)`${z}${(0,r.callValidateCode)(h,S,F,te)}`,d.modifying)}function U(z){var F;w.if((0,e.not)((F=d.valid)!==null&&F!==void 0?F:C),z)}}Pt.funcKeywordCode=s;function a(h){const{gen:d,data:p,it:w}=h;d.if(w.parentData,()=>d.assign(p,(0,e._)`${w.parentData}[${w.parentDataProperty}]`))}function i(h,d){const{gen:p}=h;p.if((0,e._)`Array.isArray(${d})`,()=>{p.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${d} : ${t.default.vErrors}.concat(${d})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(h)},()=>h.error())}function l({schemaEnv:h},d){if(d.async&&!h.$async)throw new Error("async keyword in sync schema")}function c(h,d,p){if(p===void 0)throw new Error(`keyword "${d}" failed to compile`);return h.scopeValue("keyword",typeof p=="function"?{ref:p}:{ref:p,code:(0,e.stringify)(p)})}function u(h,d,p=!1){return!d.length||d.some(w=>w==="array"?Array.isArray(h):w==="object"?h&&typeof h=="object"&&!Array.isArray(h):typeof h==w||p&&typeof h>"u")}Pt.validSchemaType=u;function g({schema:h,opts:d,self:p,errSchemaPath:w},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");const _=m.dependencies;if(_?.some(f=>!Object.prototype.hasOwnProperty.call(h,f)))throw new Error(`parent schema must have dependencies of ${y}: ${_.join(",")}`);if(m.validateSchema&&!m.validateSchema(h[y])){const b=`keyword "${y}" value is invalid at path "${w}": `+p.errorsText(m.validateSchema.errors);if(d.validateSchema==="log")p.logger.error(b);else throw new Error(b)}}return Pt.validateKeywordUsage=g,Pt}var Xt={},yh;function sk(){if(yh)return Xt;yh=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.extendSubschemaMode=Xt.extendSubschemaData=Xt.getSubschema=void 0;const e=ye(),t=Se();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 h=s.schema[a];return i===void 0?{schema:h,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:h[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')}Xt.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:h}=a;if(i!==void 0){const{errorPath:p,dataPathArr:w,opts:m}=a,y=h.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);d(y),s.errorPath=(0,e.str)`${p}${(0,t.getErrorPath)(i,l,m.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[...w,s.parentDataProperty]}if(c!==void 0){const p=c instanceof e.Name?c:h.let("data",c,!0);d(p),g!==void 0&&(s.propertyName=g)}u&&(s.dataTypes=u);function d(p){s.data=p,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,p]}}Xt.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 Xt.extendSubschemaMode=o,Xt}var ot={},il,wh;function bh(){return wh||(wh=1,il=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}),il}var ll={exports:{}},kh;function ak(){if(kh)return ll.exports;kh=1;var e=ll.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,h){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,g,h);for(var d in a){var p=a[d];if(Array.isArray(p)){if(d in e.arrayKeywords)for(var w=0;w<p.length;w++)t(n,o,s,p[w],i+"/"+d+"/"+w,l,i,d,a,w)}else if(d in e.propsKeywords){if(p&&typeof p=="object")for(var m in p)t(n,o,s,p[m],i+"/"+d+"/"+r(m),l,i,d,a,m)}else(d in e.keywords||n.allKeys&&!(d in e.skipKeywords))&&t(n,o,s,p,i+"/"+d,l,i,d,a)}s(a,i,l,c,u,g,h)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return ll.exports}var Sh;function as(){if(Sh)return ot;Sh=1,Object.defineProperty(ot,"__esModule",{value:!0}),ot.getSchemaRefs=ot.resolveUrl=ot.normalizeId=ot._getFullPath=ot.getFullPath=ot.inlineRef=void 0;const e=Se(),t=bh(),r=ak(),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}ot.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 y=w[m];if(Array.isArray(y)&&y.some(a)||typeof y=="object"&&a(y))return!0}return!1}function i(w){let m=0;for(const y in w){if(y==="$ref")return 1/0;if(m++,!n.has(y)&&(typeof w[y]=="object"&&(0,e.eachItem)(w[y],_=>m+=i(_)),m===1/0))return 1/0}return m}function l(w,m="",y){y!==!1&&(m=g(m));const _=w.parse(m);return c(w,_)}ot.getFullPath=l;function c(w,m){return w.serialize(m).split("#")[0]+"#"}ot._getFullPath=c;const u=/#\/?$/;function g(w){return w?w.replace(u,""):""}ot.normalizeId=g;function h(w,m,y){return y=g(y),w.resolve(m,y)}ot.resolveUrl=h;const d=/^[a-z_][-a-z0-9._]*$/i;function p(w,m){if(typeof w=="boolean")return{};const{schemaId:y,uriResolver:_}=this.opts,f=g(w[y]||m),b={"":f},k=l(_,f,!1),S={},C=new Set;return r(w,{allKeys:!0},(M,P,U,z)=>{if(z===void 0)return;const F=k+P;let te=b[z];typeof M[y]=="string"&&(te=ie.call(this,M[y])),se.call(this,M.$anchor),se.call(this,M.$dynamicAnchor),b[P]=te;function ie(ee){const pe=this.opts.uriResolver.resolve;if(ee=g(te?pe(te,ee):ee),C.has(ee))throw x(ee);C.add(ee);let V=this.refs[ee];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?I(M,V.schema,ee):ee!==g(F)&&(ee[0]==="#"?(I(M,S[ee],ee),S[ee]=M):this.refs[ee]=F),ee}function se(ee){if(typeof ee=="string"){if(!d.test(ee))throw new Error(`invalid anchor "${ee}"`);ie.call(this,`#${ee}`)}}}),S;function I(M,P,U){if(P!==void 0&&!t(M,P))throw x(U)}function x(M){return new Error(`reference "${M}" resolves to more than one schema`)}}return ot.getSchemaRefs=p,ot}var Ch;function is(){if(Ch)return Yt;Ch=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.getData=Yt.KeywordCxt=Yt.validateFunctionCode=void 0;const e=rk(),t=ss(),r=hh(),n=ss(),o=nk(),s=ok(),a=sk(),i=ye(),l=hr(),c=as(),u=Se(),g=os();function h(N){if(k(N)&&(C(N),b(N))){m(N);return}d(N,()=>(0,e.topBoolOrEmptySchema)(N))}Yt.validateFunctionCode=h;function d({gen:N,validateName:D,schema:B,schemaEnv:W,opts:Y},oe){Y.code.es5?N.func(D,(0,i._)`${l.default.data}, ${l.default.valCxt}`,W.$async,()=>{N.code((0,i._)`"use strict"; ${_(B,Y)}`),w(N,Y),N.code(oe)}):N.func(D,(0,i._)`${l.default.data}, ${p(Y)}`,W.$async,()=>N.code(_(B,Y)).code(oe))}function p(N){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${N.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function w(N,D){N.if(l.default.valCxt,()=>{N.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),N.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),N.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),N.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),D.dynamicRef&&N.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{N.var(l.default.instancePath,(0,i._)`""`),N.var(l.default.parentData,(0,i._)`undefined`),N.var(l.default.parentDataProperty,(0,i._)`undefined`),N.var(l.default.rootData,l.default.data),D.dynamicRef&&N.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function m(N){const{schema:D,opts:B,gen:W}=N;d(N,()=>{B.$comment&&D.$comment&&z(N),M(N),W.let(l.default.vErrors,null),W.let(l.default.errors,0),B.unevaluated&&y(N),I(N),F(N)})}function y(N){const{gen:D,validateName:B}=N;N.evaluated=D.const("evaluated",(0,i._)`${B}.evaluated`),D.if((0,i._)`${N.evaluated}.dynamicProps`,()=>D.assign((0,i._)`${N.evaluated}.props`,(0,i._)`undefined`)),D.if((0,i._)`${N.evaluated}.dynamicItems`,()=>D.assign((0,i._)`${N.evaluated}.items`,(0,i._)`undefined`))}function _(N,D){const B=typeof N=="object"&&N[D.schemaId];return B&&(D.code.source||D.code.process)?(0,i._)`/*# sourceURL=${B} */`:i.nil}function f(N,D){if(k(N)&&(C(N),b(N))){S(N,D);return}(0,e.boolOrEmptySchema)(N,D)}function b({schema:N,self:D}){if(typeof N=="boolean")return!N;for(const B in N)if(D.RULES.all[B])return!0;return!1}function k(N){return typeof N.schema!="boolean"}function S(N,D){const{schema:B,gen:W,opts:Y}=N;Y.$comment&&B.$comment&&z(N),P(N),U(N);const oe=W.const("_errs",l.default.errors);I(N,oe),W.var(D,(0,i._)`${oe} === ${l.default.errors}`)}function C(N){(0,u.checkUnknownRules)(N),x(N)}function I(N,D){if(N.opts.jtd)return ie(N,[],!1,D);const B=(0,t.getSchemaTypes)(N.schema),W=(0,t.coerceAndCheckDataType)(N,B);ie(N,B,!W,D)}function x(N){const{schema:D,errSchemaPath:B,opts:W,self:Y}=N;D.$ref&&W.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(D,Y.RULES)&&Y.logger.warn(`$ref: keywords ignored in schema at path "${B}"`)}function M(N){const{schema:D,opts:B}=N;D.default!==void 0&&B.useDefaults&&B.strictSchema&&(0,u.checkStrictMode)(N,"default is ignored in the schema root")}function P(N){const D=N.schema[N.opts.schemaId];D&&(N.baseId=(0,c.resolveUrl)(N.opts.uriResolver,N.baseId,D))}function U(N){if(N.schema.$async&&!N.schemaEnv.$async)throw new Error("async schema in sync schema")}function z({gen:N,schemaEnv:D,schema:B,errSchemaPath:W,opts:Y}){const oe=B.$comment;if(Y.$comment===!0)N.code((0,i._)`${l.default.self}.logger.log(${oe})`);else if(typeof Y.$comment=="function"){const le=(0,i.str)`${W}/$comment`,Ne=N.scopeValue("root",{ref:D.root});N.code((0,i._)`${l.default.self}.opts.$comment(${oe}, ${le}, ${Ne}.schema)`)}}function F(N){const{gen:D,schemaEnv:B,validateName:W,ValidationError:Y,opts:oe}=N;B.$async?D.if((0,i._)`${l.default.errors} === 0`,()=>D.return(l.default.data),()=>D.throw((0,i._)`new ${Y}(${l.default.vErrors})`)):(D.assign((0,i._)`${W}.errors`,l.default.vErrors),oe.unevaluated&&te(N),D.return((0,i._)`${l.default.errors} === 0`))}function te({gen:N,evaluated:D,props:B,items:W}){B instanceof i.Name&&N.assign((0,i._)`${D}.props`,B),W instanceof i.Name&&N.assign((0,i._)`${D}.items`,W)}function ie(N,D,B,W){const{gen:Y,schema:oe,data:le,allErrors:Ne,opts:qe,self:X}=N,{RULES:me}=X;if(oe.$ref&&(qe.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(oe,me))){Y.block(()=>H(N,"$ref",me.all.$ref.definition));return}qe.jtd||ee(N,D),Y.block(()=>{for(const be of me.rules)st(be);st(me.post)});function st(be){(0,r.shouldUseGroup)(oe,be)&&(be.type?(Y.if((0,n.checkDataType)(be.type,le,qe.strictNumbers)),se(N,be),D.length===1&&D[0]===be.type&&B&&(Y.else(),(0,n.reportTypeError)(N)),Y.endIf()):se(N,be),Ne||Y.if((0,i._)`${l.default.errors} === ${W||0}`))}}function se(N,D){const{gen:B,schema:W,opts:{useDefaults:Y}}=N;Y&&(0,o.assignDefaults)(N,D.type),B.block(()=>{for(const oe of D.rules)(0,r.shouldUseRule)(W,oe)&&H(N,oe.keyword,oe.definition,D.type)})}function ee(N,D){N.schemaEnv.meta||!N.opts.strictTypes||(pe(N,D),N.opts.allowUnionTypes||V(N,D),O(N,N.dataTypes))}function pe(N,D){if(D.length){if(!N.dataTypes.length){N.dataTypes=D;return}D.forEach(B=>{j(N.dataTypes,B)||R(N,`type "${B}" not allowed by context "${N.dataTypes.join(",")}"`)}),E(N,D)}}function V(N,D){D.length>1&&!(D.length===2&&D.includes("null"))&&R(N,"use allowUnionTypes to allow union type keyword")}function O(N,D){const B=N.self.RULES.all;for(const W in B){const Y=B[W];if(typeof Y=="object"&&(0,r.shouldUseRule)(N.schema,Y)){const{type:oe}=Y.definition;oe.length&&!oe.some(le=>Z(D,le))&&R(N,`missing type "${oe.join(",")}" for keyword "${W}"`)}}}function Z(N,D){return N.includes(D)||D==="number"&&N.includes("integer")}function j(N,D){return N.includes(D)||D==="integer"&&N.includes("number")}function E(N,D){const B=[];for(const W of N.dataTypes)j(D,W)?B.push(W):D.includes("integer")&&W==="number"&&B.push("integer");N.dataTypes=B}function R(N,D){const B=N.schemaEnv.baseId+N.errSchemaPath;D+=` at "${B}" (strictTypes)`,(0,u.checkStrictMode)(N,D,N.opts.strictTypes)}class ${constructor(D,B,W){if((0,s.validateKeywordUsage)(D,B,W),this.gen=D.gen,this.allErrors=D.allErrors,this.keyword=W,this.data=D.data,this.schema=D.schema[W],this.$data=B.$data&&D.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(D,this.schema,W,this.$data),this.schemaType=B.schemaType,this.parentSchema=D.schema,this.params={},this.it=D,this.def=B,this.$data)this.schemaCode=D.gen.const("vSchema",ae(this.$data,D));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,B.schemaType,B.allowUndefined))throw new Error(`${W} value must be ${JSON.stringify(B.schemaType)}`);("code"in B?B.trackErrors:B.errors!==!1)&&(this.errsCount=D.gen.const("_errs",l.default.errors))}result(D,B,W){this.failResult((0,i.not)(D),B,W)}failResult(D,B,W){this.gen.if(D),W?W():this.error(),B?(this.gen.else(),B(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(D,B){this.failResult((0,i.not)(D),void 0,B)}fail(D){if(D===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(D),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(D){if(!this.$data)return this.fail(D);const{schemaCode:B}=this;this.fail((0,i._)`${B} !== undefined && (${(0,i.or)(this.invalid$data(),D)})`)}error(D,B,W){if(B){this.setParams(B),this._error(D,W),this.setParams({});return}this._error(D,W)}_error(D,B){(D?g.reportExtraError:g.reportError)(this,this.def.error,B)}$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(D){this.allErrors||this.gen.if(D)}setParams(D,B){B?Object.assign(this.params,D):this.params=D}block$data(D,B,W=i.nil){this.gen.block(()=>{this.check$data(D,W),B()})}check$data(D=i.nil,B=i.nil){if(!this.$data)return;const{gen:W,schemaCode:Y,schemaType:oe,def:le}=this;W.if((0,i.or)((0,i._)`${Y} === undefined`,B)),D!==i.nil&&W.assign(D,!0),(oe.length||le.validateSchema)&&(W.elseIf(this.invalid$data()),this.$dataError(),D!==i.nil&&W.assign(D,!1)),W.else()}invalid$data(){const{gen:D,schemaCode:B,schemaType:W,def:Y,it:oe}=this;return(0,i.or)(le(),Ne());function le(){if(W.length){if(!(B instanceof i.Name))throw new Error("ajv implementation error");const qe=Array.isArray(W)?W:[W];return(0,i._)`${(0,n.checkDataTypes)(qe,B,oe.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function Ne(){if(Y.validateSchema){const qe=D.scopeValue("validate$data",{ref:Y.validateSchema});return(0,i._)`!${qe}(${B})`}return i.nil}}subschema(D,B){const W=(0,a.getSubschema)(this.it,D);(0,a.extendSubschemaData)(W,this.it,D),(0,a.extendSubschemaMode)(W,D);const Y={...this.it,...W,items:void 0,props:void 0};return f(Y,B),Y}mergeEvaluated(D,B){const{it:W,gen:Y}=this;W.opts.unevaluated&&(W.props!==!0&&D.props!==void 0&&(W.props=u.mergeEvaluated.props(Y,D.props,W.props,B)),W.items!==!0&&D.items!==void 0&&(W.items=u.mergeEvaluated.items(Y,D.items,W.items,B)))}mergeValidEvaluated(D,B){const{it:W,gen:Y}=this;if(W.opts.unevaluated&&(W.props!==!0||W.items!==!0))return Y.if(B,()=>this.mergeEvaluated(D,i.Name)),!0}}Yt.KeywordCxt=$;function H(N,D,B,W){const Y=new $(N,B,D);"code"in B?B.code(Y,W):Y.$data&&B.validate?(0,s.funcKeywordCode)(Y,B):"macro"in B?(0,s.macroKeywordCode)(Y,B):(B.compile||B.validate)&&(0,s.funcKeywordCode)(Y,B)}const G=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ae(N,{dataLevel:D,dataNames:B,dataPathArr:W}){let Y,oe;if(N==="")return l.default.rootData;if(N[0]==="/"){if(!G.test(N))throw new Error(`Invalid JSON-pointer: ${N}`);Y=N,oe=l.default.rootData}else{const X=fe.exec(N);if(!X)throw new Error(`Invalid JSON-pointer: ${N}`);const me=+X[1];if(Y=X[2],Y==="#"){if(me>=D)throw new Error(qe("property/index",me));return W[D-me]}if(me>D)throw new Error(qe("data",me));if(oe=B[D-me],!Y)return oe}let le=oe;const Ne=Y.split("/");for(const X of Ne)X&&(oe=(0,i._)`${oe}${(0,i.getProperty)((0,u.unescapeJsonPointer)(X))}`,le=(0,i._)`${le} && ${oe}`);return le;function qe(X,me){return`Cannot access ${X} ${me} levels up, current level is ${D}`}}return Yt.getData=ae,Yt}var ls={},Th;function cl(){if(Th)return ls;Th=1,Object.defineProperty(ls,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return ls.default=e,ls}var cs={},$h;function us(){if($h)return cs;$h=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=as();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 cs.default=t,cs}var _t={},Eh;function ul(){if(Eh)return _t;Eh=1,Object.defineProperty(_t,"__esModule",{value:!0}),_t.resolveSchema=_t.getCompilingSchema=_t.resolveRef=_t.compileSchema=_t.SchemaEnv=void 0;const e=ye(),t=cl(),r=hr(),n=as(),o=Se(),s=is();class a{constructor(y){var _;this.refs={},this.dynamicAnchors={};let f;typeof y.schema=="object"&&(f=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(_=y.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(f?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=f?.$async,this.refs={}}}_t.SchemaEnv=a;function i(m){const y=u.call(this,m);if(y)return y;const _=(0,n.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:f,lines:b}=this.opts.code,{ownProperties:k}=this.opts,S=new e.CodeGen(this.scope,{es5:f,lines:b,ownProperties:k});let C;m.$async&&(C=S.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=S.scopeName("validate");m.validateName=I;const x={gen:S,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:S.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,e.stringify)(m.schema)}:{ref:m.schema}),validateName:I,ValidationError:C,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 M;try{this._compilations.add(m),(0,s.validateFunctionCode)(x),S.optimize(this.opts.code.optimize);const P=S.toString();M=`${S.scopeRefs(r.default.scope)}return ${P}`,this.opts.code.process&&(M=this.opts.code.process(M,m));const z=new Function(`${r.default.self}`,`${r.default.scope}`,M)(this,this.scope.get());if(this.scope.value(I,{ref:z}),z.errors=null,z.schema=m.schema,z.schemaEnv=m,m.$async&&(z.$async=!0),this.opts.code.source===!0&&(z.source={validateName:I,validateCode:P,scopeValues:S._values}),this.opts.unevaluated){const{props:F,items:te}=x;z.evaluated={props:F instanceof e.Name?void 0:F,items:te instanceof e.Name?void 0:te,dynamicProps:F instanceof e.Name,dynamicItems:te instanceof e.Name},z.source&&(z.source.evaluated=(0,e.stringify)(z.evaluated))}return m.validate=z,m}catch(P){throw delete m.validate,delete m.validateName,M&&this.logger.error("Error compiling schema, function code:",M),P}finally{this._compilations.delete(m)}}_t.compileSchema=i;function l(m,y,_){var f;_=(0,n.resolveUrl)(this.opts.uriResolver,y,_);const b=m.refs[_];if(b)return b;let k=h.call(this,m,_);if(k===void 0){const S=(f=m.localRefs)===null||f===void 0?void 0:f[_],{schemaId:C}=this.opts;S&&(k=new a({schema:S,schemaId:C,root:m,baseId:y}))}if(k!==void 0)return m.refs[_]=c.call(this,k)}_t.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 y of this._compilations)if(g(y,m))return y}_t.getCompilingSchema=u;function g(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function h(m,y){let _;for(;typeof(_=this.refs[y])=="string";)y=_;return _||this.schemas[y]||d.call(this,m,y)}function d(m,y){const _=this.opts.uriResolver.parse(y),f=(0,n._getFullPath)(this.opts.uriResolver,_);let b=(0,n.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&f===b)return w.call(this,_,m);const k=(0,n.normalizeId)(f),S=this.refs[k]||this.schemas[k];if(typeof S=="string"){const C=d.call(this,m,S);return typeof C?.schema!="object"?void 0:w.call(this,_,C)}if(typeof S?.schema=="object"){if(S.validate||i.call(this,S),k===(0,n.normalizeId)(y)){const{schema:C}=S,{schemaId:I}=this.opts,x=C[I];return x&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,x)),new a({schema:C,schemaId:I,root:m,baseId:b})}return w.call(this,_,S)}}_t.resolveSchema=d;const p=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(m,{baseId:y,schema:_,root:f}){var b;if(((b=m.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const C of m.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const I=_[(0,o.unescapeFragment)(C)];if(I===void 0)return;_=I;const x=typeof _=="object"&&_[this.opts.schemaId];!p.has(C)&&x&&(y=(0,n.resolveUrl)(this.opts.uriResolver,y,x))}let k;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const C=(0,n.resolveUrl)(this.opts.uriResolver,y,_.$ref);k=d.call(this,f,C)}const{schemaId:S}=this.opts;if(k=k||new a({schema:_,schemaId:S,root:f,baseId:y}),k.schema!==k.root.schema)return k}return _t}const ik={$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 ds={},Yn={exports:{}},dl,Ih;function xh(){if(Ih)return dl;Ih=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(h){let d="",p=0,w=0;for(w=0;w<h.length;w++)if(p=h[w].charCodeAt(0),p!==48){if(!(p>=48&&p<=57||p>=65&&p<=70||p>=97&&p<=102))return"";d+=h[w];break}for(w+=1;w<h.length;w++){if(p=h[w].charCodeAt(0),!(p>=48&&p<=57||p>=65&&p<=70||p>=97&&p<=102))return"";d+=h[w]}return d}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(h){return h.length=0,!0}function s(h,d,p){if(h.length){const w=r(h);if(w!=="")d.push(w);else return p.error=!0,!1;h.length=0}return!0}function a(h){let d=0;const p={error:!1,address:"",zone:""},w=[],m=[];let y=!1,_=!1,f=s;for(let b=0;b<h.length;b++){const k=h[b];if(!(k==="["||k==="]"))if(k===":"){if(y===!0&&(_=!0),!f(m,w,p))break;if(++d>7){p.error=!0;break}b>0&&h[b-1]===":"&&(y=!0),w.push(":");continue}else if(k==="%"){if(!f(m,w,p))break;f=o}else{m.push(k);continue}}return m.length&&(f===o?p.zone=m.join(""):_?w.push(m.join("")):w.push(r(m))),p.address=w.join(""),p}function i(h){if(l(h,":")<2)return{host:h,isIPV6:!1};const d=a(h);if(d.error)return{host:h,isIPV6:!1};{let p=d.address,w=d.address;return d.zone&&(p+="%"+d.zone,w+="%25"+d.zone),{host:p,isIPV6:!0,escapedHost:w}}}function l(h,d){let p=0;for(let w=0;w<h.length;w++)h[w]===d&&p++;return p}function c(h){let d=h;const p=[];let w=-1,m=0;for(;m=d.length;){if(m===1){if(d===".")break;if(d==="/"){p.push("/");break}else{p.push(d);break}}else if(m===2){if(d[0]==="."){if(d[1]===".")break;if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&(d[1]==="."||d[1]==="/")){p.push("/");break}}else if(m===3&&d==="/.."){p.length!==0&&p.pop(),p.push("/");break}if(d[0]==="."){if(d[1]==="."){if(d[2]==="/"){d=d.slice(3);continue}}else if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&d[1]==="."){if(d[2]==="/"){d=d.slice(2);continue}else if(d[2]==="."&&d[3]==="/"){d=d.slice(3),p.length!==0&&p.pop();continue}}if((w=d.indexOf("/",1))===-1){p.push(d);break}else p.push(d.slice(0,w)),d=d.slice(w)}return p.join("")}function u(h,d){const p=d!==!0?escape:unescape;return h.scheme!==void 0&&(h.scheme=p(h.scheme)),h.userinfo!==void 0&&(h.userinfo=p(h.userinfo)),h.host!==void 0&&(h.host=p(h.host)),h.path!==void 0&&(h.path=p(h.path)),h.query!==void 0&&(h.query=p(h.query)),h.fragment!==void 0&&(h.fragment=p(h.fragment)),h}function g(h){const d=[];if(h.userinfo!==void 0&&(d.push(h.userinfo),d.push("@")),h.host!==void 0){let p=unescape(h.host);if(!t(p)){const w=i(p);w.isIPV6===!0?p=`[${w.escapedHost}]`:p=h.host}d.push(p)}return(typeof h.port=="number"||typeof h.port=="string")&&(d.push(":"),d.push(String(h.port))),d.length?d.join(""):void 0}return dl={nonSimpleDomain:n,recomposeAuthority:g,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},dl}var pl,Rh;function lk(){if(Rh)return pl;Rh=1;const{isUUID:e}=xh(),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 S=String(k.scheme).toLowerCase()==="https";return(k.port===(S?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[S,C]=k.resourceName.split("?");k.path=S&&S!=="/"?S:void 0,k.query=C,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,S){if(!k.path)return k.error="URN can not be parsed",k;const C=k.path.match(t);if(C){const I=S.scheme||k.scheme||"urn";k.nid=C[1].toLowerCase(),k.nss=C[2];const x=`${I}:${S.nid||k.nid}`,M=b(x);k.path=void 0,M&&(k=M.parse(k,S))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,S){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const C=S.scheme||k.scheme||"urn",I=k.nid.toLowerCase(),x=`${C}:${S.nid||I}`,M=b(x);M&&(k=M.serialize(k,S));const P=k,U=k.nss;return P.path=`${I||S.nid}:${U}`,S.skipEscape=!0,P}function g(k,S){const C=k;return C.uuid=C.nss,C.nss=void 0,!S.tolerant&&(!C.uuid||!e(C.uuid))&&(C.error=C.error||"UUID is not valid."),C}function h(k){const S=k;return S.nss=(k.uuid||"").toLowerCase(),S}const d={scheme:"http",domainHost:!0,parse:s,serialize:a},p={scheme:"https",domainHost:d.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:d,https:p,ws:w,wss:m,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:g,serialize:h,skipNormalize:!0}};Object.setPrototypeOf(f,null);function b(k){return k&&(f[k]||f[k.toLowerCase()])||void 0}return pl={wsIsSecure:o,SCHEMES:f,isValidSchemeName:n,getSchemeHandler:b},pl}var Ph;function ck(){if(Ph)return Yn.exports;Ph=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=xh(),{SCHEMES:a,getSchemeHandler:i}=lk();function l(m,y){return typeof m=="string"?m=h(p(m,y),y):typeof m=="object"&&(m=p(h(m,y),y)),m}function c(m,y,_){const f=_?Object.assign({scheme:"null"},_):{scheme:"null"},b=u(p(m,f),p(y,f),f,!0);return f.skipEscape=!0,h(b,f)}function u(m,y,_,f){const b={};return f||(m=p(h(m,_),_),y=p(h(y,_),_)),_=_||{},!_.tolerant&&y.scheme?(b.scheme=y.scheme,b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=t(y.path||""),b.query=y.query):(y.userinfo!==void 0||y.host!==void 0||y.port!==void 0?(b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=t(y.path||""),b.query=y.query):(y.path?(y.path[0]==="/"?b.path=t(y.path):((m.userinfo!==void 0||m.host!==void 0||m.port!==void 0)&&!m.path?b.path="/"+y.path:m.path?b.path=m.path.slice(0,m.path.lastIndexOf("/")+1)+y.path:b.path=y.path,b.path=t(b.path)),b.query=y.query):(b.path=m.path,y.query!==void 0?b.query=y.query:b.query=m.query),b.userinfo=m.userinfo,b.host=m.host,b.port=m.port),b.scheme=m.scheme),b.fragment=y.fragment,b}function g(m,y,_){return typeof m=="string"?(m=unescape(m),m=h(n(p(m,_),!0),{..._,skipEscape:!0})):typeof m=="object"&&(m=h(n(m,!0),{..._,skipEscape:!0})),typeof y=="string"?(y=unescape(y),y=h(n(p(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=h(n(y,!0),{..._,skipEscape:!0})),m.toLowerCase()===y.toLowerCase()}function h(m,y){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({},y),b=[],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&&b.push(_.scheme,":");const S=r(_);if(S!==void 0&&(f.reference!=="suffix"&&b.push("//"),b.push(S),_.path&&_.path[0]!=="/"&&b.push("/")),_.path!==void 0){let C=_.path;!f.absolutePath&&(!k||!k.absolutePath)&&(C=t(C)),S===void 0&&C[0]==="/"&&C[1]==="/"&&(C="/%2F"+C.slice(2)),b.push(C)}return _.query!==void 0&&b.push("?",_.query),_.fragment!==void 0&&b.push("#",_.fragment),b.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function p(m,y){const _=Object.assign({},y),f={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;_.reference==="suffix"&&(_.scheme?m=_.scheme+":"+m:m="//"+m);const k=m.match(d);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 I=e(f.host);f.host=I.host.toLowerCase(),b=I.isIPV6}else b=!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 S=i(_.scheme||f.scheme);if(!_.unicodeSupport&&(!S||!S.unicodeSupport)&&f.host&&(_.domainHost||S&&S.domainHost)&&b===!1&&s(f.host))try{f.host=URL.domainToASCII(f.host.toLowerCase())}catch(C){f.error=f.error||"Host's domain name can not be converted to ASCII: "+C}(!S||S&&!S.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)))),S&&S.parse&&S.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:h,parse:p};return Yn.exports=w,Yn.exports.default=w,Yn.exports.fastUri=w,Yn.exports}var Oh;function uk(){if(Oh)return ds;Oh=1,Object.defineProperty(ds,"__esModule",{value:!0});const e=ck();return e.code='require("ajv/dist/runtime/uri").default',ds.default=e,ds}var Mh;function dk(){return Mh||(Mh=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=is();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=ye();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=cl(),o=us(),s=ph(),a=ul(),i=ye(),l=as(),c=ss(),u=Se(),g=ik,h=uk(),d=(V,O)=>new RegExp(V,O);d.code="new RegExp";const p=["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."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function f(V){var O,Z,j,E,R,$,H,G,fe,ae,N,D,B,W,Y,oe,le,Ne,qe,X,me,st,be,pt,tr;const ft=V.strict,We=(O=V.code)===null||O===void 0?void 0:O.optimize,St=We===!0||We===void 0?1:We||0,yr=(j=(Z=V.code)===null||Z===void 0?void 0:Z.regExp)!==null&&j!==void 0?j:d,wr=(E=V.uriResolver)!==null&&E!==void 0?E:h.default;return{strictSchema:($=(R=V.strictSchema)!==null&&R!==void 0?R:ft)!==null&&$!==void 0?$:!0,strictNumbers:(G=(H=V.strictNumbers)!==null&&H!==void 0?H:ft)!==null&&G!==void 0?G:!0,strictTypes:(ae=(fe=V.strictTypes)!==null&&fe!==void 0?fe:ft)!==null&&ae!==void 0?ae:"log",strictTuples:(D=(N=V.strictTuples)!==null&&N!==void 0?N:ft)!==null&&D!==void 0?D:"log",strictRequired:(W=(B=V.strictRequired)!==null&&B!==void 0?B:ft)!==null&&W!==void 0?W:!1,code:V.code?{...V.code,optimize:St,regExp:yr}:{optimize:St,regExp:yr},loopRequired:(Y=V.loopRequired)!==null&&Y!==void 0?Y:_,loopEnum:(oe=V.loopEnum)!==null&&oe!==void 0?oe:_,meta:(le=V.meta)!==null&&le!==void 0?le:!0,messages:(Ne=V.messages)!==null&&Ne!==void 0?Ne:!0,inlineRefs:(qe=V.inlineRefs)!==null&&qe!==void 0?qe:!0,schemaId:(X=V.schemaId)!==null&&X!==void 0?X:"$id",addUsedSchema:(me=V.addUsedSchema)!==null&&me!==void 0?me:!0,validateSchema:(st=V.validateSchema)!==null&&st!==void 0?st:!0,validateFormats:(be=V.validateFormats)!==null&&be!==void 0?be:!0,unicodeRegExp:(pt=V.unicodeRegExp)!==null&&pt!==void 0?pt:!0,int32range:(tr=V.int32range)!==null&&tr!==void 0?tr:!0,uriResolver:wr}}class b{constructor(O={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,O=this.opts={...O,...f(O)};const{es5:Z,lines:j}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:w,es5:Z,lines:j}),this.logger=U(O.logger);const E=O.validateFormats;O.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,m,O,"NOT SUPPORTED"),k.call(this,y,O,"DEPRECATED","warn"),this._metaOpts=M.call(this),O.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),O.keywords&&x.call(this,O.keywords),typeof O.meta=="object"&&this.addMetaSchema(O.meta),C.call(this),O.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:O,meta:Z,schemaId:j}=this.opts;let E=g;j==="id"&&(E={...g},E.id=E.$id,delete E.$id),Z&&O&&this.addMetaSchema(E,E[j],!1)}defaultMeta(){const{meta:O,schemaId:Z}=this.opts;return this.opts.defaultMeta=typeof O=="object"?O[Z]||O:void 0}validate(O,Z){let j;if(typeof O=="string"){if(j=this.getSchema(O),!j)throw new Error(`no schema with key or ref "${O}"`)}else j=this.compile(O);const E=j(Z);return"$async"in j||(this.errors=j.errors),E}compile(O,Z){const j=this._addSchema(O,Z);return j.validate||this._compileSchemaEnv(j)}compileAsync(O,Z){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:j}=this.opts;return E.call(this,O,Z);async function E(ae,N){await R.call(this,ae.$schema);const D=this._addSchema(ae,N);return D.validate||$.call(this,D)}async function R(ae){ae&&!this.getSchema(ae)&&await E.call(this,{$ref:ae},!0)}async function $(ae){try{return this._compileSchemaEnv(ae)}catch(N){if(!(N instanceof o.default))throw N;return H.call(this,N),await G.call(this,N.missingSchema),$.call(this,ae)}}function H({missingSchema:ae,missingRef:N}){if(this.refs[ae])throw new Error(`AnySchema ${ae} is loaded but ${N} cannot be resolved`)}async function G(ae){const N=await fe.call(this,ae);this.refs[ae]||await R.call(this,N.$schema),this.refs[ae]||this.addSchema(N,ae,Z)}async function fe(ae){const N=this._loading[ae];if(N)return N;try{return await(this._loading[ae]=j(ae))}finally{delete this._loading[ae]}}}addSchema(O,Z,j,E=this.opts.validateSchema){if(Array.isArray(O)){for(const $ of O)this.addSchema($,void 0,j,E);return this}let R;if(typeof O=="object"){const{schemaId:$}=this.opts;if(R=O[$],R!==void 0&&typeof R!="string")throw new Error(`schema ${$} must be string`)}return Z=(0,l.normalizeId)(Z||R),this._checkUnique(Z),this.schemas[Z]=this._addSchema(O,j,Z,E,!0),this}addMetaSchema(O,Z,j=this.opts.validateSchema){return this.addSchema(O,Z,!0,j),this}validateSchema(O,Z){if(typeof O=="boolean")return!0;let j;if(j=O.$schema,j!==void 0&&typeof j!="string")throw new Error("$schema must be a string");if(j=j||this.opts.defaultMeta||this.defaultMeta(),!j)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(j,O);if(!E&&Z){const R="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(R);else throw new Error(R)}return E}getSchema(O){let Z;for(;typeof(Z=S.call(this,O))=="string";)O=Z;if(Z===void 0){const{schemaId:j}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:j});if(Z=a.resolveSchema.call(this,E,O),!Z)return;this.refs[O]=Z}return Z.validate||this._compileSchemaEnv(Z)}removeSchema(O){if(O instanceof RegExp)return this._removeAllSchemas(this.schemas,O),this._removeAllSchemas(this.refs,O),this;switch(typeof O){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const Z=S.call(this,O);return typeof Z=="object"&&this._cache.delete(Z.schema),delete this.schemas[O],delete this.refs[O],this}case"object":{const Z=O;this._cache.delete(Z);let j=O[this.opts.schemaId];return j&&(j=(0,l.normalizeId)(j),delete this.schemas[j],delete this.refs[j]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(O){for(const Z of O)this.addKeyword(Z);return this}addKeyword(O,Z){let j;if(typeof O=="string")j=O,typeof Z=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Z.keyword=j);else if(typeof O=="object"&&Z===void 0){if(Z=O,j=Z.keyword,Array.isArray(j)&&!j.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(F.call(this,j,Z),!Z)return(0,u.eachItem)(j,R=>te.call(this,R)),this;se.call(this,Z);const E={...Z,type:(0,c.getJSONTypes)(Z.type),schemaType:(0,c.getJSONTypes)(Z.schemaType)};return(0,u.eachItem)(j,E.type.length===0?R=>te.call(this,R,E):R=>E.type.forEach($=>te.call(this,R,E,$))),this}getKeyword(O){const Z=this.RULES.all[O];return typeof Z=="object"?Z.definition:!!Z}removeKeyword(O){const{RULES:Z}=this;delete Z.keywords[O],delete Z.all[O];for(const j of Z.rules){const E=j.rules.findIndex(R=>R.keyword===O);E>=0&&j.rules.splice(E,1)}return this}addFormat(O,Z){return typeof Z=="string"&&(Z=new RegExp(Z)),this.formats[O]=Z,this}errorsText(O=this.errors,{separator:Z=", ",dataVar:j="data"}={}){return!O||O.length===0?"No errors":O.map(E=>`${j}${E.instancePath} ${E.message}`).reduce((E,R)=>E+Z+R)}$dataMetaSchema(O,Z){const j=this.RULES.all;O=JSON.parse(JSON.stringify(O));for(const E of Z){const R=E.split("/").slice(1);let $=O;for(const H of R)$=$[H];for(const H in j){const G=j[H];if(typeof G!="object")continue;const{$data:fe}=G.definition,ae=$[H];fe&&ae&&($[H]=pe(ae))}}return O}_removeAllSchemas(O,Z){for(const j in O){const E=O[j];(!Z||Z.test(j))&&(typeof E=="string"?delete O[j]:E&&!E.meta&&(this._cache.delete(E.schema),delete O[j]))}}_addSchema(O,Z,j,E=this.opts.validateSchema,R=this.opts.addUsedSchema){let $;const{schemaId:H}=this.opts;if(typeof O=="object")$=O[H];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof O!="boolean")throw new Error("schema must be object or boolean")}let G=this._cache.get(O);if(G!==void 0)return G;j=(0,l.normalizeId)($||j);const fe=l.getSchemaRefs.call(this,O,j);return G=new a.SchemaEnv({schema:O,schemaId:H,meta:Z,baseId:j,localRefs:fe}),this._cache.set(G.schema,G),R&&!j.startsWith("#")&&(j&&this._checkUnique(j),this.refs[j]=G),E&&this.validateSchema(O,!0),G}_checkUnique(O){if(this.schemas[O]||this.refs[O])throw new Error(`schema with key or id "${O}" already exists`)}_compileSchemaEnv(O){if(O.meta?this._compileMetaSchema(O):a.compileSchema.call(this,O),!O.validate)throw new Error("ajv implementation error");return O.validate}_compileMetaSchema(O){const Z=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,O)}finally{this.opts=Z}}}b.ValidationError=n.default,b.MissingRefError=o.default,e.default=b;function k(V,O,Z,j="error"){for(const E in V){const R=E;R in O&&this.logger[j](`${Z}: option ${E}. ${V[R]}`)}}function S(V){return V=(0,l.normalizeId)(V),this.schemas[V]||this.refs[V]}function C(){const V=this.opts.schemas;if(V)if(Array.isArray(V))this.addSchema(V);else for(const O in V)this.addSchema(V[O],O)}function I(){for(const V in this.opts.formats){const O=this.opts.formats[V];O&&this.addFormat(V,O)}}function x(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const O in V){const Z=V[O];Z.keyword||(Z.keyword=O),this.addKeyword(Z)}}function M(){const V={...this.opts};for(const O of p)delete V[O];return V}const P={log(){},warn(){},error(){}};function U(V){if(V===!1)return P;if(V===void 0)return console;if(V.log&&V.warn&&V.error)return V;throw new Error("logger must implement log, warn and error methods")}const z=/^[a-z_$][a-z0-9_$:-]*$/i;function F(V,O){const{RULES:Z}=this;if((0,u.eachItem)(V,j=>{if(Z.keywords[j])throw new Error(`Keyword ${j} is already defined`);if(!z.test(j))throw new Error(`Keyword ${j} has invalid name`)}),!!O&&O.$data&&!("code"in O||"validate"in O))throw new Error('$data keyword must have "code" or "validate" function')}function te(V,O,Z){var j;const E=O?.post;if(Z&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:R}=this;let $=E?R.post:R.rules.find(({type:G})=>G===Z);if($||($={type:Z,rules:[]},R.rules.push($)),R.keywords[V]=!0,!O)return;const H={keyword:V,definition:{...O,type:(0,c.getJSONTypes)(O.type),schemaType:(0,c.getJSONTypes)(O.schemaType)}};O.before?ie.call(this,$,H,O.before):$.rules.push(H),R.all[V]=H,(j=O.implements)===null||j===void 0||j.forEach(G=>this.addKeyword(G))}function ie(V,O,Z){const j=V.rules.findIndex(E=>E.keyword===Z);j>=0?V.rules.splice(j,0,O):(V.rules.push(O),this.logger.warn(`rule ${Z} is not defined`))}function se(V){let{metaSchema:O}=V;O!==void 0&&(V.$data&&this.opts.$data&&(O=pe(O)),V.validateSchema=this.compile(O,!0))}const ee={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pe(V){return{anyOf:[V,ee]}}})(rl)),rl}var ps={},fs={},hs={},Nh;function pk(){if(Nh)return hs;Nh=1,Object.defineProperty(hs,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return hs.default=e,hs}var mr={},Ah;function fk(){if(Ah)return mr;Ah=1,Object.defineProperty(mr,"__esModule",{value:!0}),mr.callRef=mr.getValidate=void 0;const e=us(),t=Ot(),r=ye(),n=hr(),o=ul(),s=Se(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:g,it:h}=c,{baseId:d,schemaEnv:p,validateName:w,opts:m,self:y}=h,{root:_}=p;if((g==="#"||g==="#/")&&d===_.baseId)return b();const f=o.resolveRef.call(y,_,d,g);if(f===void 0)throw new e.default(h.opts.uriResolver,d,g);if(f instanceof o.SchemaEnv)return k(f);return S(f);function b(){if(p===_)return l(c,w,p,p.$async);const C=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${C}.validate`,_,_.$async)}function k(C){const I=i(c,C);l(c,I,C,C.$async)}function S(C){const I=u.scopeValue("schema",m.code.source===!0?{ref:C,code:(0,r.stringify)(C)}:{ref:C}),x=u.name("valid"),M=c.subschema({schema:C,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:g},x);c.mergeEvaluated(M),c.ok(x)}}};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`}mr.getValidate=i;function l(c,u,g,h){const{gen:d,it:p}=c,{allErrors:w,schemaEnv:m,opts:y}=p,_=y.passContext?n.default.this:r.nil;h?f():b();function f(){if(!m.$async)throw new Error("async schema referenced by sync schema");const C=d.let("valid");d.try(()=>{d.code((0,r._)`await ${(0,t.callValidateCode)(c,u,_)}`),S(u),w||d.assign(C,!0)},I=>{d.if((0,r._)`!(${I} instanceof ${p.ValidationError})`,()=>d.throw(I)),k(I),w||d.assign(C,!1)}),c.ok(C)}function b(){c.result((0,t.callValidateCode)(c,u,_),()=>S(u),()=>k(u))}function k(C){const I=(0,r._)`${C}.errors`;d.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${I} : ${n.default.vErrors}.concat(${I})`),d.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function S(C){var I;if(!p.opts.unevaluated)return;const x=(I=g?.validate)===null||I===void 0?void 0:I.evaluated;if(p.props!==!0)if(x&&!x.dynamicProps)x.props!==void 0&&(p.props=s.mergeEvaluated.props(d,x.props,p.props));else{const M=d.var("props",(0,r._)`${C}.evaluated.props`);p.props=s.mergeEvaluated.props(d,M,p.props,r.Name)}if(p.items!==!0)if(x&&!x.dynamicItems)x.items!==void 0&&(p.items=s.mergeEvaluated.items(d,x.items,p.items));else{const M=d.var("items",(0,r._)`${C}.evaluated.items`);p.items=s.mergeEvaluated.items(d,M,p.items,r.Name)}}}return mr.callRef=l,mr.default=a,mr}var qh;function hk(){if(qh)return fs;qh=1,Object.defineProperty(fs,"__esModule",{value:!0});const e=pk(),t=fk(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return fs.default=r,fs}var ms={},gs={},Lh;function mk(){if(Lh)return gs;Lh=1,Object.defineProperty(gs,"__esModule",{value:!0});const e=ye(),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 gs.default=o,gs}var vs={},jh;function gk(){if(jh)return vs;jh=1,Object.defineProperty(vs,"__esModule",{value:!0});const e=ye(),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 vs.default=r,vs}var _s={},ys={},Uh;function vk(){if(Uh)return ys;Uh=1,Object.defineProperty(ys,"__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 ys.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ys}var zh;function _k(){if(zh)return _s;zh=1,Object.defineProperty(_s,"__esModule",{value:!0});const e=ye(),t=Se(),r=vk(),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 _s.default=o,_s}var ws={},Dh;function yk(){if(Dh)return ws;Dh=1,Object.defineProperty(ws,"__esModule",{value:!0});const e=Ot(),t=ye(),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 ws.default=n,ws}var bs={},Zh;function wk(){if(Zh)return bs;Zh=1,Object.defineProperty(bs,"__esModule",{value:!0});const e=ye(),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 bs.default=r,bs}var ks={},Fh;function bk(){if(Fh)return ks;Fh=1,Object.defineProperty(ks,"__esModule",{value:!0});const e=Ot(),t=ye(),r=Se(),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:h}=g;if(!u&&i.length===0)return;const d=i.length>=h.loopRequired;if(g.allErrors?p():w(),h.strictRequired){const _=s.parentSchema.properties,{definedProperties:f}=s.it;for(const b of i)if(_?.[b]===void 0&&!f.has(b)){const k=g.schemaEnv.baseId+g.errSchemaPath,S=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(g,S,g.opts.strictRequired)}}function p(){if(d||u)s.block$data(t.nil,m);else for(const _ of i)(0,e.checkReportMissingProp)(s,_)}function w(){const _=a.let("missing");if(d||u){const f=a.let("valid",!0);s.block$data(f,()=>y(_,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,_,h.ownProperties),()=>s.error())})}function y(_,f){s.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(f,(0,e.propertyInData)(a,c,_,h.ownProperties)),a.if((0,t.not)(f),()=>{s.error(),a.break()})},t.nil)}}};return ks.default=o,ks}var Ss={},Vh;function kk(){if(Vh)return Ss;Vh=1,Object.defineProperty(Ss,"__esModule",{value:!0});const e=ye(),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 Ss.default=r,Ss}var Cs={},Ts={},Hh;function fl(){if(Hh)return Ts;Hh=1,Object.defineProperty(Ts,"__esModule",{value:!0});const e=bh();return e.code='require("ajv/dist/runtime/equal").default',Ts.default=e,Ts}var Bh;function Sk(){if(Bh)return Cs;Bh=1,Object.defineProperty(Cs,"__esModule",{value:!0});const e=ss(),t=ye(),r=Se(),n=fl(),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:h,it:d}=a;if(!c&&!u)return;const p=i.let("valid"),w=g.items?(0,e.getSchemaTypes)(g.items):[];a.block$data(p,m,(0,t._)`${h} === false`),a.ok(p);function m(){const b=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:b,j:k}),i.assign(p,!0),i.if((0,t._)`${b} > 1`,()=>(y()?_:f)(b,k))}function y(){return w.length>0&&!w.some(b=>b==="object"||b==="array")}function _(b,k){const S=i.name("item"),C=(0,e.checkDataTypes)(w,S,d.opts.strictNumbers,e.DataType.Wrong),I=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${b}--;`,()=>{i.let(S,(0,t._)`${l}[${b}]`),i.if(C,(0,t._)`continue`),w.length>1&&i.if((0,t._)`typeof ${S} == "string"`,(0,t._)`${S} += "_"`),i.if((0,t._)`typeof ${I}[${S}] == "number"`,()=>{i.assign(k,(0,t._)`${I}[${S}]`),a.error(),i.assign(p,!1).break()}).code((0,t._)`${I}[${S}] = ${b}`)})}function f(b,k){const S=(0,r.useFunc)(i,n.default),C=i.name("outer");i.label(C).for((0,t._)`;${b}--;`,()=>i.for((0,t._)`${k} = ${b}; ${k}--;`,()=>i.if((0,t._)`${S}(${l}[${b}], ${l}[${k}])`,()=>{a.error(),i.assign(p,!1).break(C)})))}}};return Cs.default=s,Cs}var $s={},Jh;function Ck(){if(Jh)return $s;Jh=1,Object.defineProperty($s,"__esModule",{value:!0});const e=ye(),t=Se(),r=fl(),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 $s.default=o,$s}var Es={},Gh;function Tk(){if(Gh)return Es;Gh=1,Object.defineProperty(Es,"__esModule",{value:!0});const e=ye(),t=Se(),r=fl(),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 h=c.length>=g.opts.loopEnum;let d;const p=()=>d??(d=(0,t.useFunc)(a,r.default));let w;if(h||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,b)=>y(_,b)))}s.pass(w);function m(){a.assign(w,!1),a.forOf("v",u,_=>a.if((0,e._)`${p()}(${i}, ${_})`,()=>a.assign(w,!0).break()))}function y(_,f){const b=c[f];return typeof b=="object"&&b!==null?(0,e._)`${p()}(${i}, ${_}[${f}])`:(0,e._)`${i} === ${b}`}}};return Es.default=o,Es}var Wh;function $k(){if(Wh)return ms;Wh=1,Object.defineProperty(ms,"__esModule",{value:!0});const e=mk(),t=gk(),r=_k(),n=yk(),o=wk(),s=bk(),a=kk(),i=Sk(),l=Ck(),c=Tk(),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 ms.default=u,ms}var Is={},ln={},Kh;function Yh(){if(Kh)return ln;Kh=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.validateAdditionalItems=void 0;const e=ye(),t=Se(),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 h=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${h} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(g,l)){const p=i.var("valid",(0,e._)`${h} <= ${a.length}`);i.if((0,e.not)(p),()=>d(p)),s.ok(p)}function d(p){i.forRange("i",a.length,h,w=>{s.subschema({keyword:u,dataProp:w,dataPropType:t.Type.Num},p),g.allErrors||i.if((0,e.not)(p),()=>i.break())})}}return ln.validateAdditionalItems=o,ln.default=n,ln}var xs={},cn={},Qh;function Xh(){if(Qh)return cn;Qh=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.validateTuple=void 0;const e=ye(),t=Se(),r=Ot(),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:h}=s;w(c),h.opts.unevaluated&&i.length&&h.items!==!0&&(h.items=t.mergeEvaluated.items(l,i.length,h.items));const d=l.name("valid"),p=l.const("len",(0,e._)`${u}.length`);i.forEach((m,y)=>{(0,t.alwaysValidSchema)(h,m)||(l.if((0,e._)`${p} > ${y}`,()=>s.subschema({keyword:g,schemaProp:y,dataProp:y},d)),s.ok(d))});function w(m){const{opts:y,errSchemaPath:_}=h,f=i.length,b=f===m.minItems&&(f===m.maxItems||m[a]===!1);if(y.strictTuples&&!b){const k=`"${g}" is ${f}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(h,k,y.strictTuples)}}}return cn.validateTuple=o,cn.default=n,cn}var em;function Ek(){if(em)return xs;em=1,Object.defineProperty(xs,"__esModule",{value:!0});const e=Xh(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return xs.default=t,xs}var Rs={},tm;function Ik(){if(tm)return Rs;tm=1,Object.defineProperty(Rs,"__esModule",{value:!0});const e=ye(),t=Se(),r=Ot(),n=Yh(),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 Rs.default=s,Rs}var Ps={},rm;function xk(){if(rm)return Ps;rm=1,Object.defineProperty(Ps,"__esModule",{value:!0});const e=ye(),t=Se(),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:h,maxContains:d}=i;c.opts.next?(u=h===void 0?1:h,g=d):u=1;const p=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._)`${p} >= ${u}`;g!==void 0&&(f=(0,e._)`${f} && ${p} <= ${g}`),o.pass(f);return}c.items=!0;const w=s.name("valid");g===void 0&&u===1?y(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"),b=s.let("count",0);y(f,()=>s.if(f,()=>_(b)))}function y(f,b){s.forRange("i",0,p,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},f),b()})}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 Ps.default=n,Ps}var hl={},nm;function Rk(){return nm||(nm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=ye(),r=Se(),n=Ot();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},
76
- missingProperty: ${g},
73
+ ${t}:`]}}function Vm({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 Hm(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 MC=at(()=>Ee(C({id:d().nullish(),created:A().nullish(),model:d().nullish(),choices:R(C({text:d(),finish_reason:d(),logprobs:C({tokens:R(d()),token_logprobs:R(A()),top_logprobs:R(oe(d(),A())).nullish()}).nullish()})),usage:C({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}))),AC=at(()=>Ee(X([C({id:d().nullish(),created:A().nullish(),model:d().nullish(),choices:R(C({text:d(),finish_reason:d().nullish(),index:A(),logprobs:C({tokens:R(d()),token_logprobs:R(A()),top_logprobs:R(oe(d(),A())).nullish()}).nullish()})),usage:C({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}),Nl]))),Bm=at(()=>Ee(C({echo:te().optional(),logitBias:oe(d(),A()).optional(),suffix:d().optional(),user:d().optional(),logprobs:X([te(),A()]).optional()}))),NC=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:i,stopSequences:a,responseFormat:l,tools:c,toolChoice:u,seed:m,providerOptions:f}){const p=[],h={...await br({provider:"openai",providerOptions:f,schema:Bm}),...await br({provider:this.providerOptionsName,providerOptions:f,schema:Bm})};o!=null&&p.push({type:"unsupported-setting",setting:"topK"}),c?.length&&p.push({type:"unsupported-setting",setting:"tools"}),u!=null&&p.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:_}=OC({prompt:e}),w=[..._??[],...a??[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:h?.logprobs===!0?0:h?.logprobs===!1?void 0:h?.logprobs,suffix:h.suffix,user:h.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:i,seed:m,prompt:v,stop:w.length>0?w:void 0},warnings:p}}async doGenerate(e){var t,r,n;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:l}=await sr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Qt(this.config.headers(),e.headers),body:o,failedResponseHandler:Xt,successfulResponseHandler:_n(MC),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(t=a.usage)==null?void 0:t.prompt_tokens,outputTokens:(r=a.usage)==null?void 0:r.completion_tokens,totalTokens:(n=a.usage)==null?void 0:n.total_tokens},finishReason:Hm(c.finish_reason),request:{body:o},response:{...Vm(a),headers:i,body:l},providerMetadata:u,warnings:s}}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 sr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Qt(this.config.headers(),e.headers),body:n,failedResponseHandler:Xt,successfulResponseHandler:Pl(AC),abortSignal:e.abortSignal,fetch:this.config.fetch});let i="unknown";const a={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let 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){i="error",m.enqueue({type:"error",error:u.error});return}const f=u.value;if("error"in f){i="error",m.enqueue({type:"error",error:f.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",...Vm(f)}),m.enqueue({type:"text-start",id:"0"})),f.usage!=null&&(l.inputTokens=f.usage.prompt_tokens,l.outputTokens=f.usage.completion_tokens,l.totalTokens=f.usage.total_tokens);const p=f.choices[0];p?.finish_reason!=null&&(i=Hm(p.finish_reason)),p?.logprobs!=null&&(a.openai.logprobs=p.logprobs),p?.text!=null&&p.text.length>0&&m.enqueue({type:"text-delta",id:"0",delta:p.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:i,providerMetadata:a,usage:l})}})),request:{body:n},response:{headers:o}}}},qC=at(()=>Ee(C({dimensions:A().optional(),user:d().optional()}))),LC=at(()=>Ee(C({data:R(C({embedding:R(A())})),usage:C({prompt_tokens:A()}).nullish()}))),UC=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new s8({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await br({provider:"openai",providerOptions:n,schema:qC}))!=null?o:{},{responseHeaders:i,value:a,rawValue:l}=await sr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Qt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Xt,successfulResponseHandler:_n(LC),abortSignal:r,fetch:this.config.fetch});return{embeddings:a.data.map(c=>c.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:i,body:l}}}},jC=at(()=>Ee(C({created:A().nullish(),data:R(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:A().nullish(),output_tokens:A().nullish(),total_tokens:A().nullish(),input_tokens_details:C({image_tokens:A().nullish(),text_tokens:A().nullish()}).nullish()}).nullish()}))),DC={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},zC=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),ZC=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=DC[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,providerOptions:s,headers:i,abortSignal:a}){var l,c,u,m;const f=[];n!=null&&f.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&f.push({type:"unsupported-setting",setting:"seed"});const p=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:h,responseHeaders:v}=await sr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Qt(this.config.headers(),i),body:{model:this.modelId,prompt:e,n:t,size:r,...(m=s.openai)!=null?m:{},...zC.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Xt,successfulResponseHandler:_n(jC),abortSignal:a,fetch:this.config.fetch});return{images:h.data.map(_=>_.b64_json),warnings:f,response:{timestamp:p,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:h.data.map(_=>({..._.revised_prompt?{revisedPrompt:_.revised_prompt}:{},...h.created!=null?{created:h.created}:{},...h.size!=null?{size:h.size}:{},...h.quality!=null?{quality:h.quality}:{},...h.background!=null?{background:h.background}:{},...h.output_format!=null?{outputFormat:h.output_format}:{}}))}}}}},FC=nt(()=>Ee(C({code:d().nullish(),containerId:d()}))),VC=nt(()=>Ee(C({outputs:R(De("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullish()}))),HC=nt(()=>Ee(C({container:X([d(),C({fileIds:R(d()).optional()})]).optional()}))),BC=gn({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:FC,outputSchema:VC}),JC=(e={})=>BC(e),Jm=C({key:d(),type:_e(["eq","ne","gt","gte","lt","lte","in","nin"]),value:X([d(),A(),te(),R(d())])}),Wm=C({type:_e(["and","or"]),filters:R(X([Jm,lp(()=>Wm)]))}),WC=nt(()=>Ee(C({vectorStoreIds:R(d()),maxNumResults:A().optional(),ranking:C({ranker:d().optional(),scoreThreshold:A().optional()}).optional(),filters:X([Jm,Wm]).optional()}))),GC=nt(()=>Ee(C({queries:R(d()),results:R(C({attributes:oe(d(),ce()),fileId:d(),filename:d(),score:A(),text:d()})).nullable()}))),KC=gn({id:"openai.file_search",name:"file_search",inputSchema:C({}),outputSchema:GC}),YC=nt(()=>Ee(C({background:_e(["auto","opaque","transparent"]).optional(),inputFidelity:_e(["low","high"]).optional(),inputImageMask:C({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:_e(["auto"]).optional(),outputCompression:A().int().min(0).max(100).optional(),outputFormat:_e(["png","jpeg","webp"]).optional(),partialImages:A().int().min(0).max(3).optional(),quality:_e(["auto","low","medium","high"]).optional(),size:_e(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),QC=nt(()=>Ee(C({}))),XC=nt(()=>Ee(C({result:d()}))),ek=gn({id:"openai.image_generation",name:"image_generation",inputSchema:QC,outputSchema:XC}),tk=(e={})=>ek(e),Gm=nt(()=>Ee(C({action:C({type:O("exec"),command:R(d()),timeoutMs:A().optional(),user:d().optional(),workingDirectory:d().optional(),env:oe(d(),d()).optional()})}))),Km=nt(()=>Ee(C({output:d()}))),rk=gn({id:"openai.local_shell",name:"local_shell",inputSchema:Gm,outputSchema:Km}),nk=nt(()=>Ee(C({externalWebAccess:te().optional(),filters:C({allowedDomains:R(d()).optional()}).optional(),searchContextSize:_e(["low","medium","high"]).optional(),userLocation:C({type:O("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),ok=nt(()=>Ee(C({}))),sk=nt(()=>Ee(C({action:De("type",[C({type:O("search"),query:d().optional()}),C({type:O("openPage"),url:d().nullish()}),C({type:O("findInPage"),url:d().nullish(),pattern:d().nullish()})]),sources:R(De("type",[C({type:O("url"),url:d()}),C({type:O("api"),name:d()})])).optional()}))),ak=gn({id:"openai.web_search",name:"web_search",inputSchema:ok,outputSchema:sk}),ik=(e={})=>ak(e),lk=nt(()=>Ee(C({searchContextSize:_e(["low","medium","high"]).optional(),userLocation:C({type:O("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),ck=nt(()=>Ee(C({}))),uk=nt(()=>Ee(C({action:De("type",[C({type:O("search"),query:d().optional()}),C({type:O("openPage"),url:d().nullish()}),C({type:O("findInPage"),url:d().nullish(),pattern:d().nullish()})])}))),dk=gn({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:ck,outputSchema:uk}),pk={codeInterpreter:JC,fileSearch:KC,imageGeneration:tk,localShell:rk,webSearchPreview:dk,webSearch:ik};function Ym(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function hk({prompt:e,systemMessageMode:t,fileIdPrefixes:r,store:n,hasLocalShellTool:o=!1}){var s,i,a,l;const c=[],u=[];for(const{role:m,content:f}of e)switch(m){case"system":{switch(t){case"system":{c.push({role:"system",content:f});break}case"developer":{c.push({role:"developer",content:f});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const p=t;throw new Error(`Unsupported system message mode: ${p}`)}}break}case"user":{c.push({role:"user",content:f.map((p,h)=>{var v,_,w;switch(p.type){case"text":return{type:"input_text",text:p.text};case"file":if(p.mediaType.startsWith("image/")){const g=p.mediaType==="image/*"?"image/jpeg":p.mediaType;return{type:"input_image",...p.data instanceof URL?{image_url:p.data.toString()}:typeof p.data=="string"&&Ym(p.data,r)?{file_id:p.data}:{image_url:`data:${g};base64,${vn(p.data)}`},detail:(_=(v=p.providerOptions)==null?void 0:v.openai)==null?void 0:_.imageDetail}}else{if(p.mediaType==="application/pdf")return p.data instanceof URL?{type:"input_file",file_url:p.data.toString()}:{type:"input_file",...typeof p.data=="string"&&Ym(p.data,r)?{file_id:p.data}:{filename:(w=p.filename)!=null?w:`part-${h}.pdf`,file_data:`data:application/pdf;base64,${vn(p.data)}`}};throw new or({functionality:`file part media type ${p.mediaType}`})}}})});break}case"assistant":{const p={},h={};for(const v of f)switch(v.type){case"text":{const _=(i=(s=v.providerOptions)==null?void 0:s.openai)==null?void 0:i.itemId;if(n&&_!=null){c.push({type:"item_reference",id:_});break}c.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:_});break}case"tool-call":{if(h[v.toolCallId]=v,v.providerExecuted)break;const _=(l=(a=v.providerOptions)==null?void 0:a.openai)==null?void 0:l.itemId;if(n&&_!=null){c.push({type:"item_reference",id:_});break}if(o&&v.toolName==="local_shell"){const w=await wr({value:v.input,schema:Gm});c.push({type:"local_shell_call",call_id:v.toolCallId,id:_,action:{type:"exec",command:w.action.command,timeout_ms:w.action.timeoutMs,user:w.action.user,working_directory:w.action.workingDirectory,env:w.action.env}});break}c.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:_});break}case"tool-result":{n?c.push({type:"item_reference",id:v.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${v.toolName} are not sent to the API when store is false`});break}case"reasoning":{const _=await br({provider:"openai",providerOptions:v.providerOptions,schema:fk}),w=_?.itemId;if(w!=null){const g=p[w];if(n)g===void 0&&(c.push({type:"item_reference",id:w}),p[w]={type:"reasoning",id:w,summary:[]});else{const y=[];v.text.length>0?y.push({type:"summary_text",text:v.text}):g!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),g===void 0?(p[w]={type:"reasoning",id:w,encrypted_content:_?.reasoningEncryptedContent,summary:y},c.push(p[w])):(g.summary.push(...y),_?.reasoningEncryptedContent!=null&&(g.encrypted_content=_.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(v)}.`});break}}break}case"tool":{for(const p of f){const h=p.output;if(o&&p.toolName==="local_shell"&&h.type==="json"){const _=await wr({value:h.value,schema:Km});c.push({type:"local_shell_call_output",call_id:p.toolCallId,output:_.output});break}let v;switch(h.type){case"text":case"error-text":v=h.value;break;case"json":case"error-json":v=JSON.stringify(h.value);break;case"content":v=h.value.map(_=>{switch(_.type){case"text":return{type:"input_text",text:_.text};case"media":return _.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${_.mediaType};base64,${_.data}`}:{type:"input_file",filename:"data",file_data:`data:${_.mediaType};base64,${_.data}`}}});break}c.push({type:"function_call_output",call_id:p.toolCallId,output:v})}break}default:{const p=m;throw new Error(`Unsupported role: ${p}`)}}return{input:c,warnings:u}}var fk=C({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function Qm({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":"unknown"}}var mk=at(()=>Ee(X([C({type:O("response.output_text.delta"),item_id:d(),delta:d(),logprobs:R(C({token:d(),logprob:A(),top_logprobs:R(C({token:d(),logprob:A()}))})).nullish()}),C({type:_e(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:A(),input_tokens_details:C({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:C({reasoning_tokens:A().nullish()}).nullish()}),service_tier:d().nullish()})}),C({type:O("response.created"),response:C({id:d(),created_at:A(),model:d(),service_tier:d().nullish()})}),C({type:O("response.output_item.added"),output_index:A(),item:De("type",[C({type:O("message"),id:d()}),C({type:O("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:O("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),C({type:O("web_search_call"),id:d(),status:d()}),C({type:O("computer_call"),id:d(),status:d()}),C({type:O("file_search_call"),id:d()}),C({type:O("image_generation_call"),id:d()}),C({type:O("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:R(De("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullable(),status:d()})])}),C({type:O("response.output_item.done"),output_index:A(),item:De("type",[C({type:O("message"),id:d()}),C({type:O("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:O("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:O("completed")}),C({type:O("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:R(De("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullable()}),C({type:O("image_generation_call"),id:d(),result:d()}),C({type:O("web_search_call"),id:d(),status:d(),action:De("type",[C({type:O("search"),query:d().nullish(),sources:R(De("type",[C({type:O("url"),url:d()}),C({type:O("api"),name:d()})])).nullish()}),C({type:O("open_page"),url:d().nullish()}),C({type:O("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),C({type:O("file_search_call"),id:d(),queries:R(d()),results:R(C({attributes:oe(d(),ce()),file_id:d(),filename:d(),score:A(),text:d()})).nullish()}),C({type:O("local_shell_call"),id:d(),call_id:d(),action:C({type:O("exec"),command:R(d()),timeout_ms:A().optional(),user:d().optional(),working_directory:d().optional(),env:oe(d(),d()).optional()})}),C({type:O("computer_call"),id:d(),status:O("completed")})])}),C({type:O("response.function_call_arguments.delta"),item_id:d(),output_index:A(),delta:d()}),C({type:O("response.image_generation_call.partial_image"),item_id:d(),output_index:A(),partial_image_b64:d()}),C({type:O("response.code_interpreter_call_code.delta"),item_id:d(),output_index:A(),delta:d()}),C({type:O("response.code_interpreter_call_code.done"),item_id:d(),output_index:A(),code:d()}),C({type:O("response.output_text.annotation.added"),annotation:De("type",[C({type:O("url_citation"),start_index:A(),end_index:A(),url:d(),title:d()}),C({type:O("file_citation"),file_id:d(),filename:d().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:d().nullish()})])}),C({type:O("response.reasoning_summary_part.added"),item_id:d(),summary_index:A()}),C({type:O("response.reasoning_summary_text.delta"),item_id:d(),summary_index:A(),delta:d()}),C({type:O("response.reasoning_summary_part.done"),item_id:d(),summary_index:A()}),C({type:O("error"),sequence_number:A(),error:C({type:d(),code:d(),message:d(),param:d().nullish()})}),C({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),gk=at(()=>Ee(C({id:d().optional(),created_at:A().optional(),error:C({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:R(De("type",[C({type:O("message"),role:O("assistant"),id:d(),content:R(C({type:O("output_text"),text:d(),logprobs:R(C({token:d(),logprob:A(),top_logprobs:R(C({token:d(),logprob:A()}))})).nullish(),annotations:R(De("type",[C({type:O("url_citation"),start_index:A(),end_index:A(),url:d(),title:d()}),C({type:O("file_citation"),file_id:d(),filename:d().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:d().nullish()}),C({type:O("container_file_citation"),container_id:d(),file_id:d(),filename:d().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),C({type:O("file_path"),file_id:d(),index:A().nullish()})]))}))}),C({type:O("web_search_call"),id:d(),status:d(),action:De("type",[C({type:O("search"),query:d().nullish(),sources:R(De("type",[C({type:O("url"),url:d()}),C({type:O("api"),name:d()})])).nullish()}),C({type:O("open_page"),url:d().nullish()}),C({type:O("find_in_page"),url:d().nullish(),pattern:d().nullish()})])}),C({type:O("file_search_call"),id:d(),queries:R(d()),results:R(C({attributes:oe(d(),X([d(),A(),te()])),file_id:d(),filename:d(),score:A(),text:d()})).nullish()}),C({type:O("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:R(De("type",[C({type:O("logs"),logs:d()}),C({type:O("image"),url:d()})])).nullable()}),C({type:O("image_generation_call"),id:d(),result:d()}),C({type:O("local_shell_call"),id:d(),call_id:d(),action:C({type:O("exec"),command:R(d()),timeout_ms:A().optional(),user:d().optional(),working_directory:d().optional(),env:oe(d(),d()).optional()})}),C({type:O("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),C({type:O("computer_call"),id:d(),status:d().optional()}),C({type:O("reasoning"),id:d(),encrypted_content:d().nullish(),summary:R(C({type:O("summary_text"),text:d()}))})])).optional(),service_tier:d().nullish(),incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:A(),input_tokens_details:C({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:C({reasoning_tokens:A().nullish()}).nullish()}).optional()}))),Xm=20,_k=at(()=>Ee(C({conversation:d().nullish(),include:R(_e(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:X([te(),A().min(1).max(Xm)]).optional(),maxToolCalls:A().nullish(),metadata:tt().nullish(),parallelToolCalls:te().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:_e(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:_e(["auto","flex","priority","default"]).nullish(),store:te().nullish(),strictJsonSchema:te().nullish(),textVerbosity:_e(["low","medium","high"]).nullish(),truncation:_e(["auto","disabled"]).nullish(),user:d().nullish()})));async function vk({tools:e,toolChoice:t,strictJsonSchema:r}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const o=[];for(const i of e)switch(i.type){case"function":o.push({type:"function",name:i.name,description:i.description,parameters:i.inputSchema,strict:r});break;case"provider-defined":{switch(i.id){case"openai.file_search":{const a=await wr({value:i.args,schema:WC});o.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":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const a=await wr({value:i.args,schema:lk});o.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await wr({value:i.args,schema:nk});o.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 wr({value:i.args,schema:HC});o.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 wr({value:i.args,schema:YC});o.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,size:a.size,quality:a.quality,moderation:a.moderation,output_format:a.outputFormat,output_compression:a.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:n};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:n};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const i=s;throw new or({functionality:`tool choice type: ${i}`})}}}var yk=class{constructor(e,t){this.specificationVersion="v2",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:i,seed:a,prompt:l,providerOptions:c,tools:u,toolChoice:m,responseFormat:f}){var p,h,v,_;const w=[],g=Zm(this.modelId);o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),a!=null&&w.push({type:"unsupported-setting",setting:"seed"}),s!=null&&w.push({type:"unsupported-setting",setting:"presencePenalty"}),i!=null&&w.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&w.push({type:"unsupported-setting",setting:"stopSequences"});const y=await br({provider:"openai",providerOptions:c,schema:_k});y?.conversation&&y?.previousResponseId&&w.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:S}=await hk({prompt:l,systemMessageMode:g.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(p=y?.store)!=null?p:!0,hasLocalShellTool:P("openai.local_shell")});w.push(...S);const $=(h=y?.strictJsonSchema)!=null?h:!1;let k=y?.include;function I(ie){k==null?k=[ie]:k.includes(ie)||(k=[...k,ie])}function P(ie){return u?.find(re=>re.type==="provider-defined"&&re.id===ie)!=null}const L=typeof y?.logprobs=="number"?y?.logprobs:y?.logprobs===!0?Xm:void 0;L&&I("message.output_text.logprobs");const N=(v=u?.find(ie=>ie.type==="provider-defined"&&(ie.id==="openai.web_search"||ie.id==="openai.web_search_preview")))==null?void 0:v.name;N&&I("web_search_call.action.sources"),P("openai.code_interpreter")&&I("code_interpreter_call.outputs");const j=y?.store;j===!1&&g.isReasoningModel&&I("reasoning.encrypted_content");const D={model:this.modelId,input:b,temperature:t,top_p:n,max_output_tokens:e,...(f?.type==="json"||y?.textVerbosity)&&{text:{...f?.type==="json"&&{format:f.schema!=null?{type:"json_schema",strict:$,name:(_=f.name)!=null?_:"response",description:f.description,schema:f.schema}:{type:"json_object"}},...y?.textVerbosity&&{verbosity:y.textVerbosity}}},conversation:y?.conversation,max_tool_calls:y?.maxToolCalls,metadata:y?.metadata,parallel_tool_calls:y?.parallelToolCalls,previous_response_id:y?.previousResponseId,store:j,user:y?.user,instructions:y?.instructions,service_tier:y?.serviceTier,include:k,prompt_cache_key:y?.promptCacheKey,prompt_cache_retention:y?.promptCacheRetention,safety_identifier:y?.safetyIdentifier,top_logprobs:L,truncation:y?.truncation,...g.isReasoningModel&&(y?.reasoningEffort!=null||y?.reasoningSummary!=null)&&{reasoning:{...y?.reasoningEffort!=null&&{effort:y.reasoningEffort},...y?.reasoningSummary!=null&&{summary:y.reasoningSummary}}}};g.isReasoningModel?y?.reasoningEffort==="none"&&g.supportsNonReasoningParameters||(D.temperature!=null&&(D.temperature=void 0,w.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),D.top_p!=null&&(D.top_p=void 0,w.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(y?.reasoningEffort!=null&&w.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),y?.reasoningSummary!=null&&w.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),y?.serviceTier==="flex"&&!g.supportsFlexProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete D.service_tier),y?.serviceTier==="priority"&&!g.supportsPriorityProcessing&&(w.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete D.service_tier);const{tools:F,toolChoice:ne,toolWarnings:ue}=await vk({tools:u,toolChoice:m,strictJsonSchema:$});return{webSearchToolName:N,args:{...D,tools:F,tool_choice:ne},warnings:[...w,...ue],store:j}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,m,f,p,h,v,_,w,g,y,b,S,$,k,I,P,L,N,j;const{args:D,warnings:F,webSearchToolName:ne}=await this.getArgs(e),ue=this.config.url({path:"/responses",modelId:this.modelId}),ie=this.config.provider.replace(".responses",""),{responseHeaders:re,value:he,rawValue:V}=await sr({url:ue,headers:Qt(this.config.headers(),e.headers),body:D,failedResponseHandler:Xt,successfulResponseHandler:_n(gk),abortSignal:e.abortSignal,fetch:this.config.fetch});if(he.error)throw new Et({message:he.error.message,url:ue,requestBodyValues:D,statusCode:400,responseHeaders:re,responseBody:V,isRetryable:!1});const M=[],Z=[];let U=!1;for(const E of he.output)switch(E.type){case"reasoning":{E.summary.length===0&&E.summary.push({type:"summary_text",text:""});for(const H of E.summary)M.push({type:"reasoning",text:H.text,providerMetadata:{[ie]:{itemId:E.id,reasoningEncryptedContent:(t=E.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{M.push({type:"tool-call",toolCallId:E.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),M.push({type:"tool-result",toolCallId:E.id,toolName:"image_generation",result:{result:E.result},providerExecuted:!0});break}case"local_shell_call":{M.push({type:"tool-call",toolCallId:E.call_id,toolName:"local_shell",input:JSON.stringify({action:E.action}),providerMetadata:{[ie]:{itemId:E.id}}});break}case"message":{for(const H of E.content){(n=(r=e.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&H.logprobs&&Z.push(H.logprobs),M.push({type:"text",text:H.text,providerMetadata:{[ie]:{itemId:E.id}}});for(const W of H.annotations)W.type==="url_citation"?M.push({type:"source",sourceType:"url",id:(i=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?i:Lt(),url:W.url,title:W.title}):W.type==="file_citation"?M.push({type:"source",sourceType:"document",id:(c=(l=(a=this.config).generateId)==null?void 0:l.call(a))!=null?c:Lt(),mediaType:"text/plain",title:(m=(u=W.quote)!=null?u:W.filename)!=null?m:"Document",filename:(f=W.filename)!=null?f:W.file_id,...W.file_id?{providerMetadata:{[ie]:{fileId:W.file_id}}}:{}}):W.type==="container_file_citation"?M.push({type:"source",sourceType:"document",id:(v=(h=(p=this.config).generateId)==null?void 0:h.call(p))!=null?v:Lt(),mediaType:"text/plain",title:(w=(_=W.filename)!=null?_:W.file_id)!=null?w:"Document",filename:(g=W.filename)!=null?g:W.file_id,providerMetadata:{[ie]:{fileId:W.file_id,containerId:W.container_id,...W.index!=null?{index:W.index}:{}}}}):W.type==="file_path"&&M.push({type:"source",sourceType:"document",id:(S=(b=(y=this.config).generateId)==null?void 0:b.call(y))!=null?S:Lt(),mediaType:"application/octet-stream",title:W.file_id,filename:W.file_id,providerMetadata:{[ie]:{fileId:W.file_id,...W.index!=null?{index:W.index}:{}}}})}break}case"function_call":{U=!0,M.push({type:"tool-call",toolCallId:E.call_id,toolName:E.name,input:E.arguments,providerMetadata:{[ie]:{itemId:E.id}}});break}case"web_search_call":{M.push({type:"tool-call",toolCallId:E.id,toolName:ne??"web_search",input:JSON.stringify({}),providerExecuted:!0}),M.push({type:"tool-result",toolCallId:E.id,toolName:ne??"web_search",result:t2(E.action),providerExecuted:!0});break}case"computer_call":{M.push({type:"tool-call",toolCallId:E.id,toolName:"computer_use",input:"",providerExecuted:!0}),M.push({type:"tool-result",toolCallId:E.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:E.status||"completed"},providerExecuted:!0});break}case"file_search_call":{M.push({type:"tool-call",toolCallId:E.id,toolName:"file_search",input:"{}",providerExecuted:!0}),M.push({type:"tool-result",toolCallId:E.id,toolName:"file_search",result:{queries:E.queries,results:(k=($=E.results)==null?void 0:$.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?k:null},providerExecuted:!0});break}case"code_interpreter_call":{M.push({type:"tool-call",toolCallId:E.id,toolName:"code_interpreter",input:JSON.stringify({code:E.code,containerId:E.container_id}),providerExecuted:!0}),M.push({type:"tool-result",toolCallId:E.id,toolName:"code_interpreter",result:{outputs:E.outputs},providerExecuted:!0});break}}const T={[ie]:{...he.id!=null?{responseId:he.id}:{}}};Z.length>0&&(T[ie].logprobs=Z),typeof he.service_tier=="string"&&(T[ie].serviceTier=he.service_tier);const x=he.usage;return{content:M,finishReason:Qm({finishReason:(I=he.incomplete_details)==null?void 0:I.reason,hasFunctionCall:U}),usage:{inputTokens:x.input_tokens,outputTokens:x.output_tokens,totalTokens:x.input_tokens+x.output_tokens,reasoningTokens:(L=(P=x.output_tokens_details)==null?void 0:P.reasoning_tokens)!=null?L:void 0,cachedInputTokens:(j=(N=x.input_tokens_details)==null?void 0:N.cached_tokens)!=null?j:void 0},request:{body:D},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:re,body:V},providerMetadata:T,warnings:F}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,store:o}=await this.getArgs(e),{responseHeaders:s,value:i}=await sr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Qt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Xt,successfulResponseHandler:Pl(mk),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=this,l=this.config.provider.replace(".responses","");let c="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},m=[];let f=null;const p={},h=[];let v=!1;const _={};let w;return{stream:i.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,y){var b,S,$,k,I,P,L,N,j,D,F,ne,ue,ie,re,he,V,M,Z,U,T,x;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){c="error",y.enqueue({type:"error",error:g.error});return}const E=g.value;if(e2(E))E.item.type==="function_call"?(p[E.output_index]={toolName:E.item.name,toolCallId:E.item.call_id},y.enqueue({type:"tool-input-start",id:E.item.call_id,toolName:E.item.name})):E.item.type==="web_search_call"?(p[E.output_index]={toolName:n??"web_search",toolCallId:E.item.id},y.enqueue({type:"tool-input-start",id:E.item.id,toolName:n??"web_search",providerExecuted:!0}),y.enqueue({type:"tool-input-end",id:E.item.id}),y.enqueue({type:"tool-call",toolCallId:E.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):E.item.type==="computer_call"?(p[E.output_index]={toolName:"computer_use",toolCallId:E.item.id},y.enqueue({type:"tool-input-start",id:E.item.id,toolName:"computer_use",providerExecuted:!0})):E.item.type==="code_interpreter_call"?(p[E.output_index]={toolName:"code_interpreter",toolCallId:E.item.id,codeInterpreter:{containerId:E.item.container_id}},y.enqueue({type:"tool-input-start",id:E.item.id,toolName:"code_interpreter",providerExecuted:!0}),y.enqueue({type:"tool-input-delta",id:E.item.id,delta:`{"containerId":"${E.item.container_id}","code":"`})):E.item.type==="file_search_call"?y.enqueue({type:"tool-call",toolCallId:E.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):E.item.type==="image_generation_call"?y.enqueue({type:"tool-call",toolCallId:E.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):E.item.type==="message"?(h.splice(0,h.length),y.enqueue({type:"text-start",id:E.item.id,providerMetadata:{[l]:{itemId:E.item.id}}})):e2(E)&&E.item.type==="reasoning"&&(_[E.item.id]={encryptedContent:E.item.encrypted_content,summaryParts:{0:"active"}},y.enqueue({type:"reasoning-start",id:`${E.item.id}:0`,providerMetadata:{[l]:{itemId:E.item.id,reasoningEncryptedContent:(b=E.item.encrypted_content)!=null?b:null}}}));else if(bk(E)){if(E.item.type==="message")y.enqueue({type:"text-end",id:E.item.id,providerMetadata:{[l]:{itemId:E.item.id,...h.length>0&&{annotations:h}}}});else if(E.item.type==="function_call")p[E.output_index]=void 0,v=!0,y.enqueue({type:"tool-input-end",id:E.item.call_id}),y.enqueue({type:"tool-call",toolCallId:E.item.call_id,toolName:E.item.name,input:E.item.arguments,providerMetadata:{[l]:{itemId:E.item.id}}});else if(E.item.type==="web_search_call")p[E.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:n??"web_search",result:t2(E.item.action),providerExecuted:!0});else if(E.item.type==="computer_call")p[E.output_index]=void 0,y.enqueue({type:"tool-input-end",id:E.item.id}),y.enqueue({type:"tool-call",toolCallId:E.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),y.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:E.item.status||"completed"},providerExecuted:!0});else if(E.item.type==="file_search_call")p[E.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"file_search",result:{queries:E.item.queries,results:($=(S=E.item.results)==null?void 0:S.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?$:null},providerExecuted:!0});else if(E.item.type==="code_interpreter_call")p[E.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"code_interpreter",result:{outputs:E.item.outputs},providerExecuted:!0});else if(E.item.type==="image_generation_call")y.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"image_generation",result:{result:E.item.result},providerExecuted:!0});else if(E.item.type==="local_shell_call")p[E.output_index]=void 0,y.enqueue({type:"tool-call",toolCallId:E.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:E.item.action.command,timeoutMs:E.item.action.timeout_ms,user:E.item.action.user,workingDirectory:E.item.action.working_directory,env:E.item.action.env}}),providerMetadata:{[l]:{itemId:E.item.id}}});else if(E.item.type==="reasoning"){const H=_[E.item.id],W=Object.entries(H.summaryParts).filter(([fe,le])=>le==="active"||le==="can-conclude").map(([fe])=>fe);for(const fe of W)y.enqueue({type:"reasoning-end",id:`${E.item.id}:${fe}`,providerMetadata:{[l]:{itemId:E.item.id,reasoningEncryptedContent:(k=E.item.encrypted_content)!=null?k:null}}});delete _[E.item.id]}}else if(Ck(E)){const H=p[E.output_index];H!=null&&y.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:E.delta})}else if(kk(E)){const H=p[E.output_index];H!=null&&y.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:JSON.stringify(E.delta).slice(1,-1)})}else if(Ek(E)){const H=p[E.output_index];H!=null&&(y.enqueue({type:"tool-input-delta",id:H.toolCallId,delta:'"}'}),y.enqueue({type:"tool-input-end",id:H.toolCallId}),y.enqueue({type:"tool-call",toolCallId:H.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:E.code,containerId:H.codeInterpreter.containerId}),providerExecuted:!0}))}else if($k(E))f=E.response.id,y.enqueue({type:"response-metadata",id:E.response.id,timestamp:new Date(E.response.created_at*1e3),modelId:E.response.model});else if(wk(E))y.enqueue({type:"text-delta",id:E.item_id,delta:E.delta}),(P=(I=e.providerOptions)==null?void 0:I.openai)!=null&&P.logprobs&&E.logprobs&&m.push(E.logprobs);else if(E.type==="response.reasoning_summary_part.added"){if(E.summary_index>0){const H=_[E.item_id];H.summaryParts[E.summary_index]="active";for(const W of Object.keys(H.summaryParts))H.summaryParts[W]==="can-conclude"&&(y.enqueue({type:"reasoning-end",id:`${E.item_id}:${W}`,providerMetadata:{[l]:{itemId:E.item_id}}}),H.summaryParts[W]="concluded");y.enqueue({type:"reasoning-start",id:`${E.item_id}:${E.summary_index}`,providerMetadata:{[l]:{itemId:E.item_id,reasoningEncryptedContent:(N=(L=_[E.item_id])==null?void 0:L.encryptedContent)!=null?N:null}}})}}else E.type==="response.reasoning_summary_text.delta"?y.enqueue({type:"reasoning-delta",id:`${E.item_id}:${E.summary_index}`,delta:E.delta,providerMetadata:{[l]:{itemId:E.item_id}}}):E.type==="response.reasoning_summary_part.done"?o?(y.enqueue({type:"reasoning-end",id:`${E.item_id}:${E.summary_index}`,providerMetadata:{[l]:{itemId:E.item_id}}}),_[E.item_id].summaryParts[E.summary_index]="concluded"):_[E.item_id].summaryParts[E.summary_index]="can-conclude":Sk(E)?(c=Qm({finishReason:(j=E.response.incomplete_details)==null?void 0:j.reason,hasFunctionCall:v}),u.inputTokens=E.response.usage.input_tokens,u.outputTokens=E.response.usage.output_tokens,u.totalTokens=E.response.usage.input_tokens+E.response.usage.output_tokens,u.reasoningTokens=(F=(D=E.response.usage.output_tokens_details)==null?void 0:D.reasoning_tokens)!=null?F:void 0,u.cachedInputTokens=(ue=(ne=E.response.usage.input_tokens_details)==null?void 0:ne.cached_tokens)!=null?ue:void 0,typeof E.response.service_tier=="string"&&(w=E.response.service_tier)):Tk(E)?(h.push(E.annotation),E.annotation.type==="url_citation"?y.enqueue({type:"source",sourceType:"url",id:(he=(re=(ie=a.config).generateId)==null?void 0:re.call(ie))!=null?he:Lt(),url:E.annotation.url,title:E.annotation.title}):E.annotation.type==="file_citation"&&y.enqueue({type:"source",sourceType:"document",id:(Z=(M=(V=a.config).generateId)==null?void 0:M.call(V))!=null?Z:Lt(),mediaType:"text/plain",title:(T=(U=E.annotation.quote)!=null?U:E.annotation.filename)!=null?T:"Document",filename:(x=E.annotation.filename)!=null?x:E.annotation.file_id,...E.annotation.file_id?{providerMetadata:{[l]:{fileId:E.annotation.file_id}}}:{}})):Ik(E)&&y.enqueue({type:"error",error:E})},flush(g){const y={[l]:{responseId:f}};m.length>0&&(y[l].logprobs=m),w!==void 0&&(y[l].serviceTier=w),g.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:y})}})),request:{body:t},response:{headers:s}}}};function wk(e){return e.type==="response.output_text.delta"}function bk(e){return e.type==="response.output_item.done"}function Sk(e){return e.type==="response.completed"||e.type==="response.incomplete"}function $k(e){return e.type==="response.created"}function Ck(e){return e.type==="response.function_call_arguments.delta"}function kk(e){return e.type==="response.code_interpreter_call_code.delta"}function Ek(e){return e.type==="response.code_interpreter_call_code.done"}function e2(e){return e.type==="response.output_item.added"}function Tk(e){return e.type==="response.output_text.annotation.added"}function Ik(e){return e.type==="error"}function t2(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}}}}var Rk=at(()=>Ee(C({instructions:d().nullish(),speed:A().min(.25).max(4).default(1).nullish()}))),xk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:i}){const a=[],l=await br({provider:"openai",providerOptions:i,schema:Rk}),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:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const m in u){const f=u[m];f!==void 0&&(c[m]=f)}}return s&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:a}}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:i}=await this.getArgs(e),{value:a,responseHeaders:l,rawValue:c}=await sr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Qt(this.config.headers(),e.headers),body:s,failedResponseHandler:Xt,successfulResponseHandler:R8(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},Pk=at(()=>Ee(C({text:d(),language:d().nullish(),duration:A().nullish(),words:R(C({word:d(),start:A(),end:A()})).nullish(),segments:R(C({id:A(),seek:A(),start:A(),end:A(),text:d(),tokens:R(A()),temperature:A(),avg_logprob:A(),compression_ratio:A(),no_speech_prob:A()})).nullish()}))),Ok=at(()=>Ee(C({include:R(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:A().min(0).max(1).default(0).optional(),timestampGranularities:R(_e(["word","segment"])).default(["segment"]).optional()}))),r2={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Mk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await br({provider:"openai",providerOptions:r,schema:Ok}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([$C(e)]);s.append("model",this.modelId);const a=g8(t);if(s.append("file",new File([i],"audio",{type:t}),`audio.${a}`),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,i,a,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:f,responseHeaders:p,rawValue:h}=await T8({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Qt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Xt,successfulResponseHandler:_n(Pk),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=f.language!=null&&f.language in r2?r2[f.language]:void 0;return{text:f.text,segments:(a=(i=(o=f.segments)==null?void 0:o.map(_=>({text:_.text,startSecond:_.start,endSecond:_.end})))!=null?i:(s=f.words)==null?void 0:s.map(_=>({text:_.word,startSecond:_.start,endSecond:_.end})))!=null?a:[],language:v,durationInSeconds:(l=f.duration)!=null?l:void 0,warnings:m,response:{timestamp:c,modelId:this.modelId,headers:p,body:h}}}},Ak="2.0.89";function n2(e={}){var t,r;const n=(t=kC(m8({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>xm({Authorization:`Bearer ${f8({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Ak}`),i=v=>new PC(v,{provider:`${o}.chat`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),a=v=>new NC(v,{provider:`${o}.completion`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),l=v=>new UC(v,{provider:`${o}.embedding`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),c=v=>new ZC(v,{provider:`${o}.image`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),u=v=>new Mk(v,{provider:`${o}.transcription`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),m=v=>new xk(v,{provider:`${o}.speech`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch}),f=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return p(v)},p=v=>new yk(v,{provider:`${o}.responses`,url:({path:_})=>`${n}${_}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),h=function(v){return f(v)};return h.languageModel=f,h.chat=i,h.completion=a,h.responses=p,h.embedding=l,h.textEmbedding=l,h.textEmbeddingModel=l,h.image=c,h.imageModel=c,h.transcription=u,h.transcriptionModel=u,h.speech=m,h.speechModel=m,h.tools=pk,h}n2();function co(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function Nk(e){const t=[];for(const{role:r,content:n,...o}of e){const s=co({...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,...co(n[0])});break}t.push({role:"user",content:n.map(i=>{const a=co(i);switch(i.type){case"text":return{type:"text",text:i.text,...a};case"file":if(i.mediaType.startsWith("image/")){const l=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${l};base64,${Z3(i.data)}`},...a}}else throw new id({functionality:`file part media type ${i.mediaType}`})}}),...s});break}case"assistant":{let i="";const a=[];for(const l of n){const c=co(l);switch(l.type){case"text":{i+=l.text;break}case"tool-call":{a.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:i,tool_calls:a.length>0?a:void 0,...s});break}case"tool":{for(const i of n){const a=i.output;let l;switch(a.type){case"text":case"error-text":l=a.value;break;case"content":case"json":case"error-json":l=JSON.stringify(a.value);break}const c=co(i);t.push({role:"tool",tool_call_id:i.toolCallId,content:l,...c})}break}default:{const i=r;throw new Error(`Unsupported role: ${i}`)}}}return t}function o2({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 s2(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 Ll=C({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),qk=C({error:C({message:d(),type:d().nullish(),param:tt().nullish(),code:X([d(),A()]).nullish()})}),Lk={errorSchema:qk,errorToMessage:e=>e.error.message};function Uk({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 id({functionality:`tool choice type: ${s}`})}}}var jk=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:Lk;this.chunkSchema=zk(o.errorSchema),this.failedResponseHandler=qr(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:i,providerOptions:a,stopSequences:l,responseFormat:c,seed:u,toolChoice:m,tools:f}){var p,h,v,_;const w=[],g=Object.assign((p=await gp({provider:"openai-compatible",providerOptions:a,schema:Ll}))!=null?p:{},(h=await gp({provider:this.providerOptionsName,providerOptions:a,schema:Ll}))!=null?h:{});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:y,toolChoice:b,toolWarnings:S}=Uk({tools:f,toolChoice:m});return{args:{model:this.modelId,user:g.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:i,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((_=a?.[this.providerOptionsName])!=null?_:{}).filter(([$])=>!Object.keys(Ll.shape).includes($))),reasoning_effort:g.reasoningEffort,verbosity:g.textVerbosity,messages:Nk(e),tools:y,tool_choice:b},warnings:[...w,...S]}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,m,f,p,h,v,_,w;const{args:g,warnings:y}=await this.getArgs({...e}),b=JSON.stringify(g),{responseHeaders:S,value:$,rawValue:k}=await nn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:tn(this.config.headers(),e.headers),body:g,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:on(Dk),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=$.choices[0],P=[],L=I.message.content;L!=null&&L.length>0&&P.push({type:"text",text:L});const N=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(N!=null&&N.length>0&&P.push({type:"reasoning",text:N}),I.message.tool_calls!=null)for(const F of I.message.tool_calls)P.push({type:"tool-call",toolCallId:(r=F.id)!=null?r:Bn(),toolName:F.function.name,input:F.function.arguments});const j={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:k}))},D=(s=$.usage)==null?void 0:s.completion_tokens_details;return D?.accepted_prediction_tokens!=null&&(j[this.providerOptionsName].acceptedPredictionTokens=D?.accepted_prediction_tokens),D?.rejected_prediction_tokens!=null&&(j[this.providerOptionsName].rejectedPredictionTokens=D?.rejected_prediction_tokens),{content:P,finishReason:s2(I.finish_reason),usage:{inputTokens:(a=(i=$.usage)==null?void 0:i.prompt_tokens)!=null?a:void 0,outputTokens:(c=(l=$.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(m=(u=$.usage)==null?void 0:u.total_tokens)!=null?m:void 0,reasoningTokens:(h=(p=(f=$.usage)==null?void 0:f.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?h:void 0,cachedInputTokens:(w=(_=(v=$.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:_.cached_tokens)!=null?w:void 0},providerMetadata:j,request:{body:b},response:{...o2($),headers:S,body:k},warnings:y}}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:i,value:a}=await nn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:tn(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:vp(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 f=this.providerOptionsName;let p=!1,h=!1;return{stream:a.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,_){var w,g,y,b,S,$,k,I,P,L,N,j,D;if(e.includeRawChunks&&_.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",_.enqueue({type:"error",error:v.error});return}const F=v.value;if(s?.processChunk(v.rawValue),"error"in F){c="error",_.enqueue({type:"error",error:F.error.message});return}if(m&&(m=!1,_.enqueue({type:"response-metadata",...o2(F)})),F.usage!=null){const{prompt_tokens:re,completion_tokens:he,total_tokens:V,prompt_tokens_details:M,completion_tokens_details:Z}=F.usage;u.promptTokens=re??void 0,u.completionTokens=he??void 0,u.totalTokens=V??void 0,Z?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=Z?.reasoning_tokens),Z?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=Z?.accepted_prediction_tokens),Z?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=Z?.rejected_prediction_tokens),M?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=M?.cached_tokens)}const ne=F.choices[0];if(ne?.finish_reason!=null&&(c=s2(ne.finish_reason)),ne?.delta==null)return;const ue=ne.delta,ie=(w=ue.reasoning_content)!=null?w:ue.reasoning;if(ie&&(p||(_.enqueue({type:"reasoning-start",id:"reasoning-0"}),p=!0),_.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ie})),ue.content&&(h||(_.enqueue({type:"text-start",id:"txt-0"}),h=!0),_.enqueue({type:"text-delta",id:"txt-0",delta:ue.content})),ue.tool_calls!=null)for(const re of ue.tool_calls){const he=re.index;if(l[he]==null){if(re.id==null)throw new Vu({data:re,message:"Expected 'id' to be a string."});if(((g=re.function)==null?void 0:g.name)==null)throw new Vu({data:re,message:"Expected 'function.name' to be a string."});_.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),l[he]={id:re.id,type:"function",function:{name:re.function.name,arguments:(y=re.function.arguments)!=null?y:""},hasFinished:!1};const M=l[he];((b=M.function)==null?void 0:b.name)!=null&&((S=M.function)==null?void 0:S.arguments)!=null&&(M.function.arguments.length>0&&_.enqueue({type:"tool-input-delta",id:M.id,delta:M.function.arguments}),mp(M.function.arguments)&&(_.enqueue({type:"tool-input-end",id:M.id}),_.enqueue({type:"tool-call",toolCallId:($=M.id)!=null?$:Bn(),toolName:M.function.name,input:M.function.arguments}),M.hasFinished=!0));continue}const V=l[he];V.hasFinished||(((k=re.function)==null?void 0:k.arguments)!=null&&(V.function.arguments+=(P=(I=re.function)==null?void 0:I.arguments)!=null?P:""),_.enqueue({type:"tool-input-delta",id:V.id,delta:(L=re.function.arguments)!=null?L:""}),((N=V.function)==null?void 0:N.name)!=null&&((j=V.function)==null?void 0:j.arguments)!=null&&mp(V.function.arguments)&&(_.enqueue({type:"tool-input-end",id:V.id}),_.enqueue({type:"tool-call",toolCallId:(D=V.id)!=null?D:Bn(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(v){var _,w,g,y,b,S;p&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),h&&v.enqueue({type:"text-end",id:"txt-0"});for(const k of l.filter(I=>!I.hasFinished))v.enqueue({type:"tool-input-end",id:k.id}),v.enqueue({type:"tool-call",toolCallId:(_=k.id)!=null?_:Bn(),toolName:k.function.name,input:k.function.arguments});const $={[f]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&($[f].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&($[f].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(g=u.completionTokens)!=null?g:void 0,totalTokens:(y=u.totalTokens)!=null?y:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(S=u.promptTokensDetails.cachedTokens)!=null?S:void 0},providerMetadata:$})}})),request:{body:o},response:{headers:i}}}},a2=C({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:C({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish(),Dk=C({id:d().nullish(),created:A().nullish(),model:d().nullish(),choices:R(C({message:C({role:O("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:R(C({id:d().nullish(),function:C({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:a2}),zk=e=>X([C({id:d().nullish(),created:A().nullish(),model:d().nullish(),choices:R(C({delta:C({role:_e(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:R(C({index:A(),id:d().nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:a2}),e]);C({echo:te().optional(),logitBias:oe(d(),A()).optional(),suffix:d().optional(),user:d().optional()});var Zk=C({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()});C({id:d().nullish(),created:A().nullish(),model:d().nullish(),choices:R(C({text:d(),finish_reason:d()})),usage:Zk.nullish()}),C({dimensions:A().optional(),user:d().optional()}),C({data:R(C({embedding:R(A())})),usage:C({prompt_tokens:A()}).nullish(),providerMetadata:oe(d(),oe(d(),tt())).optional()}),C({data:R(C({b64_json:d()}))});var i2=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}}},Fk={extractMetadata:async({parsedBody:e})=>{const t=await Pt({value:e,schema:Vk});return!t.success||t.value.usage==null?void 0:i2(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Pt({value:t,schema:Hk});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:()=>i2(e)}}},l2=C({prompt_cache_hit_tokens:A().nullish(),prompt_cache_miss_tokens:A().nullish()}),Vk=C({usage:l2.nullish()}),Hk=C({choices:R(C({finish_reason:d().nullish()})).nullish(),usage:l2.nullish()}),Bk="1.0.30";function c2(e={}){var t;const r=kp((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>vr({Authorization:`Bearer ${Lb({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${Bk}`);class o extends jk{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const f=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:f}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=a=>new o(a,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:Fk}),i=a=>s(a);return i.languageModel=s,i.chat=s,i.textEmbeddingModel=a=>{throw new ed({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new ed({modelId:a,modelType:"imageModel"})},i}c2();const Jk=(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})},Wk=(e,t,r,n)=>{const o=(s,i,a)=>{if(s.type===e&&s.direction===r){const{data:l}=s;t(l,i,a),a(i)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class Gk{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=Wk("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=pn.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];Jk("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】 关闭时发生错误")}}}const Ts="2025-11-25",Kk=[Ts,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zr="io.modelcontextprotocol/related-task",Is="2.0",We=di(e=>e!==null&&(typeof e=="object"||typeof e=="function")),u2=X([d(),A().int()]),d2=d();Ce({ttl:X([A(),ii()]).optional(),pollInterval:A().optional()});const Yk=C({ttl:A().optional()}),Qk=C({taskId:d()}),Ul=Ce({progressToken:u2.optional(),[Zr]:Qk.optional()}),St=C({_meta:Ul.optional()}),uo=St.extend({task:Yk.optional()}),Xk=e=>uo.safeParse(e).success,Ge=C({method:d(),params:St.loose().optional()}),Tt=C({_meta:Ul.optional()}),It=C({method:d(),params:Tt.loose().optional()}),Ke=Ce({_meta:Ul.optional()}),Rs=X([d(),A().int()]),p2=C({jsonrpc:O(Is),id:Rs,...Ge.shape}).strict(),jl=e=>p2.safeParse(e).success,h2=C({jsonrpc:O(Is),...It.shape}).strict(),e7=e=>h2.safeParse(e).success,Dl=C({jsonrpc:O(Is),id:Rs,result:Ke}).strict(),po=e=>Dl.safeParse(e).success;var ye;(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"})(ye||(ye={}));const zl=C({jsonrpc:O(Is),id:Rs.optional(),error:C({code:A().int(),message:d(),data:ce().optional()})}).strict(),t7=e=>zl.safeParse(e).success,yn=X([p2,h2,Dl,zl]);X([Dl,zl]);const Fr=Ke.strict(),r7=Tt.extend({requestId:Rs.optional(),reason:d().optional()}),Zl=It.extend({method:O("notifications/cancelled"),params:r7}),n7=C({src:d(),mimeType:d().optional(),sizes:R(d()).optional(),theme:_e(["light","dark"]).optional()}),ho=C({icons:R(n7).optional()}),wn=C({name:d(),title:d().optional()}),f2=wn.extend({...wn.shape,...ho.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),o7=Fn(C({applyDefaults:te().optional()}),oe(d(),ce())),s7=pi(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Fn(C({form:o7.optional(),url:We.optional()}),oe(d(),ce()).optional())),a7=Ce({list:We.optional(),cancel:We.optional(),requests:Ce({sampling:Ce({createMessage:We.optional()}).optional(),elicitation:Ce({create:We.optional()}).optional()}).optional()}),i7=Ce({list:We.optional(),cancel:We.optional(),requests:Ce({tools:Ce({call:We.optional()}).optional()}).optional()}),l7=C({experimental:oe(d(),We).optional(),sampling:C({context:We.optional(),tools:We.optional()}).optional(),elicitation:s7.optional(),roots:C({listChanged:te().optional()}).optional(),tasks:a7.optional()}),c7=St.extend({protocolVersion:d(),capabilities:l7,clientInfo:f2}),u7=Ge.extend({method:O("initialize"),params:c7}),d7=C({experimental:oe(d(),We).optional(),logging:We.optional(),completions:We.optional(),prompts:C({listChanged:te().optional()}).optional(),resources:C({subscribe:te().optional(),listChanged:te().optional()}).optional(),tools:C({listChanged:te().optional()}).optional(),tasks:i7.optional()}),m2=Ke.extend({protocolVersion:d(),capabilities:d7,serverInfo:f2,instructions:d().optional()}),g2=It.extend({method:O("notifications/initialized"),params:Tt.optional()}),p7=e=>g2.safeParse(e).success,Fl=Ge.extend({method:O("ping"),params:St.optional()}),h7=C({progress:A(),total:K(A()),message:K(d())}),f7=C({...Tt.shape,...h7.shape,progressToken:u2}),Vl=It.extend({method:O("notifications/progress"),params:f7}),m7=St.extend({cursor:d2.optional()}),fo=Ge.extend({params:m7.optional()}),mo=Ke.extend({nextCursor:d2.optional()}),g7=_e(["working","input_required","completed","failed","cancelled"]),go=C({taskId:d(),status:g7,ttl:X([A(),ii()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:K(A()),statusMessage:K(d())}),_o=Ke.extend({task:go}),_7=Tt.merge(go),xs=It.extend({method:O("notifications/tasks/status"),params:_7}),Hl=Ge.extend({method:O("tasks/get"),params:St.extend({taskId:d()})}),Bl=Ke.merge(go),Jl=Ge.extend({method:O("tasks/result"),params:St.extend({taskId:d()})});Ke.loose();const Wl=fo.extend({method:O("tasks/list")}),Gl=mo.extend({tasks:R(go)}),Kl=Ge.extend({method:O("tasks/cancel"),params:St.extend({taskId:d()})}),v7=Ke.merge(go),_2=C({uri:d(),mimeType:K(d()),_meta:oe(d(),ce()).optional()}),v2=_2.extend({text:d()}),Yl=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),y2=_2.extend({blob:Yl}),vo=_e(["user","assistant"]),bn=C({audience:R(vo).optional(),priority:A().min(0).max(1).optional(),lastModified:Wd({offset:!0}).optional()}),w2=C({...wn.shape,...ho.shape,uri:d(),description:K(d()),mimeType:K(d()),annotations:bn.optional(),_meta:K(Ce({}))}),y7=C({...wn.shape,...ho.shape,uriTemplate:d(),description:K(d()),mimeType:K(d()),annotations:bn.optional(),_meta:K(Ce({}))}),w7=fo.extend({method:O("resources/list")}),b2=mo.extend({resources:R(w2)}),b7=fo.extend({method:O("resources/templates/list")}),S2=mo.extend({resourceTemplates:R(y7)}),Ql=St.extend({uri:d()}),S7=Ql,$7=Ge.extend({method:O("resources/read"),params:S7}),$2=Ke.extend({contents:R(X([v2,y2]))}),C2=It.extend({method:O("notifications/resources/list_changed"),params:Tt.optional()}),C7=Ql,k7=Ge.extend({method:O("resources/subscribe"),params:C7}),E7=Ql,T7=Ge.extend({method:O("resources/unsubscribe"),params:E7}),I7=Tt.extend({uri:d()}),R7=It.extend({method:O("notifications/resources/updated"),params:I7}),x7=C({name:d(),description:K(d()),required:K(te())}),P7=C({...wn.shape,...ho.shape,description:K(d()),arguments:K(R(x7)),_meta:K(Ce({}))}),O7=fo.extend({method:O("prompts/list")}),k2=mo.extend({prompts:R(P7)}),M7=St.extend({name:d(),arguments:oe(d(),d()).optional()}),A7=Ge.extend({method:O("prompts/get"),params:M7}),Xl=C({type:O("text"),text:d(),annotations:bn.optional(),_meta:oe(d(),ce()).optional()}),ec=C({type:O("image"),data:Yl,mimeType:d(),annotations:bn.optional(),_meta:oe(d(),ce()).optional()}),tc=C({type:O("audio"),data:Yl,mimeType:d(),annotations:bn.optional(),_meta:oe(d(),ce()).optional()}),N7=C({type:O("tool_use"),name:d(),id:d(),input:oe(d(),ce()),_meta:oe(d(),ce()).optional()}),q7=C({type:O("resource"),resource:X([v2,y2]),annotations:bn.optional(),_meta:oe(d(),ce()).optional()}),L7=w2.extend({type:O("resource_link")}),rc=X([Xl,ec,tc,L7,q7]),U7=C({role:vo,content:rc}),E2=Ke.extend({description:d().optional(),messages:R(U7)}),T2=It.extend({method:O("notifications/prompts/list_changed"),params:Tt.optional()}),j7=C({title:d().optional(),readOnlyHint:te().optional(),destructiveHint:te().optional(),idempotentHint:te().optional(),openWorldHint:te().optional()}),D7=C({taskSupport:_e(["required","optional","forbidden"]).optional()}),I2=C({...wn.shape,...ho.shape,description:d().optional(),inputSchema:C({type:O("object"),properties:oe(d(),We).optional(),required:R(d()).optional()}).catchall(ce()),outputSchema:C({type:O("object"),properties:oe(d(),We).optional(),required:R(d()).optional()}).catchall(ce()).optional(),annotations:j7.optional(),execution:D7.optional(),_meta:oe(d(),ce()).optional()}),z7=fo.extend({method:O("tools/list")}),R2=mo.extend({tools:R(I2)}),Ps=Ke.extend({content:R(rc).default([]),structuredContent:oe(d(),ce()).optional(),isError:te().optional()});Ps.or(Ke.extend({toolResult:ce()}));const Z7=uo.extend({name:d(),arguments:oe(d(),ce()).optional()}),F7=Ge.extend({method:O("tools/call"),params:Z7}),x2=It.extend({method:O("notifications/tools/list_changed"),params:Tt.optional()}),V7=C({autoRefresh:te().default(!0),debounceMs:A().int().nonnegative().default(300)}),P2=_e(["debug","info","notice","warning","error","critical","alert","emergency"]),H7=St.extend({level:P2}),B7=Ge.extend({method:O("logging/setLevel"),params:H7}),J7=Tt.extend({level:P2,logger:d().optional(),data:ce()}),W7=It.extend({method:O("notifications/message"),params:J7}),G7=C({name:d().optional()}),K7=C({hints:R(G7).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),Y7=C({mode:_e(["auto","required","none"]).optional()}),Q7=C({type:O("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:R(rc).default([]),structuredContent:C({}).loose().optional(),isError:te().optional(),_meta:oe(d(),ce()).optional()}),X7=De("type",[Xl,ec,tc]),Os=De("type",[Xl,ec,tc,N7,Q7]),eE=C({role:vo,content:X([Os,R(Os)]),_meta:oe(d(),ce()).optional()}),tE=uo.extend({messages:R(eE),modelPreferences:K7.optional(),systemPrompt:d().optional(),includeContext:_e(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:R(d()).optional(),metadata:We.optional(),tools:R(I2).optional(),toolChoice:Y7.optional()}),O2=Ge.extend({method:O("sampling/createMessage"),params:tE}),nc=Ke.extend({model:d(),stopReason:K(_e(["endTurn","stopSequence","maxTokens"]).or(d())),role:vo,content:X7}),rE=Ke.extend({model:d(),stopReason:K(_e(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:vo,content:X([Os,R(Os)])}),nE=C({type:O("boolean"),title:d().optional(),description:d().optional(),default:te().optional()}),oE=C({type:O("string"),title:d().optional(),description:d().optional(),minLength:A().optional(),maxLength:A().optional(),format:_e(["email","uri","date","date-time"]).optional(),default:d().optional()}),sE=C({type:_e(["number","integer"]),title:d().optional(),description:d().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),aE=C({type:O("string"),title:d().optional(),description:d().optional(),enum:R(d()),default:d().optional()}),iE=C({type:O("string"),title:d().optional(),description:d().optional(),oneOf:R(C({const:d(),title:d()})),default:d().optional()}),lE=C({type:O("string"),title:d().optional(),description:d().optional(),enum:R(d()),enumNames:R(d()).optional(),default:d().optional()}),cE=X([aE,iE]),uE=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:A().optional(),maxItems:A().optional(),items:C({type:O("string"),enum:R(d())}),default:R(d()).optional()}),dE=C({type:O("array"),title:d().optional(),description:d().optional(),minItems:A().optional(),maxItems:A().optional(),items:C({anyOf:R(C({const:d(),title:d()}))}),default:R(d()).optional()}),pE=X([uE,dE]),hE=X([lE,cE,pE]),fE=X([hE,nE,oE,sE]),mE=uo.extend({mode:O("form").optional(),message:d(),requestedSchema:C({type:O("object"),properties:oe(d(),fE),required:R(d()).optional()})}),gE=uo.extend({mode:O("url"),message:d(),elicitationId:d(),url:d().url()}),_E=X([mE,gE]),M2=Ge.extend({method:O("elicitation/create"),params:_E}),vE=Tt.extend({elicitationId:d()}),yE=It.extend({method:O("notifications/elicitation/complete"),params:vE}),oc=Ke.extend({action:_e(["accept","decline","cancel"]),content:pi(e=>e===null?void 0:e,oe(d(),X([d(),A(),te(),R(d())])).optional())}),wE=C({type:O("ref/resource"),uri:d()}),bE=C({type:O("ref/prompt"),name:d()}),SE=St.extend({ref:X([bE,wE]),argument:C({name:d(),value:d()}),context:C({arguments:oe(d(),d()).optional()}).optional()}),$E=Ge.extend({method:O("completion/complete"),params:SE}),A2=Ke.extend({completion:Ce({values:R(d()).max(100),total:K(A().int()),hasMore:K(te())})}),CE=C({uri:d().startsWith("file://"),name:d().optional(),_meta:oe(d(),ce()).optional()}),kE=Ge.extend({method:O("roots/list"),params:St.optional()}),N2=Ke.extend({roots:R(CE)}),EE=It.extend({method:O("notifications/roots/list_changed"),params:Tt.optional()});X([Fl,u7,$E,B7,A7,O7,w7,b7,$7,k7,T7,F7,z7,Hl,Jl,Wl,Kl]),X([Zl,Vl,g2,EE,xs]),X([Fr,nc,rE,oc,N2,Bl,Gl,_o]),X([Fl,O2,M2,kE,Hl,Jl,Wl,Kl]),X([Zl,Vl,W7,R7,C2,x2,T2,xs,yE]),X([Fr,m2,A2,E2,k2,b2,S2,$2,Ps,R2,Bl,Gl,_o]);class pe 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===ye.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new TE(o.elicitations,r)}return new pe(t,r,n)}}class TE extends pe{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ye.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}function Ms(e){return!!e._zod}function Sr(e,t){return Ms(e)?ei(e,t):e.safeParse(t)}function q2(e){if(!e)return;let t;if(Ms(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function IE(e){if(Ms(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 Vr(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function L2(e){const r=q2(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=IE(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function U2(e,t){const r=Sr(e,t);if(!r.success)throw r.error;return r.data}const RE=6e4;let xE=class{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(Zl,r=>{this._oncancel(r)}),this.setNotificationHandler(Vl,r=>{this._onprogress(r)}),this.setRequestHandler(Fl,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Hl,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new pe(ye.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Jl,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){const l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{const m=l,f=new pe(m.error.code,m.error.message,m.error.data);u(f)}else{const m=a.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new pe(ye.InvalidParams,`Task not found: ${s}`);if(!Vr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Vr(i.status)){const a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Zr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Wl,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 pe(ye.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Kl,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new pe(ye.InvalidParams,`Task not found: ${r.params.taskId}`);if(Vr(o.status))throw new pe(ye.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 pe(ye.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof pe?o:new pe(ye.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),pe.fromError(ye.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,i)=>{o?.(s,i),po(s)||t7(s)?this._onresponse(s):jl(s)?this._onrequest(s,i):e7(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=pe.fromError(ye.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?.[Zr]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:ye.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 i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const a=Xk(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:i.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,f)=>{const p={...f,relatedRequestId:t.id};s&&!p.relatedTask&&(p.relatedTask={taskId:s});const h=p.relatedTask?.taskId??s;return h&&l&&await l.updateTaskStatus(h,"input_required"),await this.request(u,m,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(i.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(i.signal.aborted)return;const m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:ye.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 i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),po(t))n(t);else{const i=new pe(t.error.code,t.error.message,t.error.data);n(i)}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(po(t)&&t.result&&typeof t.result=="object"){const i=t.result;if(i.task&&typeof i.task=="object"){const a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),po(t))o(t);else{const i=pe.fromError(t.error.code,t.error.message,t.error.data);o(i)}}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(i){yield{type:"error",error:i instanceof pe?i:new pe(ye.InternalError,String(i))}}return}let s;try{const i=await this.request(t,_o,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new pe(ye.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Vr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new pe(ye.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new pe(ye.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof pe?i:new pe(ye.InternalError,String(i))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{const m=g=>{u(g)};if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(g){m(g);return}n?.signal?.throwIfAborted();const f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),l&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Zr]:l}});const h=g=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(g)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));const y=g instanceof pe?g:new pe(ye.RequestTimeout,String(g));u(y)};this._responseHandlers.set(f,g=>{if(!n?.signal?.aborted){if(g instanceof Error)return u(g);try{const y=Sr(r,g.result);y.success?c(y.data):u(y.error)}catch(y){u(y)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});const v=n?.timeout??RE,_=()=>h(pe.fromError(ye.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(f,v,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const g=y=>{const b=this._responseHandlers.get(f);b?b(y):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,g),this._enqueueTaskMessage(w,{type:"request",message:p,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(f),u(y)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(g=>{this._cleanupTimeout(f),u(g)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Bl,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},Gl,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},v7,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 a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Zr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,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 a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Zr]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Zr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=L2(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const i=U2(t,o);return Promise.resolve(r(i,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=L2(t);this._notificationHandlers.set(n,o=>{const s=U2(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"&&jl(o.message)){const s=o.message.id,i=this._requestResolvers.get(s);i?(i(new pe(ye.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 pe(ye.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new pe(ye.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 pe(ye.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);const a=await n.getTask(o,r);if(a){const l=xs.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Vr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{const a=await n.getTask(o,r);if(!a)throw new pe(ye.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Vr(a.status))throw new pe(ye.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);const l=await n.getTask(o,r);if(l){const c=xs.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Vr(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function j2(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function PE(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const i=r[o];j2(i)&&j2(s)?r[o]={...i,...s}:r[o]=s}return r}var As={exports:{}},sc={},ar={},Hr={},ac={},ic={},lc={},D2;function Ns(){return D2||(D2=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(g){if(super(),!e.IDENTIFIER.test(g))throw new Error("CodeGen: name must be a valid identifier");this.str=g}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(g){super(),this._items=typeof g=="string"?[g]:g}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const g=this._items[0];return g===""||g==='""'}get str(){var g;return(g=this._str)!==null&&g!==void 0?g:this._str=this._items.reduce((y,b)=>`${y}${b}`,"")}get names(){var g;return(g=this._names)!==null&&g!==void 0?g:this._names=this._items.reduce((y,b)=>(b instanceof r&&(y[b.str]=(y[b.str]||0)+1),y),{})}}e._Code=n,e.nil=new n("");function o(w,...g){const y=[w[0]];let b=0;for(;b<g.length;)a(y,g[b]),y.push(w[++b]);return new n(y)}e._=o;const s=new n("+");function i(w,...g){const y=[p(w[0])];let b=0;for(;b<g.length;)y.push(s),a(y,g[b]),y.push(s,p(w[++b]));return l(y),new n(y)}e.str=i;function a(w,g){g instanceof n?w.push(...g._items):g instanceof r?w.push(g):w.push(m(g))}e.addCodeArg=a;function l(w){let g=1;for(;g<w.length-1;){if(w[g]===s){const y=c(w[g-1],w[g+1]);if(y!==void 0){w.splice(g-1,3,y);continue}w[g++]="+"}g++}}function c(w,g){if(g==='""')return w;if(w==='""')return g;if(typeof w=="string")return g instanceof r||w[w.length-1]!=='"'?void 0:typeof g!="string"?`${w.slice(0,-1)}${g}"`:g[0]==='"'?w.slice(0,-1)+g.slice(1):void 0;if(typeof g=="string"&&g[0]==='"'&&!(w instanceof r))return`"${w}${g.slice(1)}`}function u(w,g){return g.emptyStr()?w:w.emptyStr()?g:i`${w}${g}`}e.strConcat=u;function m(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:p(Array.isArray(w)?w.join(","):w)}function f(w){return new n(p(w))}e.stringify=f;function p(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=p;function h(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=h;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 _(w){return new n(w.toString())}e.regexpCode=_})(lc)),lc}var cc={},z2;function Z2(){return z2||(z2=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Ns();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 i=(0,t._)`\n`;class a extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?i: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 f=this.toName(c),{prefix:p}=f,h=(m=u.key)!==null&&m!==void 0?m:u.ref;let v=this._values[p];if(v){const g=v.get(h);if(g)return g}else v=this._values[p]=new Map;v.set(h,f);const _=this._scope[p]||(this._scope[p]=[]),w=_.length;return _[w]=u.ref,f.setValue(u,{property:p,itemIndex:w}),f}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,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},u,m)}_reduceValues(c,u,m={},f){let p=t.nil;for(const h in c){const v=c[h];if(!v)continue;const _=m[h]=m[h]||new Map;v.forEach(w=>{if(_.has(w))return;_.set(w,n.Started);let g=u(w);if(g){const y=this.opts.es5?e.varKinds.var:e.varKinds.const;p=(0,t._)`${p}${y} ${w} = ${g};${this.opts._n}`}else if(g=f?.(w))p=(0,t._)`${p}${g}${this.opts._n}`;else throw new r(w);_.set(w,n.Completed)})}return p}}e.ValueScope=a})(cc)),cc}var F2;function we(){return F2||(F2=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=Ns(),r=Z2();var n=Ns();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=Z2();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(T,x){return this}}class i extends s{constructor(T,x,E){super(),this.varKind=T,this.name=x,this.rhs=E}render({es5:T,_n:x}){const E=T?r.varKinds.var:this.varKind,H=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${H};`+x}optimizeNames(T,x){if(T[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,T,x)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(T,x,E){super(),this.lhs=T,this.rhs=x,this.sideEffects=E}render({_n:T}){return`${this.lhs} = ${this.rhs};`+T}optimizeNames(T,x){if(!(this.lhs instanceof t.Name&&!T[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,T,x),this}get names(){const T=this.lhs instanceof t.Name?{}:{...this.lhs.names};return D(T,this.rhs)}}class l extends a{constructor(T,x,E,H){super(T,E,H),this.op=x}render({_n:T}){return`${this.lhs} ${this.op}= ${this.rhs};`+T}}class c extends s{constructor(T){super(),this.label=T,this.names={}}render({_n:T}){return`${this.label}:`+T}}class u extends s{constructor(T){super(),this.label=T,this.names={}}render({_n:T}){return`break${this.label?` ${this.label}`:""};`+T}}class m extends s{constructor(T){super(),this.error=T}render({_n:T}){return`throw ${this.error};`+T}get names(){return this.error.names}}class f extends s{constructor(T){super(),this.code=T}render({_n:T}){return`${this.code};`+T}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(T,x){return this.code=F(this.code,T,x),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends s{constructor(T=[]){super(),this.nodes=T}render(T){return this.nodes.reduce((x,E)=>x+E.render(T),"")}optimizeNodes(){const{nodes:T}=this;let x=T.length;for(;x--;){const E=T[x].optimizeNodes();Array.isArray(E)?T.splice(x,1,...E):E?T[x]=E:T.splice(x,1)}return T.length>0?this:void 0}optimizeNames(T,x){const{nodes:E}=this;let H=E.length;for(;H--;){const W=E[H];W.optimizeNames(T,x)||(ne(T,W.names),E.splice(H,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((T,x)=>j(T,x.names),{})}}class h extends p{render(T){return"{"+T._n+super.render(T)+"}"+T._n}}class v extends p{}class _ extends h{}_.kind="else";class w extends h{constructor(T,x){super(x),this.condition=T}render(T){let x=`if(${this.condition})`+super.render(T);return this.else&&(x+="else "+this.else.render(T)),x}optimizeNodes(){super.optimizeNodes();const T=this.condition;if(T===!0)return this.nodes;let x=this.else;if(x){const E=x.optimizeNodes();x=this.else=Array.isArray(E)?new _(E):E}if(x)return T===!1?x instanceof w?x:x.nodes:this.nodes.length?this:new w(ue(T),x instanceof w?[x]:x.nodes);if(!(T===!1||!this.nodes.length))return this}optimizeNames(T,x){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames(T,x),!!(super.optimizeNames(T,x)||this.else))return this.condition=F(this.condition,T,x),this}get names(){const T=super.names;return D(T,this.condition),this.else&&j(T,this.else.names),T}}w.kind="if";class g extends h{}g.kind="for";class y extends g{constructor(T){super(),this.iteration=T}render(T){return`for(${this.iteration})`+super.render(T)}optimizeNames(T,x){if(super.optimizeNames(T,x))return this.iteration=F(this.iteration,T,x),this}get names(){return j(super.names,this.iteration.names)}}class b extends g{constructor(T,x,E,H){super(),this.varKind=T,this.name=x,this.from=E,this.to=H}render(T){const x=T.es5?r.varKinds.var:this.varKind,{name:E,from:H,to:W}=this;return`for(${x} ${E}=${H}; ${E}<${W}; ${E}++)`+super.render(T)}get names(){const T=D(super.names,this.from);return D(T,this.to)}}class S extends g{constructor(T,x,E,H){super(),this.loop=T,this.varKind=x,this.name=E,this.iterable=H}render(T){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(T)}optimizeNames(T,x){if(super.optimizeNames(T,x))return this.iterable=F(this.iterable,T,x),this}get names(){return j(super.names,this.iterable.names)}}class $ extends h{constructor(T,x,E){super(),this.name=T,this.args=x,this.async=E}render(T){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(T)}}$.kind="func";class k extends p{render(T){return"return "+super.render(T)}}k.kind="return";class I extends h{render(T){let x="try"+super.render(T);return this.catch&&(x+=this.catch.render(T)),this.finally&&(x+=this.finally.render(T)),x}optimizeNodes(){var T,x;return super.optimizeNodes(),(T=this.catch)===null||T===void 0||T.optimizeNodes(),(x=this.finally)===null||x===void 0||x.optimizeNodes(),this}optimizeNames(T,x){var E,H;return super.optimizeNames(T,x),(E=this.catch)===null||E===void 0||E.optimizeNames(T,x),(H=this.finally)===null||H===void 0||H.optimizeNames(T,x),this}get names(){const T=super.names;return this.catch&&j(T,this.catch.names),this.finally&&j(T,this.finally.names),T}}class P extends h{constructor(T){super(),this.error=T}render(T){return`catch(${this.error})`+super.render(T)}}P.kind="catch";class L extends h{render(T){return"finally"+super.render(T)}}L.kind="finally";class N{constructor(T,x={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...x,_n:x.lines?`
74
+ `:""},this._extScope=T,this._scope=new r.Scope({parent:T}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(T){return this._scope.name(T)}scopeName(T){return this._extScope.name(T)}scopeValue(T,x){const E=this._extScope.value(T,x);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue(T,x){return this._extScope.getValue(T,x)}scopeRefs(T){return this._extScope.scopeRefs(T,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(T,x,E,H){const W=this._scope.toName(x);return E!==void 0&&H&&(this._constants[W.str]=E),this._leafNode(new i(T,W,E)),W}const(T,x,E){return this._def(r.varKinds.const,T,x,E)}let(T,x,E){return this._def(r.varKinds.let,T,x,E)}var(T,x,E){return this._def(r.varKinds.var,T,x,E)}assign(T,x,E){return this._leafNode(new a(T,x,E))}add(T,x){return this._leafNode(new l(T,e.operators.ADD,x))}code(T){return typeof T=="function"?T():T!==t.nil&&this._leafNode(new f(T)),this}object(...T){const x=["{"];for(const[E,H]of T)x.length>1&&x.push(","),x.push(E),(E!==H||this.opts.es5)&&(x.push(":"),(0,t.addCodeArg)(x,H));return x.push("}"),new t._Code(x)}if(T,x,E){if(this._blockNode(new w(T)),x&&E)this.code(x).else().code(E).endIf();else if(x)this.code(x).endIf();else if(E)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(T){return this._elseNode(new w(T))}else(){return this._elseNode(new _)}endIf(){return this._endBlockNode(w,_)}_for(T,x){return this._blockNode(T),x&&this.code(x).endFor(),this}for(T,x){return this._for(new y(T),x)}forRange(T,x,E,H,W=this.opts.es5?r.varKinds.var:r.varKinds.let){const fe=this._scope.toName(T);return this._for(new b(W,fe,x,E),()=>H(fe))}forOf(T,x,E,H=r.varKinds.const){const W=this._scope.toName(T);if(this.opts.es5){const fe=x instanceof t.Name?x:this.var("_arr",x);return this.forRange("_i",0,(0,t._)`${fe}.length`,le=>{this.var(W,(0,t._)`${fe}[${le}]`),E(W)})}return this._for(new S("of",H,W,x),()=>E(W))}forIn(T,x,E,H=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(T,(0,t._)`Object.keys(${x})`,E);const W=this._scope.toName(T);return this._for(new S("in",H,W,x),()=>E(W))}endFor(){return this._endBlockNode(g)}label(T){return this._leafNode(new c(T))}break(T){return this._leafNode(new u(T))}return(T){const x=new k;if(this._blockNode(x),this.code(T),x.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(T,x,E){if(!x&&!E)throw new Error('CodeGen: "try" without "catch" and "finally"');const H=new I;if(this._blockNode(H),this.code(T),x){const W=this.name("e");this._currNode=H.catch=new P(W),x(W)}return E&&(this._currNode=H.finally=new L,this.code(E)),this._endBlockNode(P,L)}throw(T){return this._leafNode(new m(T))}block(T,x){return this._blockStarts.push(this._nodes.length),T&&this.code(T).endBlock(x),this}endBlock(T){const x=this._blockStarts.pop();if(x===void 0)throw new Error("CodeGen: not in self-balancing block");const E=this._nodes.length-x;if(E<0||T!==void 0&&E!==T)throw new Error(`CodeGen: wrong number of nodes: ${E} vs ${T} expected`);return this._nodes.length=x,this}func(T,x=t.nil,E,H){return this._blockNode(new $(T,x,E)),H&&this.code(H).endFunc(),this}endFunc(){return this._endBlockNode($)}optimize(T=1){for(;T-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(T){return this._currNode.nodes.push(T),this}_blockNode(T){this._currNode.nodes.push(T),this._nodes.push(T)}_endBlockNode(T,x){const E=this._currNode;if(E instanceof T||x&&E instanceof x)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${x?`${T.kind}/${x.kind}`:T.kind}"`)}_elseNode(T){const x=this._currNode;if(!(x instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=x.else=T,this}get _root(){return this._nodes[0]}get _currNode(){const T=this._nodes;return T[T.length-1]}set _currNode(T){const x=this._nodes;x[x.length-1]=T}}e.CodeGen=N;function j(U,T){for(const x in T)U[x]=(U[x]||0)+(T[x]||0);return U}function D(U,T){return T instanceof t._CodeOrName?j(U,T.names):U}function F(U,T,x){if(U instanceof t.Name)return E(U);if(!H(U))return U;return new t._Code(U._items.reduce((W,fe)=>(fe instanceof t.Name&&(fe=E(fe)),fe instanceof t._Code?W.push(...fe._items):W.push(fe),W),[]));function E(W){const fe=x[W.str];return fe===void 0||T[W.str]!==1?W:(delete T[W.str],fe)}function H(W){return W instanceof t._Code&&W._items.some(fe=>fe instanceof t.Name&&T[fe.str]===1&&x[fe.str]!==void 0)}}function ne(U,T){for(const x in T)U[x]=(U[x]||0)-(T[x]||0)}function ue(U){return typeof U=="boolean"||typeof U=="number"||U===null?!U:(0,t._)`!${Z(U)}`}e.not=ue;const ie=M(e.operators.AND);function re(...U){return U.reduce(ie)}e.and=re;const he=M(e.operators.OR);function V(...U){return U.reduce(he)}e.or=V;function M(U){return(T,x)=>T===t.nil?x:x===t.nil?T:(0,t._)`${Z(T)} ${U} ${Z(x)}`}function Z(U){return U instanceof t.Name?U:(0,t._)`(${U})`}})(ic)),ic}var be={},V2;function ke(){if(V2)return be;V2=1,Object.defineProperty(be,"__esModule",{value:!0}),be.checkStrictMode=be.getErrorPath=be.Type=be.useFunc=be.setEvaluated=be.evaluatedPropsToName=be.mergeEvaluated=be.eachItem=be.unescapeJsonPointer=be.escapeJsonPointer=be.escapeFragment=be.unescapeFragment=be.schemaRefOrVal=be.schemaHasRulesButRef=be.schemaHasRules=be.checkUnknownRules=be.alwaysValidSchema=be.toHash=void 0;const e=we(),t=Ns();function r(S){const $={};for(const k of S)$[k]=!0;return $}be.toHash=r;function n(S,$){return typeof $=="boolean"?$:Object.keys($).length===0?!0:(o(S,$),!s($,S.self.RULES.all))}be.alwaysValidSchema=n;function o(S,$=S.schema){const{opts:k,self:I}=S;if(!k.strictSchema||typeof $=="boolean")return;const P=I.RULES.keywords;for(const L in $)P[L]||b(S,`unknown keyword: "${L}"`)}be.checkUnknownRules=o;function s(S,$){if(typeof S=="boolean")return!S;for(const k in S)if($[k])return!0;return!1}be.schemaHasRules=s;function i(S,$){if(typeof S=="boolean")return!S;for(const k in S)if(k!=="$ref"&&$.all[k])return!0;return!1}be.schemaHasRulesButRef=i;function a({topSchemaRef:S,schemaPath:$},k,I,P){if(!P){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return(0,e._)`${k}`}return(0,e._)`${S}${$}${(0,e.getProperty)(I)}`}be.schemaRefOrVal=a;function l(S){return m(decodeURIComponent(S))}be.unescapeFragment=l;function c(S){return encodeURIComponent(u(S))}be.escapeFragment=c;function u(S){return typeof S=="number"?`${S}`:S.replace(/~/g,"~0").replace(/\//g,"~1")}be.escapeJsonPointer=u;function m(S){return S.replace(/~1/g,"/").replace(/~0/g,"~")}be.unescapeJsonPointer=m;function f(S,$){if(Array.isArray(S))for(const k of S)$(k);else $(S)}be.eachItem=f;function p({mergeNames:S,mergeToName:$,mergeValues:k,resultToName:I}){return(P,L,N,j)=>{const D=N===void 0?L:N instanceof e.Name?(L instanceof e.Name?S(P,L,N):$(P,L,N),N):L instanceof e.Name?($(P,N,L),L):k(L,N);return j===e.Name&&!(D instanceof e.Name)?I(P,D):D}}be.mergeEvaluated={props:p({mergeNames:(S,$,k)=>S.if((0,e._)`${k} !== true && ${$} !== undefined`,()=>{S.if((0,e._)`${$} === true`,()=>S.assign(k,!0),()=>S.assign(k,(0,e._)`${k} || {}`).code((0,e._)`Object.assign(${k}, ${$})`))}),mergeToName:(S,$,k)=>S.if((0,e._)`${k} !== true`,()=>{$===!0?S.assign(k,!0):(S.assign(k,(0,e._)`${k} || {}`),v(S,k,$))}),mergeValues:(S,$)=>S===!0?!0:{...S,...$},resultToName:h}),items:p({mergeNames:(S,$,k)=>S.if((0,e._)`${k} !== true && ${$} !== undefined`,()=>S.assign(k,(0,e._)`${$} === true ? true : ${k} > ${$} ? ${k} : ${$}`)),mergeToName:(S,$,k)=>S.if((0,e._)`${k} !== true`,()=>S.assign(k,$===!0?!0:(0,e._)`${k} > ${$} ? ${k} : ${$}`)),mergeValues:(S,$)=>S===!0?!0:Math.max(S,$),resultToName:(S,$)=>S.var("items",$)})};function h(S,$){if($===!0)return S.var("props",!0);const k=S.var("props",(0,e._)`{}`);return $!==void 0&&v(S,k,$),k}be.evaluatedPropsToName=h;function v(S,$,k){Object.keys(k).forEach(I=>S.assign((0,e._)`${$}${(0,e.getProperty)(I)}`,!0))}be.setEvaluated=v;const _={};function w(S,$){return S.scopeValue("func",{ref:$,code:_[$.code]||(_[$.code]=new t._Code($.code))})}be.useFunc=w;var g;(function(S){S[S.Num=0]="Num",S[S.Str=1]="Str"})(g||(be.Type=g={}));function y(S,$,k){if(S instanceof e.Name){const I=$===g.Num;return k?I?(0,e._)`"[" + ${S} + "]"`:(0,e._)`"['" + ${S} + "']"`:I?(0,e._)`"/" + ${S}`:(0,e._)`"/" + ${S}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,e.getProperty)(S).toString():"/"+u(S)}be.getErrorPath=y;function b(S,$,k=S.opts.strictSchema){if(k){if($=`strict mode: ${$}`,k===!0)throw new Error($);S.self.logger.warn($)}}return be.checkStrictMode=b,be}var qs={},H2;function $r(){if(H2)return qs;H2=1,Object.defineProperty(qs,"__esModule",{value:!0});const e=we(),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 qs.default=t,qs}var B2;function Ls(){return B2||(B2=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=we(),r=ke(),n=$r();e.keywordError={message:({keyword:_})=>(0,t.str)`must pass "${_}" keyword validation`},e.keyword$DataError={message:({keyword:_,schemaType:w})=>w?(0,t.str)`"${_}" keyword must be ${w} ($data)`:(0,t.str)`"${_}" keyword is invalid ($data)`};function o(_,w=e.keywordError,g,y){const{it:b}=_,{gen:S,compositeRule:$,allErrors:k}=b,I=m(_,w,g);y??($||k)?l(S,I):c(b,(0,t._)`[${I}]`)}e.reportError=o;function s(_,w=e.keywordError,g){const{it:y}=_,{gen:b,compositeRule:S,allErrors:$}=y,k=m(_,w,g);l(b,k),S||$||c(y,n.default.vErrors)}e.reportExtraError=s;function i(_,w){_.assign(n.default.errors,w),_.if((0,t._)`${n.default.vErrors} !== null`,()=>_.if(w,()=>_.assign((0,t._)`${n.default.vErrors}.length`,w),()=>_.assign(n.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:_,keyword:w,schemaValue:g,data:y,errsCount:b,it:S}){if(b===void 0)throw new Error("ajv implementation error");const $=_.name("err");_.forRange("i",b,n.default.errors,k=>{_.const($,(0,t._)`${n.default.vErrors}[${k}]`),_.if((0,t._)`${$}.instancePath === undefined`,()=>_.assign((0,t._)`${$}.instancePath`,(0,t.strConcat)(n.default.instancePath,S.errorPath))),_.assign((0,t._)`${$}.schemaPath`,(0,t.str)`${S.errSchemaPath}/${w}`),S.opts.verbose&&(_.assign((0,t._)`${$}.schema`,g),_.assign((0,t._)`${$}.data`,y))})}e.extendErrors=a;function l(_,w){const g=_.const("err",w);_.if((0,t._)`${n.default.vErrors} === null`,()=>_.assign(n.default.vErrors,(0,t._)`[${g}]`),(0,t._)`${n.default.vErrors}.push(${g})`),_.code((0,t._)`${n.default.errors}++`)}function c(_,w){const{gen:g,validateName:y,schemaEnv:b}=_;b.$async?g.throw((0,t._)`new ${_.ValidationError}(${w})`):(g.assign((0,t._)`${y}.errors`,w),g.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(_,w,g){const{createErrors:y}=_.it;return y===!1?(0,t._)`{}`:f(_,w,g)}function f(_,w,g={}){const{gen:y,it:b}=_,S=[p(b,g),h(_,g)];return v(_,w,S),y.object(...S)}function p({errorPath:_},{instancePath:w}){const g=w?(0,t.str)`${_}${(0,r.getErrorPath)(w,r.Type.Str)}`:_;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,g)]}function h({keyword:_,it:{errSchemaPath:w}},{schemaPath:g,parentSchema:y}){let b=y?w:(0,t.str)`${w}/${_}`;return g&&(b=(0,t.str)`${b}${(0,r.getErrorPath)(g,r.Type.Str)}`),[u.schemaPath,b]}function v(_,{params:w,message:g},y){const{keyword:b,data:S,schemaValue:$,it:k}=_,{opts:I,propertyName:P,topSchemaRef:L,schemaPath:N}=k;y.push([u.keyword,b],[u.params,typeof w=="function"?w(_):w||(0,t._)`{}`]),I.messages&&y.push([u.message,typeof g=="function"?g(_):g]),I.verbose&&y.push([u.schema,$],[u.parentSchema,(0,t._)`${L}${N}`],[n.default.data,S]),P&&y.push([u.propertyName,P])}})(ac)),ac}var J2;function OE(){if(J2)return Hr;J2=1,Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.boolOrEmptySchema=Hr.topBoolOrEmptySchema=void 0;const e=Ls(),t=we(),r=$r(),n={message:"boolean schema is false"};function o(a){const{gen:l,schema:c,validateName:u}=a;c===!1?i(a,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}Hr.topBoolOrEmptySchema=o;function s(a,l){const{gen:c,schema:u}=a;u===!1?(c.var(l,!1),i(a)):c.var(l,!0)}Hr.boolOrEmptySchema=s;function i(a,l){const{gen:c,data:u}=a,m={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(m,n,void 0,l)}return Hr}var Ye={},Br={},W2;function G2(){if(W2)return Br;W2=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.getRules=Br.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)}Br.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 Br.getRules=n,Br}var ir={},K2;function Y2(){if(K2)return ir;K2=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.shouldUseRule=ir.shouldUseGroup=ir.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(n,i)}ir.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}ir.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(i=>n[i]!==void 0))}return ir.shouldUseRule=r,ir}var Q2;function Us(){if(Q2)return Ye;Q2=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.reportTypeError=Ye.checkDataTypes=Ye.checkDataType=Ye.coerceAndCheckDataType=Ye.getJSONTypes=Ye.getSchemaTypes=Ye.DataType=void 0;const e=G2(),t=Y2(),r=Ls(),n=we(),o=ke();var s;(function(g){g[g.Correct=0]="Correct",g[g.Wrong=1]="Wrong"})(s||(Ye.DataType=s={}));function i(g){const y=a(g.type);if(y.includes("null")){if(g.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!y.length&&g.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');g.nullable===!0&&y.push("null")}return y}Ye.getSchemaTypes=i;function a(g){const y=Array.isArray(g)?g:g?[g]:[];if(y.every(e.isJSONType))return y;throw new Error("type must be JSONType or JSONType[]: "+y.join(","))}Ye.getJSONTypes=a;function l(g,y){const{gen:b,data:S,opts:$}=g,k=u(y,$.coerceTypes),I=y.length>0&&!(k.length===0&&y.length===1&&(0,t.schemaHasRulesForType)(g,y[0]));if(I){const P=h(y,S,$.strictNumbers,s.Wrong);b.if(P,()=>{k.length?m(g,y,k):_(g)})}return I}Ye.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(g,y){return y?g.filter(b=>c.has(b)||y==="array"&&b==="array"):[]}function m(g,y,b){const{gen:S,data:$,opts:k}=g,I=S.let("dataType",(0,n._)`typeof ${$}`),P=S.let("coerced",(0,n._)`undefined`);k.coerceTypes==="array"&&S.if((0,n._)`${I} == 'object' && Array.isArray(${$}) && ${$}.length == 1`,()=>S.assign($,(0,n._)`${$}[0]`).assign(I,(0,n._)`typeof ${$}`).if(h(y,$,k.strictNumbers),()=>S.assign(P,$))),S.if((0,n._)`${P} !== undefined`);for(const N of b)(c.has(N)||N==="array"&&k.coerceTypes==="array")&&L(N);S.else(),_(g),S.endIf(),S.if((0,n._)`${P} !== undefined`,()=>{S.assign($,P),f(g,P)});function L(N){switch(N){case"string":S.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(P,(0,n._)`"" + ${$}`).elseIf((0,n._)`${$} === null`).assign(P,(0,n._)`""`);return;case"number":S.elseIf((0,n._)`${I} == "boolean" || ${$} === null
75
+ || (${I} == "string" && ${$} && ${$} == +${$})`).assign(P,(0,n._)`+${$}`);return;case"integer":S.elseIf((0,n._)`${I} === "boolean" || ${$} === null
76
+ || (${I} === "string" && ${$} && ${$} == +${$} && !(${$} % 1))`).assign(P,(0,n._)`+${$}`);return;case"boolean":S.elseIf((0,n._)`${$} === "false" || ${$} === 0 || ${$} === null`).assign(P,!1).elseIf((0,n._)`${$} === "true" || ${$} === 1`).assign(P,!0);return;case"null":S.elseIf((0,n._)`${$} === "" || ${$} === 0 || ${$} === false`),S.assign(P,null);return;case"array":S.elseIf((0,n._)`${I} === "string" || ${I} === "number"
77
+ || ${I} === "boolean" || ${$} === null`).assign(P,(0,n._)`[${$}]`)}}}function f({gen:g,parentData:y,parentDataProperty:b},S){g.if((0,n._)`${y} !== undefined`,()=>g.assign((0,n._)`${y}[${b}]`,S))}function p(g,y,b,S=s.Correct){const $=S===s.Correct?n.operators.EQ:n.operators.NEQ;let k;switch(g){case"null":return(0,n._)`${y} ${$} null`;case"array":k=(0,n._)`Array.isArray(${y})`;break;case"object":k=(0,n._)`${y} && typeof ${y} == "object" && !Array.isArray(${y})`;break;case"integer":k=I((0,n._)`!(${y} % 1) && !isNaN(${y})`);break;case"number":k=I();break;default:return(0,n._)`typeof ${y} ${$} ${g}`}return S===s.Correct?k:(0,n.not)(k);function I(P=n.nil){return(0,n.and)((0,n._)`typeof ${y} == "number"`,P,b?(0,n._)`isFinite(${y})`:n.nil)}}Ye.checkDataType=p;function h(g,y,b,S){if(g.length===1)return p(g[0],y,b,S);let $;const k=(0,o.toHash)(g);if(k.array&&k.object){const I=(0,n._)`typeof ${y} != "object"`;$=k.null?I:(0,n._)`!${y} || ${I}`,delete k.null,delete k.array,delete k.object}else $=n.nil;k.number&&delete k.integer;for(const I in k)$=(0,n.and)($,p(I,y,b,S));return $}Ye.checkDataTypes=h;const v={message:({schema:g})=>`must be ${g}`,params:({schema:g,schemaValue:y})=>typeof g=="string"?(0,n._)`{type: ${g}}`:(0,n._)`{type: ${y}}`};function _(g){const y=w(g);(0,r.reportError)(y,v)}Ye.reportTypeError=_;function w(g){const{gen:y,data:b,schema:S}=g,$=(0,o.schemaRefOrVal)(g,S,"type");return{gen:y,keyword:"type",data:b,schema:S.type,schemaCode:$,schemaValue:$,parentSchema:S,params:{},it:g}}return Ye}var yo={},X2;function ME(){if(X2)return yo;X2=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.assignDefaults=void 0;const e=we(),t=ke();function r(o,s){const{properties:i,items:a}=o.schema;if(s==="object"&&i)for(const l in i)n(o,l,i[l].default);else s==="array"&&Array.isArray(a)&&a.forEach((l,c)=>n(o,c,l.default))}yo.assignDefaults=r;function n(o,s,i){const{gen:a,compositeRule:l,data:c,opts:u}=o;if(i===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 f=(0,e._)`${m} === undefined`;u.useDefaults==="empty"&&(f=(0,e._)`${f} || ${m} === null || ${m} === ""`),a.if(f,(0,e._)`${m} = ${(0,e.stringify)(i)}`)}return yo}var Dt={},Pe={},eg;function zt(){if(eg)return Pe;eg=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.validateUnion=Pe.validateArray=Pe.usePattern=Pe.callValidateCode=Pe.schemaProperties=Pe.allSchemaProperties=Pe.noPropertyInData=Pe.propertyInData=Pe.isOwnProperty=Pe.hasPropFunc=Pe.reportMissingProp=Pe.checkMissingProp=Pe.checkReportMissingProp=void 0;const e=we(),t=ke(),r=$r(),n=ke();function o(g,y){const{gen:b,data:S,it:$}=g;b.if(u(b,S,y,$.opts.ownProperties),()=>{g.setParams({missingProperty:(0,e._)`${y}`},!0),g.error()})}Pe.checkReportMissingProp=o;function s({gen:g,data:y,it:{opts:b}},S,$){return(0,e.or)(...S.map(k=>(0,e.and)(u(g,y,k,b.ownProperties),(0,e._)`${$} = ${k}`)))}Pe.checkMissingProp=s;function i(g,y){g.setParams({missingProperty:y},!0),g.error()}Pe.reportMissingProp=i;function a(g){return g.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Pe.hasPropFunc=a;function l(g,y,b){return(0,e._)`${a(g)}.call(${y}, ${b})`}Pe.isOwnProperty=l;function c(g,y,b,S){const $=(0,e._)`${y}${(0,e.getProperty)(b)} !== undefined`;return S?(0,e._)`${$} && ${l(g,y,b)}`:$}Pe.propertyInData=c;function u(g,y,b,S){const $=(0,e._)`${y}${(0,e.getProperty)(b)} === undefined`;return S?(0,e.or)($,(0,e.not)(l(g,y,b))):$}Pe.noPropertyInData=u;function m(g){return g?Object.keys(g).filter(y=>y!=="__proto__"):[]}Pe.allSchemaProperties=m;function f(g,y){return m(y).filter(b=>!(0,t.alwaysValidSchema)(g,y[b]))}Pe.schemaProperties=f;function p({schemaCode:g,data:y,it:{gen:b,topSchemaRef:S,schemaPath:$,errorPath:k},it:I},P,L,N){const j=N?(0,e._)`${g}, ${y}, ${S}${$}`:y,D=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,k)],[r.default.parentData,I.parentData],[r.default.parentDataProperty,I.parentDataProperty],[r.default.rootData,r.default.rootData]];I.opts.dynamicRef&&D.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const F=(0,e._)`${j}, ${b.object(...D)}`;return L!==e.nil?(0,e._)`${P}.call(${L}, ${F})`:(0,e._)`${P}(${F})`}Pe.callValidateCode=p;const h=(0,e._)`new RegExp`;function v({gen:g,it:{opts:y}},b){const S=y.unicodeRegExp?"u":"",{regExp:$}=y.code,k=$(b,S);return g.scopeValue("pattern",{key:k.toString(),ref:k,code:(0,e._)`${$.code==="new RegExp"?h:(0,n.useFunc)(g,$)}(${b}, ${S})`})}Pe.usePattern=v;function _(g){const{gen:y,data:b,keyword:S,it:$}=g,k=y.name("valid");if($.allErrors){const P=y.let("valid",!0);return I(()=>y.assign(P,!1)),P}return y.var(k,!0),I(()=>y.break()),k;function I(P){const L=y.const("len",(0,e._)`${b}.length`);y.forRange("i",0,L,N=>{g.subschema({keyword:S,dataProp:N,dataPropType:t.Type.Num},k),y.if((0,e.not)(k),P)})}}Pe.validateArray=_;function w(g){const{gen:y,schema:b,keyword:S,it:$}=g;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(L=>(0,t.alwaysValidSchema)($,L))&&!$.opts.unevaluated)return;const I=y.let("valid",!1),P=y.name("_valid");y.block(()=>b.forEach((L,N)=>{const j=g.subschema({keyword:S,schemaProp:N,compositeRule:!0},P);y.assign(I,(0,e._)`${I} || ${P}`),g.mergeValidEvaluated(j,P)||y.if((0,e.not)(I))})),g.result(I,()=>g.reset(),()=>g.error(!0))}return Pe.validateUnion=w,Pe}var tg;function AE(){if(tg)return Dt;tg=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.validateKeywordUsage=Dt.validSchemaType=Dt.funcKeywordCode=Dt.macroKeywordCode=void 0;const e=we(),t=$r(),r=zt(),n=Ls();function o(f,p){const{gen:h,keyword:v,schema:_,parentSchema:w,it:g}=f,y=p.macro.call(g.self,_,w,g),b=c(h,v,y);g.opts.validateSchema!==!1&&g.self.validateSchema(y,!0);const S=h.name("valid");f.subschema({schema:y,schemaPath:e.nil,errSchemaPath:`${g.errSchemaPath}/${v}`,topSchemaRef:b,compositeRule:!0},S),f.pass(S,()=>f.error(!0))}Dt.macroKeywordCode=o;function s(f,p){var h;const{gen:v,keyword:_,schema:w,parentSchema:g,$data:y,it:b}=f;l(b,p);const S=!y&&p.compile?p.compile.call(b.self,w,g,b):p.validate,$=c(v,_,S),k=v.let("valid");f.block$data(k,I),f.ok((h=p.valid)!==null&&h!==void 0?h:k);function I(){if(p.errors===!1)N(),p.modifying&&i(f),j(()=>f.error());else{const D=p.async?P():L();p.modifying&&i(f),j(()=>a(f,D))}}function P(){const D=v.let("ruleErrs",null);return v.try(()=>N((0,e._)`await `),F=>v.assign(k,!1).if((0,e._)`${F} instanceof ${b.ValidationError}`,()=>v.assign(D,(0,e._)`${F}.errors`),()=>v.throw(F))),D}function L(){const D=(0,e._)`${$}.errors`;return v.assign(D,null),N(e.nil),D}function N(D=p.async?(0,e._)`await `:e.nil){const F=b.opts.passContext?t.default.this:t.default.self,ne=!("compile"in p&&!y||p.schema===!1);v.assign(k,(0,e._)`${D}${(0,r.callValidateCode)(f,$,F,ne)}`,p.modifying)}function j(D){var F;v.if((0,e.not)((F=p.valid)!==null&&F!==void 0?F:k),D)}}Dt.funcKeywordCode=s;function i(f){const{gen:p,data:h,it:v}=f;p.if(v.parentData,()=>p.assign(h,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function a(f,p){const{gen:h}=f;h.if((0,e._)`Array.isArray(${p})`,()=>{h.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${p} : ${t.default.vErrors}.concat(${p})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(f)},()=>f.error())}function l({schemaEnv:f},p){if(p.async&&!f.$async)throw new Error("async keyword in sync schema")}function c(f,p,h){if(h===void 0)throw new Error(`keyword "${p}" failed to compile`);return f.scopeValue("keyword",typeof h=="function"?{ref:h}:{ref:h,code:(0,e.stringify)(h)})}function u(f,p,h=!1){return!p.length||p.some(v=>v==="array"?Array.isArray(f):v==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==v||h&&typeof f>"u")}Dt.validSchemaType=u;function m({schema:f,opts:p,self:h,errSchemaPath:v},_,w){if(Array.isArray(_.keyword)?!_.keyword.includes(w):_.keyword!==w)throw new Error("ajv implementation error");const g=_.dependencies;if(g?.some(y=>!Object.prototype.hasOwnProperty.call(f,y)))throw new Error(`parent schema must have dependencies of ${w}: ${g.join(",")}`);if(_.validateSchema&&!_.validateSchema(f[w])){const b=`keyword "${w}" value is invalid at path "${v}": `+h.errorsText(_.validateSchema.errors);if(p.validateSchema==="log")h.logger.error(b);else throw new Error(b)}}return Dt.validateKeywordUsage=m,Dt}var lr={},rg;function NE(){if(rg)return lr;rg=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.extendSubschemaMode=lr.extendSubschemaData=lr.getSubschema=void 0;const e=we(),t=ke();function r(s,{keyword:i,schemaProp:a,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:m}){if(i!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const f=s.schema[i];return a===void 0?{schema:f,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${i}`}:{schema:f[a],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${i}/${(0,t.escapeFragment)(a)}`}}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')}lr.getSubschema=r;function n(s,i,{dataProp:a,dataPropType:l,data:c,dataTypes:u,propertyName:m}){if(c!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:f}=i;if(a!==void 0){const{errorPath:h,dataPathArr:v,opts:_}=i,w=f.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);p(w),s.errorPath=(0,e.str)`${h}${(0,t.getErrorPath)(a,l,_.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,s.dataPathArr=[...v,s.parentDataProperty]}if(c!==void 0){const h=c instanceof e.Name?c:f.let("data",c,!0);p(h),m!==void 0&&(s.propertyName=m)}u&&(s.dataTypes=u);function p(h){s.data=h,s.dataLevel=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,h]}}lr.extendSubschemaData=n;function o(s,{jtdDiscriminator:i,jtdMetadata:a,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=i,s.jtdMetadata=a}return lr.extendSubschemaMode=o,lr}var lt={},uc,ng;function og(){return ng||(ng=1,uc=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 i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}),uc}var dc={exports:{}},sg;function qE(){if(sg)return dc.exports;sg=1;var e=dc.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var i=typeof s=="function"?s:s.pre||function(){},a=s.post||function(){};t(o,i,a,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,i,a,l,c,u,m,f){if(i&&typeof i=="object"&&!Array.isArray(i)){o(i,a,l,c,u,m,f);for(var p in i){var h=i[p];if(Array.isArray(h)){if(p in e.arrayKeywords)for(var v=0;v<h.length;v++)t(n,o,s,h[v],a+"/"+p+"/"+v,l,a,p,i,v)}else if(p in e.propsKeywords){if(h&&typeof h=="object")for(var _ in h)t(n,o,s,h[_],a+"/"+p+"/"+r(_),l,a,p,i,_)}else(p in e.keywords||n.allKeys&&!(p in e.skipKeywords))&&t(n,o,s,h,a+"/"+p,l,a,p,i)}s(i,a,l,c,u,m,f)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return dc.exports}var ag;function js(){if(ag)return lt;ag=1,Object.defineProperty(lt,"__esModule",{value:!0}),lt.getSchemaRefs=lt.resolveUrl=lt.normalizeId=lt._getFullPath=lt.getFullPath=lt.inlineRef=void 0;const e=ke(),t=og(),r=qE(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(v,_=!0){return typeof v=="boolean"?!0:_===!0?!i(v):_?a(v)<=_:!1}lt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(v){for(const _ in v){if(s.has(_))return!0;const w=v[_];if(Array.isArray(w)&&w.some(i)||typeof w=="object"&&i(w))return!0}return!1}function a(v){let _=0;for(const w in v){if(w==="$ref")return 1/0;if(_++,!n.has(w)&&(typeof v[w]=="object"&&(0,e.eachItem)(v[w],g=>_+=a(g)),_===1/0))return 1/0}return _}function l(v,_="",w){w!==!1&&(_=m(_));const g=v.parse(_);return c(v,g)}lt.getFullPath=l;function c(v,_){return v.serialize(_).split("#")[0]+"#"}lt._getFullPath=c;const u=/#\/?$/;function m(v){return v?v.replace(u,""):""}lt.normalizeId=m;function f(v,_,w){return w=m(w),v.resolve(_,w)}lt.resolveUrl=f;const p=/^[a-z_][-a-z0-9._]*$/i;function h(v,_){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:g}=this.opts,y=m(v[w]||_),b={"":y},S=l(g,y,!1),$={},k=new Set;return r(v,{allKeys:!0},(L,N,j,D)=>{if(D===void 0)return;const F=S+N;let ne=b[D];typeof L[w]=="string"&&(ne=ue.call(this,L[w])),ie.call(this,L.$anchor),ie.call(this,L.$dynamicAnchor),b[N]=ne;function ue(re){const he=this.opts.uriResolver.resolve;if(re=m(ne?he(ne,re):re),k.has(re))throw P(re);k.add(re);let V=this.refs[re];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?I(L,V.schema,re):re!==m(F)&&(re[0]==="#"?(I(L,$[re],re),$[re]=L):this.refs[re]=F),re}function ie(re){if(typeof re=="string"){if(!p.test(re))throw new Error(`invalid anchor "${re}"`);ue.call(this,`#${re}`)}}}),$;function I(L,N,j){if(N!==void 0&&!t(L,N))throw P(j)}function P(L){return new Error(`reference "${L}" resolves to more than one schema`)}}return lt.getSchemaRefs=h,lt}var ig;function Ds(){if(ig)return ar;ig=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.getData=ar.KeywordCxt=ar.validateFunctionCode=void 0;const e=OE(),t=Us(),r=Y2(),n=Us(),o=ME(),s=AE(),i=NE(),a=we(),l=$r(),c=js(),u=ke(),m=Ls();function f(q){if(S(q)&&(k(q),b(q))){_(q);return}p(q,()=>(0,e.topBoolOrEmptySchema)(q))}ar.validateFunctionCode=f;function p({gen:q,validateName:z,schema:B,schemaEnv:G,opts:Y},ae){Y.code.es5?q.func(z,(0,a._)`${l.default.data}, ${l.default.valCxt}`,G.$async,()=>{q.code((0,a._)`"use strict"; ${g(B,Y)}`),v(q,Y),q.code(ae)}):q.func(z,(0,a._)`${l.default.data}, ${h(Y)}`,G.$async,()=>q.code(g(B,Y)).code(ae))}function h(q){return(0,a._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${q.dynamicRef?(0,a._)`, ${l.default.dynamicAnchors}={}`:a.nil}}={}`}function v(q,z){q.if(l.default.valCxt,()=>{q.var(l.default.instancePath,(0,a._)`${l.default.valCxt}.${l.default.instancePath}`),q.var(l.default.parentData,(0,a._)`${l.default.valCxt}.${l.default.parentData}`),q.var(l.default.parentDataProperty,(0,a._)`${l.default.valCxt}.${l.default.parentDataProperty}`),q.var(l.default.rootData,(0,a._)`${l.default.valCxt}.${l.default.rootData}`),z.dynamicRef&&q.var(l.default.dynamicAnchors,(0,a._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{q.var(l.default.instancePath,(0,a._)`""`),q.var(l.default.parentData,(0,a._)`undefined`),q.var(l.default.parentDataProperty,(0,a._)`undefined`),q.var(l.default.rootData,l.default.data),z.dynamicRef&&q.var(l.default.dynamicAnchors,(0,a._)`{}`)})}function _(q){const{schema:z,opts:B,gen:G}=q;p(q,()=>{B.$comment&&z.$comment&&D(q),L(q),G.let(l.default.vErrors,null),G.let(l.default.errors,0),B.unevaluated&&w(q),I(q),F(q)})}function w(q){const{gen:z,validateName:B}=q;q.evaluated=z.const("evaluated",(0,a._)`${B}.evaluated`),z.if((0,a._)`${q.evaluated}.dynamicProps`,()=>z.assign((0,a._)`${q.evaluated}.props`,(0,a._)`undefined`)),z.if((0,a._)`${q.evaluated}.dynamicItems`,()=>z.assign((0,a._)`${q.evaluated}.items`,(0,a._)`undefined`))}function g(q,z){const B=typeof q=="object"&&q[z.schemaId];return B&&(z.code.source||z.code.process)?(0,a._)`/*# sourceURL=${B} */`:a.nil}function y(q,z){if(S(q)&&(k(q),b(q))){$(q,z);return}(0,e.boolOrEmptySchema)(q,z)}function b({schema:q,self:z}){if(typeof q=="boolean")return!q;for(const B in q)if(z.RULES.all[B])return!0;return!1}function S(q){return typeof q.schema!="boolean"}function $(q,z){const{schema:B,gen:G,opts:Y}=q;Y.$comment&&B.$comment&&D(q),N(q),j(q);const ae=G.const("_errs",l.default.errors);I(q,ae),G.var(z,(0,a._)`${ae} === ${l.default.errors}`)}function k(q){(0,u.checkUnknownRules)(q),P(q)}function I(q,z){if(q.opts.jtd)return ue(q,[],!1,z);const B=(0,t.getSchemaTypes)(q.schema),G=(0,t.coerceAndCheckDataType)(q,B);ue(q,B,!G,z)}function P(q){const{schema:z,errSchemaPath:B,opts:G,self:Y}=q;z.$ref&&G.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(z,Y.RULES)&&Y.logger.warn(`$ref: keywords ignored in schema at path "${B}"`)}function L(q){const{schema:z,opts:B}=q;z.default!==void 0&&B.useDefaults&&B.strictSchema&&(0,u.checkStrictMode)(q,"default is ignored in the schema root")}function N(q){const z=q.schema[q.opts.schemaId];z&&(q.baseId=(0,c.resolveUrl)(q.opts.uriResolver,q.baseId,z))}function j(q){if(q.schema.$async&&!q.schemaEnv.$async)throw new Error("async schema in sync schema")}function D({gen:q,schemaEnv:z,schema:B,errSchemaPath:G,opts:Y}){const ae=B.$comment;if(Y.$comment===!0)q.code((0,a._)`${l.default.self}.logger.log(${ae})`);else if(typeof Y.$comment=="function"){const de=(0,a.str)`${G}/$comment`,Ae=q.scopeValue("root",{ref:z.root});q.code((0,a._)`${l.default.self}.opts.$comment(${ae}, ${de}, ${Ae}.schema)`)}}function F(q){const{gen:z,schemaEnv:B,validateName:G,ValidationError:Y,opts:ae}=q;B.$async?z.if((0,a._)`${l.default.errors} === 0`,()=>z.return(l.default.data),()=>z.throw((0,a._)`new ${Y}(${l.default.vErrors})`)):(z.assign((0,a._)`${G}.errors`,l.default.vErrors),ae.unevaluated&&ne(q),z.return((0,a._)`${l.default.errors} === 0`))}function ne({gen:q,evaluated:z,props:B,items:G}){B instanceof a.Name&&q.assign((0,a._)`${z}.props`,B),G instanceof a.Name&&q.assign((0,a._)`${z}.items`,G)}function ue(q,z,B,G){const{gen:Y,schema:ae,data:de,allErrors:Ae,opts:qe,self:ee}=q,{RULES:ve}=ee;if(ae.$ref&&(qe.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ae,ve))){Y.block(()=>H(q,"$ref",ve.all.$ref.definition));return}qe.jtd||re(q,z),Y.block(()=>{for(const Se of ve.rules)ct(Se);ct(ve.post)});function ct(Se){(0,r.shouldUseGroup)(ae,Se)&&(Se.type?(Y.if((0,n.checkDataType)(Se.type,de,qe.strictNumbers)),ie(q,Se),z.length===1&&z[0]===Se.type&&B&&(Y.else(),(0,n.reportTypeError)(q)),Y.endIf()):ie(q,Se),Ae||Y.if((0,a._)`${l.default.errors} === ${G||0}`))}}function ie(q,z){const{gen:B,schema:G,opts:{useDefaults:Y}}=q;Y&&(0,o.assignDefaults)(q,z.type),B.block(()=>{for(const ae of z.rules)(0,r.shouldUseRule)(G,ae)&&H(q,ae.keyword,ae.definition,z.type)})}function re(q,z){q.schemaEnv.meta||!q.opts.strictTypes||(he(q,z),q.opts.allowUnionTypes||V(q,z),M(q,q.dataTypes))}function he(q,z){if(z.length){if(!q.dataTypes.length){q.dataTypes=z;return}z.forEach(B=>{U(q.dataTypes,B)||x(q,`type "${B}" not allowed by context "${q.dataTypes.join(",")}"`)}),T(q,z)}}function V(q,z){z.length>1&&!(z.length===2&&z.includes("null"))&&x(q,"use allowUnionTypes to allow union type keyword")}function M(q,z){const B=q.self.RULES.all;for(const G in B){const Y=B[G];if(typeof Y=="object"&&(0,r.shouldUseRule)(q.schema,Y)){const{type:ae}=Y.definition;ae.length&&!ae.some(de=>Z(z,de))&&x(q,`missing type "${ae.join(",")}" for keyword "${G}"`)}}}function Z(q,z){return q.includes(z)||z==="number"&&q.includes("integer")}function U(q,z){return q.includes(z)||z==="integer"&&q.includes("number")}function T(q,z){const B=[];for(const G of q.dataTypes)U(z,G)?B.push(G):z.includes("integer")&&G==="number"&&B.push("integer");q.dataTypes=B}function x(q,z){const B=q.schemaEnv.baseId+q.errSchemaPath;z+=` at "${B}" (strictTypes)`,(0,u.checkStrictMode)(q,z,q.opts.strictTypes)}class E{constructor(z,B,G){if((0,s.validateKeywordUsage)(z,B,G),this.gen=z.gen,this.allErrors=z.allErrors,this.keyword=G,this.data=z.data,this.schema=z.schema[G],this.$data=B.$data&&z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(z,this.schema,G,this.$data),this.schemaType=B.schemaType,this.parentSchema=z.schema,this.params={},this.it=z,this.def=B,this.$data)this.schemaCode=z.gen.const("vSchema",le(this.$data,z));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,B.schemaType,B.allowUndefined))throw new Error(`${G} value must be ${JSON.stringify(B.schemaType)}`);("code"in B?B.trackErrors:B.errors!==!1)&&(this.errsCount=z.gen.const("_errs",l.default.errors))}result(z,B,G){this.failResult((0,a.not)(z),B,G)}failResult(z,B,G){this.gen.if(z),G?G():this.error(),B?(this.gen.else(),B(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(z,B){this.failResult((0,a.not)(z),void 0,B)}fail(z){if(z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(z){if(!this.$data)return this.fail(z);const{schemaCode:B}=this;this.fail((0,a._)`${B} !== undefined && (${(0,a.or)(this.invalid$data(),z)})`)}error(z,B,G){if(B){this.setParams(B),this._error(z,G),this.setParams({});return}this._error(z,G)}_error(z,B){(z?m.reportExtraError:m.reportError)(this,this.def.error,B)}$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(z){this.allErrors||this.gen.if(z)}setParams(z,B){B?Object.assign(this.params,z):this.params=z}block$data(z,B,G=a.nil){this.gen.block(()=>{this.check$data(z,G),B()})}check$data(z=a.nil,B=a.nil){if(!this.$data)return;const{gen:G,schemaCode:Y,schemaType:ae,def:de}=this;G.if((0,a.or)((0,a._)`${Y} === undefined`,B)),z!==a.nil&&G.assign(z,!0),(ae.length||de.validateSchema)&&(G.elseIf(this.invalid$data()),this.$dataError(),z!==a.nil&&G.assign(z,!1)),G.else()}invalid$data(){const{gen:z,schemaCode:B,schemaType:G,def:Y,it:ae}=this;return(0,a.or)(de(),Ae());function de(){if(G.length){if(!(B instanceof a.Name))throw new Error("ajv implementation error");const qe=Array.isArray(G)?G:[G];return(0,a._)`${(0,n.checkDataTypes)(qe,B,ae.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}function Ae(){if(Y.validateSchema){const qe=z.scopeValue("validate$data",{ref:Y.validateSchema});return(0,a._)`!${qe}(${B})`}return a.nil}}subschema(z,B){const G=(0,i.getSubschema)(this.it,z);(0,i.extendSubschemaData)(G,this.it,z),(0,i.extendSubschemaMode)(G,z);const Y={...this.it,...G,items:void 0,props:void 0};return y(Y,B),Y}mergeEvaluated(z,B){const{it:G,gen:Y}=this;G.opts.unevaluated&&(G.props!==!0&&z.props!==void 0&&(G.props=u.mergeEvaluated.props(Y,z.props,G.props,B)),G.items!==!0&&z.items!==void 0&&(G.items=u.mergeEvaluated.items(Y,z.items,G.items,B)))}mergeValidEvaluated(z,B){const{it:G,gen:Y}=this;if(G.opts.unevaluated&&(G.props!==!0||G.items!==!0))return Y.if(B,()=>this.mergeEvaluated(z,a.Name)),!0}}ar.KeywordCxt=E;function H(q,z,B,G){const Y=new E(q,B,z);"code"in B?B.code(Y,G):Y.$data&&B.validate?(0,s.funcKeywordCode)(Y,B):"macro"in B?(0,s.macroKeywordCode)(Y,B):(B.compile||B.validate)&&(0,s.funcKeywordCode)(Y,B)}const W=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function le(q,{dataLevel:z,dataNames:B,dataPathArr:G}){let Y,ae;if(q==="")return l.default.rootData;if(q[0]==="/"){if(!W.test(q))throw new Error(`Invalid JSON-pointer: ${q}`);Y=q,ae=l.default.rootData}else{const ee=fe.exec(q);if(!ee)throw new Error(`Invalid JSON-pointer: ${q}`);const ve=+ee[1];if(Y=ee[2],Y==="#"){if(ve>=z)throw new Error(qe("property/index",ve));return G[z-ve]}if(ve>z)throw new Error(qe("data",ve));if(ae=B[z-ve],!Y)return ae}let de=ae;const Ae=Y.split("/");for(const ee of Ae)ee&&(ae=(0,a._)`${ae}${(0,a.getProperty)((0,u.unescapeJsonPointer)(ee))}`,de=(0,a._)`${de} && ${ae}`);return de;function qe(ee,ve){return`Cannot access ${ee} ${ve} levels up, current level is ${z}`}}return ar.getData=le,ar}var zs={},lg;function pc(){if(lg)return zs;lg=1,Object.defineProperty(zs,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return zs.default=e,zs}var Zs={},cg;function Fs(){if(cg)return Zs;cg=1,Object.defineProperty(Zs,"__esModule",{value:!0});const e=js();class t extends Error{constructor(n,o,s,i){super(i||`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 Zs.default=t,Zs}var $t={},ug;function hc(){if(ug)return $t;ug=1,Object.defineProperty($t,"__esModule",{value:!0}),$t.resolveSchema=$t.getCompilingSchema=$t.resolveRef=$t.compileSchema=$t.SchemaEnv=void 0;const e=we(),t=pc(),r=$r(),n=js(),o=ke(),s=Ds();class i{constructor(w){var g;this.refs={},this.dynamicAnchors={};let y;typeof w.schema=="object"&&(y=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(g=w.baseId)!==null&&g!==void 0?g:(0,n.normalizeId)(y?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=y?.$async,this.refs={}}}$t.SchemaEnv=i;function a(_){const w=u.call(this,_);if(w)return w;const g=(0,n.getFullPath)(this.opts.uriResolver,_.root.baseId),{es5:y,lines:b}=this.opts.code,{ownProperties:S}=this.opts,$=new e.CodeGen(this.scope,{es5:y,lines:b,ownProperties:S});let k;_.$async&&(k=$.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=$.scopeName("validate");_.validateName=I;const P={gen:$,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:$.scopeValue("schema",this.opts.code.source===!0?{ref:_.schema,code:(0,e.stringify)(_.schema)}:{ref:_.schema}),validateName:I,ValidationError:k,schema:_.schema,schemaEnv:_,rootId:g,baseId:_.baseId||g,schemaPath:e.nil,errSchemaPath:_.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let L;try{this._compilations.add(_),(0,s.validateFunctionCode)(P),$.optimize(this.opts.code.optimize);const N=$.toString();L=`${$.scopeRefs(r.default.scope)}return ${N}`,this.opts.code.process&&(L=this.opts.code.process(L,_));const D=new Function(`${r.default.self}`,`${r.default.scope}`,L)(this,this.scope.get());if(this.scope.value(I,{ref:D}),D.errors=null,D.schema=_.schema,D.schemaEnv=_,_.$async&&(D.$async=!0),this.opts.code.source===!0&&(D.source={validateName:I,validateCode:N,scopeValues:$._values}),this.opts.unevaluated){const{props:F,items:ne}=P;D.evaluated={props:F instanceof e.Name?void 0:F,items:ne instanceof e.Name?void 0:ne,dynamicProps:F instanceof e.Name,dynamicItems:ne instanceof e.Name},D.source&&(D.source.evaluated=(0,e.stringify)(D.evaluated))}return _.validate=D,_}catch(N){throw delete _.validate,delete _.validateName,L&&this.logger.error("Error compiling schema, function code:",L),N}finally{this._compilations.delete(_)}}$t.compileSchema=a;function l(_,w,g){var y;g=(0,n.resolveUrl)(this.opts.uriResolver,w,g);const b=_.refs[g];if(b)return b;let S=f.call(this,_,g);if(S===void 0){const $=(y=_.localRefs)===null||y===void 0?void 0:y[g],{schemaId:k}=this.opts;$&&(S=new i({schema:$,schemaId:k,root:_,baseId:w}))}if(S!==void 0)return _.refs[g]=c.call(this,S)}$t.resolveRef=l;function c(_){return(0,n.inlineRef)(_.schema,this.opts.inlineRefs)?_.schema:_.validate?_:a.call(this,_)}function u(_){for(const w of this._compilations)if(m(w,_))return w}$t.getCompilingSchema=u;function m(_,w){return _.schema===w.schema&&_.root===w.root&&_.baseId===w.baseId}function f(_,w){let g;for(;typeof(g=this.refs[w])=="string";)w=g;return g||this.schemas[w]||p.call(this,_,w)}function p(_,w){const g=this.opts.uriResolver.parse(w),y=(0,n._getFullPath)(this.opts.uriResolver,g);let b=(0,n.getFullPath)(this.opts.uriResolver,_.baseId,void 0);if(Object.keys(_.schema).length>0&&y===b)return v.call(this,g,_);const S=(0,n.normalizeId)(y),$=this.refs[S]||this.schemas[S];if(typeof $=="string"){const k=p.call(this,_,$);return typeof k?.schema!="object"?void 0:v.call(this,g,k)}if(typeof $?.schema=="object"){if($.validate||a.call(this,$),S===(0,n.normalizeId)(w)){const{schema:k}=$,{schemaId:I}=this.opts,P=k[I];return P&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,P)),new i({schema:k,schemaId:I,root:_,baseId:b})}return v.call(this,g,$)}}$t.resolveSchema=p;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(_,{baseId:w,schema:g,root:y}){var b;if(((b=_.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const k of _.fragment.slice(1).split("/")){if(typeof g=="boolean")return;const I=g[(0,o.unescapeFragment)(k)];if(I===void 0)return;g=I;const P=typeof g=="object"&&g[this.opts.schemaId];!h.has(k)&&P&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,P))}let S;if(typeof g!="boolean"&&g.$ref&&!(0,o.schemaHasRulesButRef)(g,this.RULES)){const k=(0,n.resolveUrl)(this.opts.uriResolver,w,g.$ref);S=p.call(this,y,k)}const{schemaId:$}=this.opts;if(S=S||new i({schema:g,schemaId:$,root:y,baseId:w}),S.schema!==S.root.schema)return S}return $t}const LE={$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 Vs={},wo={exports:{}},fc,dg;function pg(){if(dg)return fc;dg=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(f){let p="",h=0,v=0;for(v=0;v<f.length;v++)if(h=f[v].charCodeAt(0),h!==48){if(!(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102))return"";p+=f[v];break}for(v+=1;v<f.length;v++){if(h=f[v].charCodeAt(0),!(h>=48&&h<=57||h>=65&&h<=70||h>=97&&h<=102))return"";p+=f[v]}return p}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(f){return f.length=0,!0}function s(f,p,h){if(f.length){const v=r(f);if(v!=="")p.push(v);else return h.error=!0,!1;f.length=0}return!0}function i(f){let p=0;const h={error:!1,address:"",zone:""},v=[],_=[];let w=!1,g=!1,y=s;for(let b=0;b<f.length;b++){const S=f[b];if(!(S==="["||S==="]"))if(S===":"){if(w===!0&&(g=!0),!y(_,v,h))break;if(++p>7){h.error=!0;break}b>0&&f[b-1]===":"&&(w=!0),v.push(":");continue}else if(S==="%"){if(!y(_,v,h))break;y=o}else{_.push(S);continue}}return _.length&&(y===o?h.zone=_.join(""):g?v.push(_.join("")):v.push(r(_))),h.address=v.join(""),h}function a(f){if(l(f,":")<2)return{host:f,isIPV6:!1};const p=i(f);if(p.error)return{host:f,isIPV6:!1};{let h=p.address,v=p.address;return p.zone&&(h+="%"+p.zone,v+="%25"+p.zone),{host:h,isIPV6:!0,escapedHost:v}}}function l(f,p){let h=0;for(let v=0;v<f.length;v++)f[v]===p&&h++;return h}function c(f){let p=f;const h=[];let v=-1,_=0;for(;_=p.length;){if(_===1){if(p===".")break;if(p==="/"){h.push("/");break}else{h.push(p);break}}else if(_===2){if(p[0]==="."){if(p[1]===".")break;if(p[1]==="/"){p=p.slice(2);continue}}else if(p[0]==="/"&&(p[1]==="."||p[1]==="/")){h.push("/");break}}else if(_===3&&p==="/.."){h.length!==0&&h.pop(),h.push("/");break}if(p[0]==="."){if(p[1]==="."){if(p[2]==="/"){p=p.slice(3);continue}}else if(p[1]==="/"){p=p.slice(2);continue}}else if(p[0]==="/"&&p[1]==="."){if(p[2]==="/"){p=p.slice(2);continue}else if(p[2]==="."&&p[3]==="/"){p=p.slice(3),h.length!==0&&h.pop();continue}}if((v=p.indexOf("/",1))===-1){h.push(p);break}else h.push(p.slice(0,v)),p=p.slice(v)}return h.join("")}function u(f,p){const h=p!==!0?escape:unescape;return f.scheme!==void 0&&(f.scheme=h(f.scheme)),f.userinfo!==void 0&&(f.userinfo=h(f.userinfo)),f.host!==void 0&&(f.host=h(f.host)),f.path!==void 0&&(f.path=h(f.path)),f.query!==void 0&&(f.query=h(f.query)),f.fragment!==void 0&&(f.fragment=h(f.fragment)),f}function m(f){const p=[];if(f.userinfo!==void 0&&(p.push(f.userinfo),p.push("@")),f.host!==void 0){let h=unescape(f.host);if(!t(h)){const v=a(h);v.isIPV6===!0?h=`[${v.escapedHost}]`:h=f.host}p.push(h)}return(typeof f.port=="number"||typeof f.port=="string")&&(p.push(":"),p.push(String(f.port))),p.length?p.join(""):void 0}return fc={nonSimpleDomain:n,recomposeAuthority:m,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:r},fc}var mc,hg;function UE(){if(hg)return mc;hg=1;const{isUUID:e}=pg(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(S){return r.indexOf(S)!==-1}function o(S){return S.secure===!0?!0:S.secure===!1?!1:S.scheme?S.scheme.length===3&&(S.scheme[0]==="w"||S.scheme[0]==="W")&&(S.scheme[1]==="s"||S.scheme[1]==="S")&&(S.scheme[2]==="s"||S.scheme[2]==="S"):!1}function s(S){return S.host||(S.error=S.error||"HTTP URIs must have a host."),S}function i(S){const $=String(S.scheme).toLowerCase()==="https";return(S.port===($?443:80)||S.port==="")&&(S.port=void 0),S.path||(S.path="/"),S}function a(S){return S.secure=o(S),S.resourceName=(S.path||"/")+(S.query?"?"+S.query:""),S.path=void 0,S.query=void 0,S}function l(S){if((S.port===(o(S)?443:80)||S.port==="")&&(S.port=void 0),typeof S.secure=="boolean"&&(S.scheme=S.secure?"wss":"ws",S.secure=void 0),S.resourceName){const[$,k]=S.resourceName.split("?");S.path=$&&$!=="/"?$:void 0,S.query=k,S.resourceName=void 0}return S.fragment=void 0,S}function c(S,$){if(!S.path)return S.error="URN can not be parsed",S;const k=S.path.match(t);if(k){const I=$.scheme||S.scheme||"urn";S.nid=k[1].toLowerCase(),S.nss=k[2];const P=`${I}:${$.nid||S.nid}`,L=b(P);S.path=void 0,L&&(S=L.parse(S,$))}else S.error=S.error||"URN can not be parsed.";return S}function u(S,$){if(S.nid===void 0)throw new Error("URN without nid cannot be serialized");const k=$.scheme||S.scheme||"urn",I=S.nid.toLowerCase(),P=`${k}:${$.nid||I}`,L=b(P);L&&(S=L.serialize(S,$));const N=S,j=S.nss;return N.path=`${I||$.nid}:${j}`,$.skipEscape=!0,N}function m(S,$){const k=S;return k.uuid=k.nss,k.nss=void 0,!$.tolerant&&(!k.uuid||!e(k.uuid))&&(k.error=k.error||"UUID is not valid."),k}function f(S){const $=S;return $.nss=(S.uuid||"").toLowerCase(),$}const p={scheme:"http",domainHost:!0,parse:s,serialize:i},h={scheme:"https",domainHost:p.domainHost,parse:s,serialize:i},v={scheme:"ws",domainHost:!0,parse:a,serialize:l},_={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},y={http:p,https:h,ws:v,wss:_,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:m,serialize:f,skipNormalize:!0}};Object.setPrototypeOf(y,null);function b(S){return S&&(y[S]||y[S.toLowerCase()])||void 0}return mc={wsIsSecure:o,SCHEMES:y,isValidSchemeName:n,getSchemeHandler:b},mc}var fg;function jE(){if(fg)return wo.exports;fg=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=pg(),{SCHEMES:i,getSchemeHandler:a}=UE();function l(_,w){return typeof _=="string"?_=f(h(_,w),w):typeof _=="object"&&(_=h(f(_,w),w)),_}function c(_,w,g){const y=g?Object.assign({scheme:"null"},g):{scheme:"null"},b=u(h(_,y),h(w,y),y,!0);return y.skipEscape=!0,f(b,y)}function u(_,w,g,y){const b={};return y||(_=h(f(_,g),g),w=h(f(w,g),g)),g=g||{},!g.tolerant&&w.scheme?(b.scheme=w.scheme,b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=t(w.path||""),b.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(b.userinfo=w.userinfo,b.host=w.host,b.port=w.port,b.path=t(w.path||""),b.query=w.query):(w.path?(w.path[0]==="/"?b.path=t(w.path):((_.userinfo!==void 0||_.host!==void 0||_.port!==void 0)&&!_.path?b.path="/"+w.path:_.path?b.path=_.path.slice(0,_.path.lastIndexOf("/")+1)+w.path:b.path=w.path,b.path=t(b.path)),b.query=w.query):(b.path=_.path,w.query!==void 0?b.query=w.query:b.query=_.query),b.userinfo=_.userinfo,b.host=_.host,b.port=_.port),b.scheme=_.scheme),b.fragment=w.fragment,b}function m(_,w,g){return typeof _=="string"?(_=unescape(_),_=f(n(h(_,g),!0),{...g,skipEscape:!0})):typeof _=="object"&&(_=f(n(_,!0),{...g,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=f(n(h(w,g),!0),{...g,skipEscape:!0})):typeof w=="object"&&(w=f(n(w,!0),{...g,skipEscape:!0})),_.toLowerCase()===w.toLowerCase()}function f(_,w){const g={host:_.host,scheme:_.scheme,userinfo:_.userinfo,port:_.port,path:_.path,query:_.query,nid:_.nid,nss:_.nss,uuid:_.uuid,fragment:_.fragment,reference:_.reference,resourceName:_.resourceName,secure:_.secure,error:""},y=Object.assign({},w),b=[],S=a(y.scheme||g.scheme);S&&S.serialize&&S.serialize(g,y),g.path!==void 0&&(y.skipEscape?g.path=unescape(g.path):(g.path=escape(g.path),g.scheme!==void 0&&(g.path=g.path.split("%3A").join(":")))),y.reference!=="suffix"&&g.scheme&&b.push(g.scheme,":");const $=r(g);if($!==void 0&&(y.reference!=="suffix"&&b.push("//"),b.push($),g.path&&g.path[0]!=="/"&&b.push("/")),g.path!==void 0){let k=g.path;!y.absolutePath&&(!S||!S.absolutePath)&&(k=t(k)),$===void 0&&k[0]==="/"&&k[1]==="/"&&(k="/%2F"+k.slice(2)),b.push(k)}return g.query!==void 0&&b.push("?",g.query),g.fragment!==void 0&&b.push("#",g.fragment),b.join("")}const p=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function h(_,w){const g=Object.assign({},w),y={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;g.reference==="suffix"&&(g.scheme?_=g.scheme+":"+_:_="//"+_);const S=_.match(p);if(S){if(y.scheme=S[1],y.userinfo=S[3],y.host=S[4],y.port=parseInt(S[5],10),y.path=S[6]||"",y.query=S[7],y.fragment=S[8],isNaN(y.port)&&(y.port=S[5]),y.host)if(o(y.host)===!1){const I=e(y.host);y.host=I.host.toLowerCase(),b=I.isIPV6}else b=!0;y.scheme===void 0&&y.userinfo===void 0&&y.host===void 0&&y.port===void 0&&y.query===void 0&&!y.path?y.reference="same-document":y.scheme===void 0?y.reference="relative":y.fragment===void 0?y.reference="absolute":y.reference="uri",g.reference&&g.reference!=="suffix"&&g.reference!==y.reference&&(y.error=y.error||"URI is not a "+g.reference+" reference.");const $=a(g.scheme||y.scheme);if(!g.unicodeSupport&&(!$||!$.unicodeSupport)&&y.host&&(g.domainHost||$&&$.domainHost)&&b===!1&&s(y.host))try{y.host=URL.domainToASCII(y.host.toLowerCase())}catch(k){y.error=y.error||"Host's domain name can not be converted to ASCII: "+k}(!$||$&&!$.skipNormalize)&&(_.indexOf("%")!==-1&&(y.scheme!==void 0&&(y.scheme=unescape(y.scheme)),y.host!==void 0&&(y.host=unescape(y.host))),y.path&&(y.path=escape(unescape(y.path))),y.fragment&&(y.fragment=encodeURI(decodeURIComponent(y.fragment)))),$&&$.parse&&$.parse(y,g)}else y.error=y.error||"URI can not be parsed.";return y}const v={SCHEMES:i,normalize:l,resolve:c,resolveComponent:u,equal:m,serialize:f,parse:h};return wo.exports=v,wo.exports.default=v,wo.exports.fastUri=v,wo.exports}var mg;function DE(){if(mg)return Vs;mg=1,Object.defineProperty(Vs,"__esModule",{value:!0});const e=jE();return e.code='require("ajv/dist/runtime/uri").default',Vs.default=e,Vs}var gg;function zE(){return gg||(gg=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=Ds();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=we();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=pc(),o=Fs(),s=G2(),i=hc(),a=we(),l=js(),c=Us(),u=ke(),m=LE,f=DE(),p=(V,M)=>new RegExp(V,M);p.code="new RegExp";const h=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_={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.'},g=200;function y(V){var M,Z,U,T,x,E,H,W,fe,le,q,z,B,G,Y,ae,de,Ae,qe,ee,ve,ct,Se,mt,pr;const gt=V.strict,Xe=(M=V.code)===null||M===void 0?void 0:M.optimize,xt=Xe===!0||Xe===void 0?1:Xe||0,Rr=(U=(Z=V.code)===null||Z===void 0?void 0:Z.regExp)!==null&&U!==void 0?U:p,xr=(T=V.uriResolver)!==null&&T!==void 0?T:f.default;return{strictSchema:(E=(x=V.strictSchema)!==null&&x!==void 0?x:gt)!==null&&E!==void 0?E:!0,strictNumbers:(W=(H=V.strictNumbers)!==null&&H!==void 0?H:gt)!==null&&W!==void 0?W:!0,strictTypes:(le=(fe=V.strictTypes)!==null&&fe!==void 0?fe:gt)!==null&&le!==void 0?le:"log",strictTuples:(z=(q=V.strictTuples)!==null&&q!==void 0?q:gt)!==null&&z!==void 0?z:"log",strictRequired:(G=(B=V.strictRequired)!==null&&B!==void 0?B:gt)!==null&&G!==void 0?G:!1,code:V.code?{...V.code,optimize:xt,regExp:Rr}:{optimize:xt,regExp:Rr},loopRequired:(Y=V.loopRequired)!==null&&Y!==void 0?Y:g,loopEnum:(ae=V.loopEnum)!==null&&ae!==void 0?ae:g,meta:(de=V.meta)!==null&&de!==void 0?de:!0,messages:(Ae=V.messages)!==null&&Ae!==void 0?Ae:!0,inlineRefs:(qe=V.inlineRefs)!==null&&qe!==void 0?qe:!0,schemaId:(ee=V.schemaId)!==null&&ee!==void 0?ee:"$id",addUsedSchema:(ve=V.addUsedSchema)!==null&&ve!==void 0?ve:!0,validateSchema:(ct=V.validateSchema)!==null&&ct!==void 0?ct:!0,validateFormats:(Se=V.validateFormats)!==null&&Se!==void 0?Se:!0,unicodeRegExp:(mt=V.unicodeRegExp)!==null&&mt!==void 0?mt:!0,int32range:(pr=V.int32range)!==null&&pr!==void 0?pr:!0,uriResolver:xr}}class b{constructor(M={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,M=this.opts={...M,...y(M)};const{es5:Z,lines:U}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:Z,lines:U}),this.logger=j(M.logger);const T=M.validateFormats;M.validateFormats=!1,this.RULES=(0,s.getRules)(),S.call(this,_,M,"NOT SUPPORTED"),S.call(this,w,M,"DEPRECATED","warn"),this._metaOpts=L.call(this),M.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),M.keywords&&P.call(this,M.keywords),typeof M.meta=="object"&&this.addMetaSchema(M.meta),k.call(this),M.validateFormats=T}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:M,meta:Z,schemaId:U}=this.opts;let T=m;U==="id"&&(T={...m},T.id=T.$id,delete T.$id),Z&&M&&this.addMetaSchema(T,T[U],!1)}defaultMeta(){const{meta:M,schemaId:Z}=this.opts;return this.opts.defaultMeta=typeof M=="object"?M[Z]||M:void 0}validate(M,Z){let U;if(typeof M=="string"){if(U=this.getSchema(M),!U)throw new Error(`no schema with key or ref "${M}"`)}else U=this.compile(M);const T=U(Z);return"$async"in U||(this.errors=U.errors),T}compile(M,Z){const U=this._addSchema(M,Z);return U.validate||this._compileSchemaEnv(U)}compileAsync(M,Z){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:U}=this.opts;return T.call(this,M,Z);async function T(le,q){await x.call(this,le.$schema);const z=this._addSchema(le,q);return z.validate||E.call(this,z)}async function x(le){le&&!this.getSchema(le)&&await T.call(this,{$ref:le},!0)}async function E(le){try{return this._compileSchemaEnv(le)}catch(q){if(!(q instanceof o.default))throw q;return H.call(this,q),await W.call(this,q.missingSchema),E.call(this,le)}}function H({missingSchema:le,missingRef:q}){if(this.refs[le])throw new Error(`AnySchema ${le} is loaded but ${q} cannot be resolved`)}async function W(le){const q=await fe.call(this,le);this.refs[le]||await x.call(this,q.$schema),this.refs[le]||this.addSchema(q,le,Z)}async function fe(le){const q=this._loading[le];if(q)return q;try{return await(this._loading[le]=U(le))}finally{delete this._loading[le]}}}addSchema(M,Z,U,T=this.opts.validateSchema){if(Array.isArray(M)){for(const E of M)this.addSchema(E,void 0,U,T);return this}let x;if(typeof M=="object"){const{schemaId:E}=this.opts;if(x=M[E],x!==void 0&&typeof x!="string")throw new Error(`schema ${E} must be string`)}return Z=(0,l.normalizeId)(Z||x),this._checkUnique(Z),this.schemas[Z]=this._addSchema(M,U,Z,T,!0),this}addMetaSchema(M,Z,U=this.opts.validateSchema){return this.addSchema(M,Z,!0,U),this}validateSchema(M,Z){if(typeof M=="boolean")return!0;let U;if(U=M.$schema,U!==void 0&&typeof U!="string")throw new Error("$schema must be a string");if(U=U||this.opts.defaultMeta||this.defaultMeta(),!U)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const T=this.validate(U,M);if(!T&&Z){const x="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(x);else throw new Error(x)}return T}getSchema(M){let Z;for(;typeof(Z=$.call(this,M))=="string";)M=Z;if(Z===void 0){const{schemaId:U}=this.opts,T=new i.SchemaEnv({schema:{},schemaId:U});if(Z=i.resolveSchema.call(this,T,M),!Z)return;this.refs[M]=Z}return Z.validate||this._compileSchemaEnv(Z)}removeSchema(M){if(M instanceof RegExp)return this._removeAllSchemas(this.schemas,M),this._removeAllSchemas(this.refs,M),this;switch(typeof M){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const Z=$.call(this,M);return typeof Z=="object"&&this._cache.delete(Z.schema),delete this.schemas[M],delete this.refs[M],this}case"object":{const Z=M;this._cache.delete(Z);let U=M[this.opts.schemaId];return U&&(U=(0,l.normalizeId)(U),delete this.schemas[U],delete this.refs[U]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(M){for(const Z of M)this.addKeyword(Z);return this}addKeyword(M,Z){let U;if(typeof M=="string")U=M,typeof Z=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Z.keyword=U);else if(typeof M=="object"&&Z===void 0){if(Z=M,U=Z.keyword,Array.isArray(U)&&!U.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(F.call(this,U,Z),!Z)return(0,u.eachItem)(U,x=>ne.call(this,x)),this;ie.call(this,Z);const T={...Z,type:(0,c.getJSONTypes)(Z.type),schemaType:(0,c.getJSONTypes)(Z.schemaType)};return(0,u.eachItem)(U,T.type.length===0?x=>ne.call(this,x,T):x=>T.type.forEach(E=>ne.call(this,x,T,E))),this}getKeyword(M){const Z=this.RULES.all[M];return typeof Z=="object"?Z.definition:!!Z}removeKeyword(M){const{RULES:Z}=this;delete Z.keywords[M],delete Z.all[M];for(const U of Z.rules){const T=U.rules.findIndex(x=>x.keyword===M);T>=0&&U.rules.splice(T,1)}return this}addFormat(M,Z){return typeof Z=="string"&&(Z=new RegExp(Z)),this.formats[M]=Z,this}errorsText(M=this.errors,{separator:Z=", ",dataVar:U="data"}={}){return!M||M.length===0?"No errors":M.map(T=>`${U}${T.instancePath} ${T.message}`).reduce((T,x)=>T+Z+x)}$dataMetaSchema(M,Z){const U=this.RULES.all;M=JSON.parse(JSON.stringify(M));for(const T of Z){const x=T.split("/").slice(1);let E=M;for(const H of x)E=E[H];for(const H in U){const W=U[H];if(typeof W!="object")continue;const{$data:fe}=W.definition,le=E[H];fe&&le&&(E[H]=he(le))}}return M}_removeAllSchemas(M,Z){for(const U in M){const T=M[U];(!Z||Z.test(U))&&(typeof T=="string"?delete M[U]:T&&!T.meta&&(this._cache.delete(T.schema),delete M[U]))}}_addSchema(M,Z,U,T=this.opts.validateSchema,x=this.opts.addUsedSchema){let E;const{schemaId:H}=this.opts;if(typeof M=="object")E=M[H];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof M!="boolean")throw new Error("schema must be object or boolean")}let W=this._cache.get(M);if(W!==void 0)return W;U=(0,l.normalizeId)(E||U);const fe=l.getSchemaRefs.call(this,M,U);return W=new i.SchemaEnv({schema:M,schemaId:H,meta:Z,baseId:U,localRefs:fe}),this._cache.set(W.schema,W),x&&!U.startsWith("#")&&(U&&this._checkUnique(U),this.refs[U]=W),T&&this.validateSchema(M,!0),W}_checkUnique(M){if(this.schemas[M]||this.refs[M])throw new Error(`schema with key or id "${M}" already exists`)}_compileSchemaEnv(M){if(M.meta?this._compileMetaSchema(M):i.compileSchema.call(this,M),!M.validate)throw new Error("ajv implementation error");return M.validate}_compileMetaSchema(M){const Z=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,M)}finally{this.opts=Z}}}b.ValidationError=n.default,b.MissingRefError=o.default,e.default=b;function S(V,M,Z,U="error"){for(const T in V){const x=T;x in M&&this.logger[U](`${Z}: option ${T}. ${V[x]}`)}}function $(V){return V=(0,l.normalizeId)(V),this.schemas[V]||this.refs[V]}function k(){const V=this.opts.schemas;if(V)if(Array.isArray(V))this.addSchema(V);else for(const M in V)this.addSchema(V[M],M)}function I(){for(const V in this.opts.formats){const M=this.opts.formats[V];M&&this.addFormat(V,M)}}function P(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const M in V){const Z=V[M];Z.keyword||(Z.keyword=M),this.addKeyword(Z)}}function L(){const V={...this.opts};for(const M of h)delete V[M];return V}const N={log(){},warn(){},error(){}};function j(V){if(V===!1)return N;if(V===void 0)return console;if(V.log&&V.warn&&V.error)return V;throw new Error("logger must implement log, warn and error methods")}const D=/^[a-z_$][a-z0-9_$:-]*$/i;function F(V,M){const{RULES:Z}=this;if((0,u.eachItem)(V,U=>{if(Z.keywords[U])throw new Error(`Keyword ${U} is already defined`);if(!D.test(U))throw new Error(`Keyword ${U} has invalid name`)}),!!M&&M.$data&&!("code"in M||"validate"in M))throw new Error('$data keyword must have "code" or "validate" function')}function ne(V,M,Z){var U;const T=M?.post;if(Z&&T)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:x}=this;let E=T?x.post:x.rules.find(({type:W})=>W===Z);if(E||(E={type:Z,rules:[]},x.rules.push(E)),x.keywords[V]=!0,!M)return;const H={keyword:V,definition:{...M,type:(0,c.getJSONTypes)(M.type),schemaType:(0,c.getJSONTypes)(M.schemaType)}};M.before?ue.call(this,E,H,M.before):E.rules.push(H),x.all[V]=H,(U=M.implements)===null||U===void 0||U.forEach(W=>this.addKeyword(W))}function ue(V,M,Z){const U=V.rules.findIndex(T=>T.keyword===Z);U>=0?V.rules.splice(U,0,M):(V.rules.push(M),this.logger.warn(`rule ${Z} is not defined`))}function ie(V){let{metaSchema:M}=V;M!==void 0&&(V.$data&&this.opts.$data&&(M=he(M)),V.validateSchema=this.compile(M,!0))}const re={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function he(V){return{anyOf:[V,re]}}})(sc)),sc}var Hs={},Bs={},Js={},_g;function ZE(){if(_g)return Js;_g=1,Object.defineProperty(Js,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Js.default=e,Js}var Cr={},vg;function FE(){if(vg)return Cr;vg=1,Object.defineProperty(Cr,"__esModule",{value:!0}),Cr.callRef=Cr.getValidate=void 0;const e=Fs(),t=zt(),r=we(),n=$r(),o=hc(),s=ke(),i={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:m,it:f}=c,{baseId:p,schemaEnv:h,validateName:v,opts:_,self:w}=f,{root:g}=h;if((m==="#"||m==="#/")&&p===g.baseId)return b();const y=o.resolveRef.call(w,g,p,m);if(y===void 0)throw new e.default(f.opts.uriResolver,p,m);if(y instanceof o.SchemaEnv)return S(y);return $(y);function b(){if(h===g)return l(c,v,h,h.$async);const k=u.scopeValue("root",{ref:g});return l(c,(0,r._)`${k}.validate`,g,g.$async)}function S(k){const I=a(c,k);l(c,I,k,k.$async)}function $(k){const I=u.scopeValue("schema",_.code.source===!0?{ref:k,code:(0,r.stringify)(k)}:{ref:k}),P=u.name("valid"),L=c.subschema({schema:k,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:m},P);c.mergeEvaluated(L),c.ok(P)}}};function a(c,u){const{gen:m}=c;return u.validate?m.scopeValue("validate",{ref:u.validate}):(0,r._)`${m.scopeValue("wrapper",{ref:u})}.validate`}Cr.getValidate=a;function l(c,u,m,f){const{gen:p,it:h}=c,{allErrors:v,schemaEnv:_,opts:w}=h,g=w.passContext?n.default.this:r.nil;f?y():b();function y(){if(!_.$async)throw new Error("async schema referenced by sync schema");const k=p.let("valid");p.try(()=>{p.code((0,r._)`await ${(0,t.callValidateCode)(c,u,g)}`),$(u),v||p.assign(k,!0)},I=>{p.if((0,r._)`!(${I} instanceof ${h.ValidationError})`,()=>p.throw(I)),S(I),v||p.assign(k,!1)}),c.ok(k)}function b(){c.result((0,t.callValidateCode)(c,u,g),()=>$(u),()=>S(u))}function S(k){const I=(0,r._)`${k}.errors`;p.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${I} : ${n.default.vErrors}.concat(${I})`),p.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function $(k){var I;if(!h.opts.unevaluated)return;const P=(I=m?.validate)===null||I===void 0?void 0:I.evaluated;if(h.props!==!0)if(P&&!P.dynamicProps)P.props!==void 0&&(h.props=s.mergeEvaluated.props(p,P.props,h.props));else{const L=p.var("props",(0,r._)`${k}.evaluated.props`);h.props=s.mergeEvaluated.props(p,L,h.props,r.Name)}if(h.items!==!0)if(P&&!P.dynamicItems)P.items!==void 0&&(h.items=s.mergeEvaluated.items(p,P.items,h.items));else{const L=p.var("items",(0,r._)`${k}.evaluated.items`);h.items=s.mergeEvaluated.items(p,L,h.items,r.Name)}}}return Cr.callRef=l,Cr.default=i,Cr}var yg;function VE(){if(yg)return Bs;yg=1,Object.defineProperty(Bs,"__esModule",{value:!0});const e=ZE(),t=FE(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Bs.default=r,Bs}var Ws={},Gs={},wg;function HE(){if(wg)return Gs;wg=1,Object.defineProperty(Gs,"__esModule",{value:!0});const e=we(),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:i})=>(0,e.str)`must be ${r[s].okStr} ${i}`,params:({keyword:s,schemaCode:i})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${i}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:i,data:a,schemaCode:l}=s;s.fail$data((0,e._)`${a} ${r[i].fail} ${l} || isNaN(${a})`)}};return Gs.default=o,Gs}var Ks={},bg;function BE(){if(bg)return Ks;bg=1,Object.defineProperty(Ks,"__esModule",{value:!0});const e=we(),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:i,it:a}=n,l=a.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._)`(${i} === 0 || (${c} = ${s}/${i}, ${u}))`)}};return Ks.default=r,Ks}var Ys={},Qs={},Sg;function JE(){if(Sg)return Qs;Sg=1,Object.defineProperty(Qs,"__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 Qs.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Qs}var $g;function WE(){if($g)return Ys;$g=1,Object.defineProperty(Ys,"__esModule",{value:!0});const e=we(),t=ke(),r=JE(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:i}){const a=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${i} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:i,data:a,schemaCode:l,it:c}=s,u=i==="maxLength"?e.operators.GT:e.operators.LT,m=c.opts.unicode===!1?(0,e._)`${a}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${a})`;s.fail$data((0,e._)`${m} ${u} ${l}`)}};return Ys.default=o,Ys}var Xs={},Cg;function GE(){if(Cg)return Xs;Cg=1,Object.defineProperty(Xs,"__esModule",{value:!0});const e=zt(),t=we(),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:i,schema:a,schemaCode:l,it:c}=o,u=c.opts.unicodeRegExp?"u":"",m=i?(0,t._)`(new RegExp(${l}, ${u}))`:(0,e.usePattern)(o,a);o.fail$data((0,t._)`!${m}.test(${s})`)}};return Xs.default=n,Xs}var ea={},kg;function KE(){if(kg)return ea;kg=1,Object.defineProperty(ea,"__esModule",{value:!0});const e=we(),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:i}=n,a=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${a} ${i}`)}};return ea.default=r,ea}var ta={},Eg;function YE(){if(Eg)return ta;Eg=1,Object.defineProperty(ta,"__esModule",{value:!0});const e=zt(),t=we(),r=ke(),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:i,schema:a,schemaCode:l,data:c,$data:u,it:m}=s,{opts:f}=m;if(!u&&a.length===0)return;const p=a.length>=f.loopRequired;if(m.allErrors?h():v(),f.strictRequired){const g=s.parentSchema.properties,{definedProperties:y}=s.it;for(const b of a)if(g?.[b]===void 0&&!y.has(b)){const S=m.schemaEnv.baseId+m.errSchemaPath,$=`required property "${b}" is not defined at "${S}" (strictRequired)`;(0,r.checkStrictMode)(m,$,m.opts.strictRequired)}}function h(){if(p||u)s.block$data(t.nil,_);else for(const g of a)(0,e.checkReportMissingProp)(s,g)}function v(){const g=i.let("missing");if(p||u){const y=i.let("valid",!0);s.block$data(y,()=>w(g,y)),s.ok(y)}else i.if((0,e.checkMissingProp)(s,a,g)),(0,e.reportMissingProp)(s,g),i.else()}function _(){i.forOf("prop",l,g=>{s.setParams({missingProperty:g}),i.if((0,e.noPropertyInData)(i,c,g,f.ownProperties),()=>s.error())})}function w(g,y){s.setParams({missingProperty:g}),i.forOf(g,l,()=>{i.assign(y,(0,e.propertyInData)(i,c,g,f.ownProperties)),i.if((0,t.not)(y),()=>{s.error(),i.break()})},t.nil)}}};return ta.default=o,ta}var ra={},Tg;function QE(){if(Tg)return ra;Tg=1,Object.defineProperty(ra,"__esModule",{value:!0});const e=we(),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:i}=n,a=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${a} ${i}`)}};return ra.default=r,ra}var na={},oa={},Ig;function gc(){if(Ig)return oa;Ig=1,Object.defineProperty(oa,"__esModule",{value:!0});const e=og();return e.code='require("ajv/dist/runtime/equal").default',oa.default=e,oa}var Rg;function XE(){if(Rg)return na;Rg=1,Object.defineProperty(na,"__esModule",{value:!0});const e=Us(),t=we(),r=ke(),n=gc(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:a}})=>(0,t.str)`must NOT have duplicate items (items ## ${a} and ${i} are identical)`,params:({params:{i,j:a}})=>(0,t._)`{i: ${i}, j: ${a}}`},code(i){const{gen:a,data:l,$data:c,schema:u,parentSchema:m,schemaCode:f,it:p}=i;if(!c&&!u)return;const h=a.let("valid"),v=m.items?(0,e.getSchemaTypes)(m.items):[];i.block$data(h,_,(0,t._)`${f} === false`),i.ok(h);function _(){const b=a.let("i",(0,t._)`${l}.length`),S=a.let("j");i.setParams({i:b,j:S}),a.assign(h,!0),a.if((0,t._)`${b} > 1`,()=>(w()?g:y)(b,S))}function w(){return v.length>0&&!v.some(b=>b==="object"||b==="array")}function g(b,S){const $=a.name("item"),k=(0,e.checkDataTypes)(v,$,p.opts.strictNumbers,e.DataType.Wrong),I=a.const("indices",(0,t._)`{}`);a.for((0,t._)`;${b}--;`,()=>{a.let($,(0,t._)`${l}[${b}]`),a.if(k,(0,t._)`continue`),v.length>1&&a.if((0,t._)`typeof ${$} == "string"`,(0,t._)`${$} += "_"`),a.if((0,t._)`typeof ${I}[${$}] == "number"`,()=>{a.assign(S,(0,t._)`${I}[${$}]`),i.error(),a.assign(h,!1).break()}).code((0,t._)`${I}[${$}] = ${b}`)})}function y(b,S){const $=(0,r.useFunc)(a,n.default),k=a.name("outer");a.label(k).for((0,t._)`;${b}--;`,()=>a.for((0,t._)`${S} = ${b}; ${S}--;`,()=>a.if((0,t._)`${$}(${l}[${b}], ${l}[${S}])`,()=>{i.error(),a.assign(h,!1).break(k)})))}}};return na.default=s,na}var sa={},xg;function eT(){if(xg)return sa;xg=1,Object.defineProperty(sa,"__esModule",{value:!0});const e=we(),t=ke(),r=gc(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:i,data:a,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(i,r.default)}(${a}, ${c})`):s.fail((0,e._)`${u} !== ${a}`)}};return sa.default=o,sa}var aa={},Pg;function tT(){if(Pg)return aa;Pg=1,Object.defineProperty(aa,"__esModule",{value:!0});const e=we(),t=ke(),r=gc(),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:i,data:a,$data:l,schema:c,schemaCode:u,it:m}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const f=c.length>=m.opts.loopEnum;let p;const h=()=>p??(p=(0,t.useFunc)(i,r.default));let v;if(f||l)v=i.let("valid"),s.block$data(v,_);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const g=i.const("vSchema",u);v=(0,e.or)(...c.map((y,b)=>w(g,b)))}s.pass(v);function _(){i.assign(v,!1),i.forOf("v",u,g=>i.if((0,e._)`${h()}(${a}, ${g})`,()=>i.assign(v,!0).break()))}function w(g,y){const b=c[y];return typeof b=="object"&&b!==null?(0,e._)`${h()}(${a}, ${g}[${y}])`:(0,e._)`${a} === ${b}`}}};return aa.default=o,aa}var Og;function rT(){if(Og)return Ws;Og=1,Object.defineProperty(Ws,"__esModule",{value:!0});const e=HE(),t=BE(),r=WE(),n=GE(),o=KE(),s=YE(),i=QE(),a=XE(),l=eT(),c=tT(),u=[e.default,t.default,r.default,n.default,o.default,s.default,i.default,a.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return Ws.default=u,Ws}var ia={},Sn={},Mg;function Ag(){if(Mg)return Sn;Mg=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.validateAdditionalItems=void 0;const e=we(),t=ke(),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:i,it:a}=s,{items:l}=i;if(!Array.isArray(l)){(0,t.checkStrictMode)(a,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,i){const{gen:a,schema:l,data:c,keyword:u,it:m}=s;m.items=!0;const f=a.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:i.length}),s.pass((0,e._)`${f} <= ${i.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(m,l)){const h=a.var("valid",(0,e._)`${f} <= ${i.length}`);a.if((0,e.not)(h),()=>p(h)),s.ok(h)}function p(h){a.forRange("i",i.length,f,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},h),m.allErrors||a.if((0,e.not)(h),()=>a.break())})}}return Sn.validateAdditionalItems=o,Sn.default=n,Sn}var la={},$n={},Ng;function qg(){if(Ng)return $n;Ng=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.validateTuple=void 0;const e=we(),t=ke(),r=zt(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:i,it:a}=s;if(Array.isArray(i))return o(s,"additionalItems",i);a.items=!0,!(0,t.alwaysValidSchema)(a,i)&&s.ok((0,r.validateArray)(s))}};function o(s,i,a=s.schema){const{gen:l,parentSchema:c,data:u,keyword:m,it:f}=s;v(c),f.opts.unevaluated&&a.length&&f.items!==!0&&(f.items=t.mergeEvaluated.items(l,a.length,f.items));const p=l.name("valid"),h=l.const("len",(0,e._)`${u}.length`);a.forEach((_,w)=>{(0,t.alwaysValidSchema)(f,_)||(l.if((0,e._)`${h} > ${w}`,()=>s.subschema({keyword:m,schemaProp:w,dataProp:w},p)),s.ok(p))});function v(_){const{opts:w,errSchemaPath:g}=f,y=a.length,b=y===_.minItems&&(y===_.maxItems||_[i]===!1);if(w.strictTuples&&!b){const S=`"${m}" is ${y}-tuple, but minItems or maxItems/${i} are not specified or different at path "${g}"`;(0,t.checkStrictMode)(f,S,w.strictTuples)}}}return $n.validateTuple=o,$n.default=n,$n}var Lg;function nT(){if(Lg)return la;Lg=1,Object.defineProperty(la,"__esModule",{value:!0});const e=qg(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return la.default=t,la}var ca={},Ug;function oT(){if(Ug)return ca;Ug=1,Object.defineProperty(ca,"__esModule",{value:!0});const e=we(),t=ke(),r=zt(),n=Ag(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,e.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,e._)`{limit: ${i}}`},code(i){const{schema:a,parentSchema:l,it:c}=i,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,a)&&(u?(0,n.validateAdditionalItems)(i,u):i.ok((0,r.validateArray)(i)))}};return ca.default=s,ca}var ua={},jg;function sT(){if(jg)return ua;jg=1,Object.defineProperty(ua,"__esModule",{value:!0});const e=we(),t=ke(),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:i,parentSchema:a,data:l,it:c}=o;let u,m;const{minContains:f,maxContains:p}=a;c.opts.next?(u=f===void 0?1:f,m=p):u=1;const h=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,i)){let y=(0,e._)`${h} >= ${u}`;m!==void 0&&(y=(0,e._)`${y} && ${h} <= ${m}`),o.pass(y);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`,_)):(s.let(v,!1),_()),o.result(v,()=>o.reset());function _(){const y=s.name("_valid"),b=s.let("count",0);w(y,()=>s.if(y,()=>g(b)))}function w(y,b){s.forRange("i",0,h,S=>{o.subschema({keyword:"contains",dataProp:S,dataPropType:t.Type.Num,compositeRule:!0},y),b()})}function g(y){s.code((0,e._)`${y}++`),m===void 0?s.if((0,e._)`${y} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${y} > ${m}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${y} >= ${u}`,()=>s.assign(v,!0)))}}};return ua.default=n,ua}var _c={},Dg;function aT(){return Dg||(Dg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=we(),r=ke(),n=zt();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},
78
+ missingProperty: ${m},
77
79
  depsCount: ${c},
78
- 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 h=Array.isArray(l[g])?c:u;h[g]=l[g]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:g,it:h}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const p in c){const w=c[p];if(w.length===0)continue;const m=(0,n.propertyInData)(u,g,p,h.opts.ownProperties);l.setParams({property:p,depsCount:w.length,deps:w.join(", ")}),h.allErrors?u.if(m,()=>{for(const y of w)(0,n.checkReportMissingProp)(l,y)}):(u.if((0,t._)`${m} && (${(0,n.checkMissingProp)(l,w,d)})`),(0,n.reportMissingProp)(l,d),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:g,keyword:h,it:d}=l,p=u.name("valid");for(const w in c)(0,r.alwaysValidSchema)(d,c[w])||(u.if((0,n.propertyInData)(u,g,w,d.opts.ownProperties),()=>{const m=l.subschema({keyword:h,schemaProp:w},p);l.mergeValidEvaluated(m,p)},()=>u.var(p,!0)),l.ok(p))}e.validateSchemaDeps=i,e.default=o})(hl)),hl}var Os={},om;function Pk(){if(om)return Os;om=1,Object.defineProperty(Os,"__esModule",{value:!0});const e=ye(),t=Se(),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 Os.default=n,Os}var Ms={},sm;function am(){if(sm)return Ms;sm=1,Object.defineProperty(Ms,"__esModule",{value:!0});const e=Ot(),t=ye(),r=hr(),n=Se(),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:h}=a;if(!g)throw new Error("ajv implementation error");const{allErrors:d,opts:p}=h;if(h.props=!0,p.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(h,l))return;const w=(0,e.allSchemaProperties)(c.properties),m=(0,e.allSchemaProperties)(c.patternProperties);y(),a.ok((0,t._)`${g} === ${r.default.errors}`);function y(){i.forIn("key",u,S=>{!w.length&&!m.length?b(S):i.if(_(S),()=>b(S))})}function _(S){let C;if(w.length>8){const I=(0,n.schemaRefOrVal)(h,c.properties,"properties");C=(0,e.isOwnProperty)(i,I,S)}else w.length?C=(0,t.or)(...w.map(I=>(0,t._)`${S} === ${I}`)):C=t.nil;return m.length&&(C=(0,t.or)(C,...m.map(I=>(0,t._)`${(0,e.usePattern)(a,I)}.test(${S})`))),(0,t.not)(C)}function f(S){i.code((0,t._)`delete ${u}[${S}]`)}function b(S){if(p.removeAdditional==="all"||p.removeAdditional&&l===!1){f(S);return}if(l===!1){a.setParams({additionalProperty:S}),a.error(),d||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(h,l)){const C=i.name("valid");p.removeAdditional==="failing"?(k(S,C,!1),i.if((0,t.not)(C),()=>{a.reset(),f(S)})):(k(S,C),d||i.if((0,t.not)(C),()=>i.break()))}}function k(S,C,I){const x={keyword:"additionalProperties",dataProp:S,dataPropType:n.Type.Str};I===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(x,C)}}};return Ms.default=s,Ms}var Ns={},im;function Ok(){if(im)return Ns;im=1,Object.defineProperty(Ns,"__esModule",{value:!0});const e=is(),t=Ot(),r=Se(),n=am(),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 h=g.filter(m=>!(0,r.alwaysValidSchema)(u,i[m]));if(h.length===0)return;const d=a.name("valid");for(const m of h)p(m)?w(m):(a.if((0,t.propertyInData)(a,c,m,u.opts.ownProperties)),w(m),u.allErrors||a.else().var(d,!0),a.endIf()),s.it.definedProperties.add(m),s.ok(d);function p(m){return u.opts.useDefaults&&!u.compositeRule&&i[m].default!==void 0}function w(m){s.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}}};return Ns.default=o,Ns}var As={},lm;function Mk(){if(lm)return As;lm=1,Object.defineProperty(As,"__esModule",{value:!0});const e=Ot(),t=ye(),r=Se(),n=Se(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:g}=u,h=(0,e.allSchemaProperties)(i),d=h.filter(b=>(0,r.alwaysValidSchema)(u,i[b]));if(h.length===0||d.length===h.length&&(!u.opts.unevaluated||u.props===!0))return;const p=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;y();function y(){for(const b of h)p&&_(b),u.allErrors?f(b):(a.var(w,!0),f(b),a.if(w))}function _(b){for(const k in p)new RegExp(b).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function f(b){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,b)}.test(${k})`,()=>{const S=d.includes(b);S||s.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:n.Type.Str},w),u.opts.unevaluated&&m!==!0?a.assign((0,t._)`${m}[${k}]`,!0):!S&&!u.allErrors&&a.if((0,t.not)(w),()=>a.break())})})}}};return As.default=o,As}var qs={},cm;function Nk(){if(cm)return qs;cm=1,Object.defineProperty(qs,"__esModule",{value:!0});const e=Se(),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 qs.default=t,qs}var Ls={},um;function Ak(){if(um)return Ls;um=1,Object.defineProperty(Ls,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ot().validateUnion,error:{message:"must match a schema in anyOf"}};return Ls.default=t,Ls}var js={},dm;function qk(){if(dm)return js;dm=1,Object.defineProperty(js,"__esModule",{value:!0});const e=ye(),t=Se(),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),h=s.name("_valid");o.setParams({passing:g}),s.block(d),o.result(u,()=>o.reset(),()=>o.error(!0));function d(){c.forEach((p,w)=>{let m;(0,t.alwaysValidSchema)(l,p)?s.var(h,!0):m=o.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},h),w>0&&s.if((0,e._)`${h} && ${u}`).assign(u,!1).assign(g,(0,e._)`[${g}, ${w}]`).else(),s.if(h,()=>{s.assign(u,!0),s.assign(g,w),m&&o.mergeEvaluated(m,e.Name)})})}}};return js.default=n,js}var Us={},pm;function Lk(){if(pm)return Us;pm=1,Object.defineProperty(Us,"__esModule",{value:!0});const e=Se(),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 Us.default=t,Us}var zs={},fm;function jk(){if(fm)return zs;fm=1,Object.defineProperty(zs,"__esModule",{value:!0});const e=ye(),t=Se(),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),h=a.name("_valid");if(d(),s.reset(),c&&u){const w=a.let("ifClause");s.setParams({ifClause:w}),a.if(h,p("then",w),p("else",w))}else c?a.if(h,p("then")):a.if((0,e.not)(h),p("else"));s.pass(g,()=>s.error(!0));function d(){const w=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},h);s.mergeEvaluated(w)}function p(w,m){return()=>{const y=s.subschema({keyword:w},h);a.assign(g,h),s.mergeValidEvaluated(y,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 zs.default=n,zs}var Ds={},hm;function Uk(){if(hm)return Ds;hm=1,Object.defineProperty(Ds,"__esModule",{value:!0});const e=Se(),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 Ds.default=t,Ds}var mm;function zk(){if(mm)return Is;mm=1,Object.defineProperty(Is,"__esModule",{value:!0});const e=Yh(),t=Ek(),r=Xh(),n=Ik(),o=xk(),s=Rk(),a=Pk(),i=am(),l=Ok(),c=Mk(),u=Nk(),g=Ak(),h=qk(),d=Lk(),p=jk(),w=Uk();function m(y=!1){const _=[u.default,g.default,h.default,d.default,p.default,w.default,a.default,i.default,s.default,l.default,c.default];return y?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return Is.default=m,Is}var Zs={},Fs={},gm;function Dk(){if(gm)return Fs;gm=1,Object.defineProperty(Fs,"__esModule",{value:!0});const e=ye(),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:h,schemaEnv:d,self:p}=u;if(!g.validateFormats)return;i?w():m();function w(){const y=s.scopeValue("formats",{ref:p.formats,code:g.code.formats}),_=s.const("fDef",(0,e._)`${y}[${c}]`),f=s.let("fType"),b=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(f,(0,e._)`${_}.type || "string"`).assign(b,(0,e._)`${_}.validate`),()=>s.assign(f,(0,e._)`"string"`).assign(b,_)),n.fail$data((0,e.or)(k(),S()));function k(){return g.strictSchema===!1?e.nil:(0,e._)`${c} && !${b}`}function S(){const C=d.$async?(0,e._)`(${_}.async ? await ${b}(${a}) : ${b}(${a}))`:(0,e._)`${b}(${a})`,I=(0,e._)`(typeof ${b} == "function" ? ${C} : ${b}.test(${a}))`;return(0,e._)`${b} && ${b} !== true && ${f} === ${o} && !${I}`}}function m(){const y=p.formats[l];if(!y){k();return}if(y===!0)return;const[_,f,b]=S(y);_===o&&n.pass(C());function k(){if(g.strictSchema===!1){p.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${h}"`}}function S(I){const x=I instanceof RegExp?(0,e.regexpCode)(I):g.code.formats?(0,e._)`${g.code.formats}${(0,e.getProperty)(l)}`:void 0,M=s.scopeValue("formats",{key:l,ref:I,code:x});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${M}.validate`]:["string",I,M]}function C(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,e._)`await ${b}(${a})`}return typeof f=="function"?(0,e._)`${b}(${a})`:(0,e._)`${b}.test(${a})`}}}};return Fs.default=r,Fs}var vm;function Zk(){if(vm)return Zs;vm=1,Object.defineProperty(Zs,"__esModule",{value:!0});const t=[Dk().default];return Zs.default=t,Zs}var jr={},_m;function Fk(){return _m||(_m=1,Object.defineProperty(jr,"__esModule",{value:!0}),jr.contentVocabulary=jr.metadataVocabulary=void 0,jr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],jr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),jr}var ym;function Vk(){if(ym)return ps;ym=1,Object.defineProperty(ps,"__esModule",{value:!0});const e=hk(),t=$k(),r=zk(),n=Zk(),o=Fk(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ps.default=s,ps}var Vs={},Qn={},wm;function Hk(){if(wm)return Qn;wm=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(Qn.DiscrError=e={})),Qn}var bm;function Bk(){if(bm)return Vs;bm=1,Object.defineProperty(Vs,"__esModule",{value:!0});const e=ye(),t=Hk(),r=ul(),n=us(),o=Se(),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:h}=i,{oneOf:d}=g;if(!h.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=u.propertyName;if(typeof p!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const w=l.let("valid",!1),m=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(p)}`);l.if((0,e._)`typeof ${m} == "string"`,()=>y(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:p})),i.ok(w);function y(){const b=f();l.if(!1);for(const k in b)l.elseIf((0,e._)`${m} === ${k}`),l.assign(w,_(b[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:p}),l.endIf()}function _(b){const k=l.name("valid"),S=i.subschema({keyword:"oneOf",schemaProp:b},k);return i.mergeEvaluated(S,e.Name),k}function f(){var b;const k={},S=I(g);let C=!0;for(let P=0;P<d.length;P++){let U=d[P];if(U?.$ref&&!(0,o.schemaHasRulesButRef)(U,h.self.RULES)){const F=U.$ref;if(U=r.resolveRef.call(h.self,h.schemaEnv.root,h.baseId,F),U instanceof r.SchemaEnv&&(U=U.schema),U===void 0)throw new n.default(h.opts.uriResolver,h.baseId,F)}const z=(b=U?.properties)===null||b===void 0?void 0:b[p];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);C=C&&(S||I(U)),x(z,P)}if(!C)throw new Error(`discriminator: "${p}" must be required`);return k;function I({required:P}){return Array.isArray(P)&&P.includes(p)}function x(P,U){if(P.const)M(P.const,U);else if(P.enum)for(const z of P.enum)M(z,U);else throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`)}function M(P,U){if(typeof P!="string"||P in k)throw new Error(`discriminator: "${p}" values must be unique strings`);k[P]=U}}}};return Vs.default=a,Vs}const Jk={$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 km;function Sm(){return km||(km=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=dk(),n=Vk(),o=Bk(),s=Jk,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(p=>this.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(p,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=is();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=ye();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=cl();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return g.default}});var h=us();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})(ts,ts.exports)),ts.exports}var Gk=Sm(),Hs={exports:{}},ml={},Cm;function Wk(){return Cm||(Cm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(P,U){return{validate:P,compare:U}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(h(!0),d),"iso-time":t(l(),u),"iso-date-time":t(h(),p),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"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:M,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:S},int64:{type:"number",validate:C},float:{type:"number",validate:I},double:{type:"number",validate:I},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,d),"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,p),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(P){return P%4===0&&(P%100!==0||P%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(P){const U=n.exec(P);if(!U)return!1;const z=+U[1],F=+U[2],te=+U[3];return F>=1&&F<=12&&te>=1&&te<=(F===2&&r(z)?29:o[F])}function a(P,U){if(P&&U)return P>U?1:P<U?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(P){return function(z){const F=i.exec(z);if(!F)return!1;const te=+F[1],ie=+F[2],se=+F[3],ee=F[4],pe=F[5]==="-"?-1:1,V=+(F[6]||0),O=+(F[7]||0);if(V>23||O>59||P&&!ee)return!1;if(te<=23&&ie<=59&&se<60)return!0;const Z=ie-O*pe,j=te-V*pe-(Z<0?1:0);return(j===23||j===-1)&&(Z===59||Z===-1)&&se<61}}function c(P,U){if(!(P&&U))return;const z=new Date("2020-01-01T"+P).valueOf(),F=new Date("2020-01-01T"+U).valueOf();if(z&&F)return z-F}function u(P,U){if(!(P&&U))return;const z=i.exec(P),F=i.exec(U);if(z&&F)return P=z[1]+z[2]+z[3],U=F[1]+F[2]+F[3],P>U?1:P<U?-1:0}const g=/t|\s/i;function h(P){const U=l(P);return function(F){const te=F.split(g);return te.length===2&&s(te[0])&&U(te[1])}}function d(P,U){if(!(P&&U))return;const z=new Date(P).valueOf(),F=new Date(U).valueOf();if(z&&F)return z-F}function p(P,U){if(!(P&&U))return;const[z,F]=P.split(g),[te,ie]=U.split(g),se=a(z,te);if(se!==void 0)return se||c(F,ie)}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 y(P){return w.test(P)&&m.test(P)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function f(P){return _.lastIndex=0,_.test(P)}const b=-2147483648,k=2**31-1;function S(P){return Number.isInteger(P)&&P<=k&&P>=b}function C(P){return Number.isInteger(P)}function I(){return!0}const x=/[^\\]\\Z/;function M(P){if(x.test(P))return!1;try{return new RegExp(P),!0}catch{return!1}}})(ml)),ml}var gl={},Tm;function Kk(){return Tm||(Tm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Sm(),r=ye(),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:h}=i,{opts:d,self:p}=h;if(!d.validateFormats)return;const w=new t.KeywordCxt(h,p.RULES.all.format.definition,"format");w.$data?m():y();function m(){const f=l.scopeValue("formats",{ref:p.formats,code:d.code.formats}),b=l.const("fmt",(0,r._)`${f}[${w.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,_(b)))}function y(){const f=w.schema,b=p.formats[f];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${g}": format "${f}" does not define "compare" function`);const k=l.scopeValue("formats",{key:f,ref:b,code:d.code.formats?(0,r._)`${d.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})(gl)),gl}var $m;function Yk(){return $m||($m=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=Wk(),n=Kk(),o=ye(),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,h]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],d=u.formats||r.formatNames;return l(c,d,g,h),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const h=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!h)throw new Error(`Unknown format "${c}"`);return h};function l(c,u,g,h){var d,p;(d=(p=c.opts.code).formats)!==null&&d!==void 0||(p.formats=(0,o._)`require("ajv-formats/dist/formats").${h}`);for(const w of u)c.addFormat(w,g[w])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(Hs,Hs.exports)),Hs.exports}var Qk=Yk();const Xk=dd(Qk);function eS(){const e=new Gk.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Xk(e),e}class tS{constructor(t){this._ajv=t??eS()}getValidator(t){var r;const n="$id"in t&&typeof t.$id=="string"?(r=this._ajv.getSchema(t.$id))!==null&&r!==void 0?r:this._ajv.compile(t):this._ajv.compile(t);return o=>n(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}class rS{constructor(t){this._client=t}async*callToolStream(t,r=Jn,n){var o;const s=this._client,a={...n,task:(o=n?.task)!==null&&o!==void 0?o:s.isToolTask(t.name)?{}:void 0},i=s.requestStream({method:"tools/call",params:t},r,a),l=s.getToolOutputValidator(t.name);for await(const c of i){if(c.type==="result"&&l){const u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new de(ge.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{const g=l(u.structuredContent);if(!g.valid){yield{type:"error",error:new de(ge.InvalidParams,`Structured content does not match the tool's output schema: ${g.errorMessage}`)};return}}catch(g){if(g instanceof de){yield{type:"error",error:g};return}yield{type:"error",error:new de(ge.InvalidParams,`Failed to validate structured content: ${g instanceof Error?g.message:String(g)}`)};return}}yield c}}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 nS(e,t,r){var n;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!(!((n=e.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function oS(e,t,r){var n,o;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!(!((n=e.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!(!((o=e.elicitation)===null||o===void 0)&&o.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function Bs(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&&Bs(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)Bs(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)Bs(r,t)}}function sS(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 Js extends ek{constructor(t,r){var n,o;super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(o=r?.jsonSchemaValidator)!==null&&o!==void 0?o:new tS}get experimental(){return this._experimental||(this._experimental={tasks:new rS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=tk(this._capabilities,t)}setRequestHandler(t,r){var n,o,s;const a=Xf(t),i=a?.method;if(!i)throw new Error("Schema is missing a method literal");let l;if(es(i)){const u=i,g=(n=u._zod)===null||n===void 0?void 0:n.def;l=(o=g?.value)!==null&&o!==void 0?o:u.value}else{const u=i,g=u._def;l=(s=g?.value)!==null&&s!==void 0?s:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");const c=l;if(c==="elicitation/create"){const u=async(g,h)=>{var d,p,w;const m=fr(Ei,g);if(!m.success){const x=m.error instanceof Error?m.error.message:String(m.error);throw new de(ge.InvalidParams,`Invalid elicitation request: ${x}`)}const{params:y}=m.data,_=(d=y.mode)!==null&&d!==void 0?d:"form",{supportsFormMode:f,supportsUrlMode:b}=sS(this._capabilities.elicitation);if(_==="form"&&!f)throw new de(ge.InvalidParams,"Client does not support form-mode elicitation requests");if(_==="url"&&!b)throw new de(ge.InvalidParams,"Client does not support URL-mode elicitation requests");const k=await Promise.resolve(r(g,h));if(y.task){const x=fr(Bn,k);if(!x.success){const M=x.error instanceof Error?x.error.message:String(x.error);throw new de(ge.InvalidParams,`Invalid task creation result: ${M}`)}return x.data}const S=fr(Ii,k);if(!S.success){const x=S.error instanceof Error?S.error.message:String(S.error);throw new de(ge.InvalidParams,`Invalid elicitation result: ${x}`)}const C=S.data,I=_==="form"?y.requestedSchema:void 0;if(_==="form"&&C.action==="accept"&&C.content&&I&&!((w=(p=this._capabilities.elicitation)===null||p===void 0?void 0:p.form)===null||w===void 0)&&w.applyDefaults)try{Bs(I,C.content)}catch{}return C};return super.setRequestHandler(t,u)}if(c==="sampling/createMessage"){const u=async(g,h)=>{const d=fr(Ti,g);if(!d.success){const y=d.error instanceof Error?d.error.message:String(d.error);throw new de(ge.InvalidParams,`Invalid sampling request: ${y}`)}const{params:p}=d.data,w=await Promise.resolve(r(g,h));if(p.task){const y=fr(Bn,w);if(!y.success){const _=y.error instanceof Error?y.error.message:String(y.error);throw new de(ge.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}const m=fr($i,w);if(!m.success){const y=m.error instanceof Error?m.error.message:String(m.error);throw new de(ge.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(t,u)}return super.setRequestHandler(t,r)}assertCapability(t,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[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:zo,capabilities:this._capabilities,clientInfo:this._clientInfo}},H0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!a4.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"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var r,n,o,s,a;switch(t){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.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(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.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(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){var r;switch(t){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.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){var r,n;nS((n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,t,"Server")}assertTaskHandlerCapability(t){var r;this._capabilities&&oS((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Mr,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},df,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Mr,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},nf,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},rf,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Y0,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Q0,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},X0,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Mr,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Mr,r)}async callTool(t,r=Jn,n){if(this.isToolTaskRequired(t.name))throw new de(ge.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 de(ge.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 de(ge.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof de?a:new de(ge.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){var r,n,o,s;return!((s=(o=(n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests)===null||o===void 0?void 0:o.tools)===null||s===void 0)&&s.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){var r;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const n of t){if(n.outputSchema){const s=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,s)}const o=(r=n.execution)===null||r===void 0?void 0:r.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(n.name),o==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},af,r);return this.cacheToolMetadata(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Em 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(Im(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(Im(this),r)}}function aS(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function vl(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(vl).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${vl(e.cause)}`:e.message:`${e}`}function Im(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var xm=e=>{throw TypeError(e)},_l=(e,t,r)=>t.has(e)||xm("Cannot "+r),ke=(e,t,r)=>(_l(e,t,"read from private field"),r?r.call(e):t.get(e)),Fe=(e,t,r)=>t.has(e)?xm("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),je=(e,t,r,n)=>(_l(e,t,"write to private field"),t.set(e,r),r),er=(e,t,r)=>(_l(e,t,"access private method"),r),ut,Ur,un,Gs,Ws,Xn,dn,eo,gr,pn,fn,hn,to,Mt,yl,wl,bl,Rm,kl,Sl,ro,Cl,Tl;class Ks extends EventTarget{constructor(t,r){var n,o;super(),Fe(this,Mt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Fe(this,ut),Fe(this,Ur),Fe(this,un),Fe(this,Gs),Fe(this,Ws),Fe(this,Xn),Fe(this,dn),Fe(this,eo,null),Fe(this,gr),Fe(this,pn),Fe(this,fn,null),Fe(this,hn,null),Fe(this,to,null),Fe(this,wl,async s=>{var a;ke(this,pn).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){er(this,Mt,ro).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?je(this,un,new URL(s.url)):je(this,un,void 0),c!==200){er(this,Mt,ro).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){er(this,Mt,ro).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(ke(this,ut)===this.CLOSED)return;je(this,ut,this.OPEN);const g=new Event("open");if((a=ke(this,to))==null||a.call(this,g),this.dispatchEvent(g),typeof i!="object"||!i||!("getReader"in i)){er(this,Mt,ro).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const h=new TextDecoder,d=i.getReader();let p=!0;do{const{done:w,value:m}=await d.read();m&&ke(this,pn).feed(h.decode(m,{stream:!w})),w&&(p=!1,ke(this,pn).reset(),er(this,Mt,Cl).call(this))}while(p)}),Fe(this,bl,s=>{je(this,gr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&er(this,Mt,Cl).call(this,vl(s))}),Fe(this,kl,s=>{typeof s.id=="string"&&je(this,eo,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:ke(this,un)?ke(this,un).origin:ke(this,Ur).origin,lastEventId:s.id||""});ke(this,hn)&&(!s.event||s.event==="message")&&ke(this,hn).call(this,a),this.dispatchEvent(a)}),Fe(this,Sl,s=>{je(this,Xn,s)}),Fe(this,Tl,()=>{je(this,dn,void 0),ke(this,ut)===this.CONNECTING&&er(this,Mt,yl).call(this)});try{if(t instanceof URL)je(this,Ur,t);else if(typeof t=="string")je(this,Ur,new URL(t,iS()));else throw new Error("Invalid URL")}catch{throw aS("An invalid or illegal string was specified")}je(this,pn,Fc({onEvent:ke(this,kl),onRetry:ke(this,Sl)})),je(this,ut,this.CONNECTING),je(this,Xn,3e3),je(this,Ws,(n=r?.fetch)!=null?n:globalThis.fetch),je(this,Gs,(o=r?.withCredentials)!=null?o:!1),er(this,Mt,yl).call(this)}get readyState(){return ke(this,ut)}get url(){return ke(this,Ur).href}get withCredentials(){return ke(this,Gs)}get onerror(){return ke(this,fn)}set onerror(t){je(this,fn,t)}get onmessage(){return ke(this,hn)}set onmessage(t){je(this,hn,t)}get onopen(){return ke(this,to)}set onopen(t){je(this,to,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(){ke(this,dn)&&clearTimeout(ke(this,dn)),ke(this,ut)!==this.CLOSED&&(ke(this,gr)&&ke(this,gr).abort(),je(this,ut,this.CLOSED),je(this,gr,void 0))}}ut=new WeakMap,Ur=new WeakMap,un=new WeakMap,Gs=new WeakMap,Ws=new WeakMap,Xn=new WeakMap,dn=new WeakMap,eo=new WeakMap,gr=new WeakMap,pn=new WeakMap,fn=new WeakMap,hn=new WeakMap,to=new WeakMap,Mt=new WeakSet,yl=function(){je(this,ut,this.CONNECTING),je(this,gr,new AbortController),ke(this,Ws)(ke(this,Ur),er(this,Mt,Rm).call(this)).then(ke(this,wl)).catch(ke(this,bl))},wl=new WeakMap,bl=new WeakMap,Rm=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...ke(this,eo)?{"Last-Event-ID":ke(this,eo)}:void 0},cache:"no-store",signal:(e=ke(this,gr))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},kl=new WeakMap,Sl=new WeakMap,ro=function(e,t){var r;ke(this,ut)!==this.CLOSED&&je(this,ut,this.CLOSED);const n=new Em("error",{code:t,message:e});(r=ke(this,fn))==null||r.call(this,n),this.dispatchEvent(n)},Cl=function(e,t){var r;if(ke(this,ut)===this.CLOSED)return;je(this,ut,this.CONNECTING);const n=new Em("error",{code:t,message:e});(r=ke(this,fn))==null||r.call(this,n),this.dispatchEvent(n),je(this,dn,setTimeout(ke(this,Tl),ke(this,Xn)))},Tl=new WeakMap,Ks.CONNECTING=0,Ks.OPEN=1,Ks.CLOSED=2;function iS(){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 lS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class $l{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=L0(r?.fetch,r?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new kt("No auth provider");let r;try{r=await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(t=this.onerror)===null||t===void 0||t.call(this,n),n}if(r!=="AUTHORIZED")throw new kt;return await this._startOrAuth()}async _commonHeaders(){var t;const r={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(r.Authorization=`Bearer ${o.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Uo((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...r,...n})}_startOrAuth(){var t,r,n;const o=(n=(r=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((s,a)=>{this._eventSource=new Ks(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await o(i,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:g,scope:h}=Wo(u);this._resourceMetadataUrl=g,this._scope=h}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,a);return}const c=new lS(i.code,i.message,i);a(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){a(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let g;try{g=Or.parse(JSON.parse(u.data))}catch(h){(l=this.onerror)===null||l===void 0||l.call(this,h);return}(c=this.onmessage)===null||c===void 0||c.call(this,g)}})}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 kt("No auth provider");if(await Nr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt("Failed to authorize")}async close(){var t,r,n;(t=this._abortController)===null||t===void 0||t.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t){var r,n,o,s;if(!this._endpoint)throw new Error("Not connected");try{const a=await this._commonHeaders();a.set("content-type","application/json");const i={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,i);if(!l.ok){const c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){const{resourceMetadataUrl:u,scope:g}=Wo(l);if(this._resourceMetadataUrl=u,this._scope=g,await Nr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kt;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((o=l.body)===null||o===void 0?void 0:o.cancel())}catch(a){throw(s=this.onerror)===null||s===void 0||s.call(this,a),a}}setProtocolVersion(t){this._protocolVersion=t}}const cS="mcp";class Pm{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,cS),this._socket.onerror=n=>{var o;const s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(s),(o=this.onerror)===null||o===void 0||o.call(this,s)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var o,s;let a;try{a=Or.parse(JSON.parse(n.data))}catch(i){(o=this.onerror)===null||o===void 0||o.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,a)}})}async close(){var t;(t=this._socket)===null||t===void 0||t.close()}send(t){return new Promise((r,n)=>{var o;if(!this._socket){n(new Error("Not connected"));return}(o=this._socket)===null||o===void 0||o.send(JSON.stringify(t)),r()})}}function Ys(){const e=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Ys=function(){return e},Ys()}(function(e,t){const r=Xe,n=Xe,o=e();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(n(429))/5)+parseInt(n(423))/6*(-parseInt(n(418))/7)+-parseInt(n(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Ys,650197);const uS=()=>{const e=Xe,t={EGhzU:function(r,n){return r!==n},kIrDB:"undefined",llYQe:function(r,n){return r!==n},PZfJg:function(r,n){return r(n)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:t[e(407)](typeof window,t.kIrDB)?window:t.llYQe(typeof global,t.kIrDB)?global:typeof self!==e(398)?self:t.PZfJg(Function,t[e(399)])()},dS=(e,t,r)=>{const n=Xe,o=Xe,s={};s[n(410)]=o(398),s.dBkaX=function(i,l){return i===l},s[o(393)]="function";const a=s;typeof window!==a[o(410)]?e.postMessage(t,"*",r):o(428)in e&&a.dBkaX(typeof e.postMessage,a[n(393)])&&e.postMessage(t,r)};class Om{constructor(t){const r=Xe;this[r(406)]=t}async start(){const t=Xe,r=Xe;this[t(406)]&&(this[t(406)][t(413)]=n=>{var o,s;const a=t,i=r;try{const l=Or[a(402)](n.data[a(400)]);(o=this[a(413)])==null||o.call(this,l,n[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,c)}},this._port[t(396)]=n=>{var o;const s=r,a=r,i=new Error(s(394)+JSON[a(395)](n));(o=this.onerror)==null||o.call(this,i)},this[t(406)][t(434)]())}async send(t,r){const n={lEyuq:function(o){return o()},YihNw:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=Xe,l=Xe;try{const c={};c[i(403)]=r?.[i(403)];const u={};u[l(400)]=t,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),n.lEyuq(o)}catch(c){const u=c instanceof Error?c:new Error(n.YihNw(String,c));(a=this[l(408)])==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=Xe,o=Xe;(t=this._port)==null||t[n(431)](),this._port=void 0,(r=this[o(420)])==null||r.call(this)}}class pS extends Om{constructor(t,r=uS()){const n=Xe,o=Xe,s={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[n(391)]=t,this[o(401)]=r;const a=new MessageChannel;this[o(406)]=a.port1,s[o(426)](dS,this[n(401)],{endpoint:this[o(391)]},[a[o(414)]])}}function Xe(e,t){const r=Ys();return Xe=function(n,o){return n=n-(17*-491+-669+9407),r[n]},Xe(e,t)}(function(e,t){const r=Me,n=Me,o=e();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(n(357))/5+-parseInt(n(389))/6*(-parseInt(r(396))/7)+parseInt(n(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Qs,-763475+-52067*10+1724410);const fS=async(e,t,r)=>{var n;const o=Me,s=Me,a={};a[o(345)]="tools/list",a.rqstG="tools/call",a.WqUnk="resources/list",a[o(329)]=s(358),a[o(365)]=o(335),a.ookoz="resources/unsubscribe",a[o(385)]=o(340),a.VTIWq="prompts/list",a.SkoRK=o(376),a.QUtUV=o(388),a.XtowM=s(332);const i=a,{id:l,method:c,params:u}=r;let g={};switch(c){case i[s(345)]:g=await t.listTools(u);break;case i.rqstG:g=await t.callTool(u);break;case i[o(334)]:g=await t[o(350)](u);break;case i[s(329)]:g=await t.listResourceTemplates(u);break;case o(372):g=await t[o(383)](u);break;case i.HgYgW:g=await t.subscribeResource(u);break;case i.ookoz:g=await t.unsubscribeResource(u);break;case i[o(385)]:g=await t.getPrompt(u);break;case i.VTIWq:g=await t.listPrompts(u);break;case i[o(344)]:g=await t[o(376)]();break;case i.QUtUV:g=await t.complete(u);break;case o(390):g=await t[o(336)](u?.level);break}const h={};h[o(361)]=g,h[o(394)]=i[o(364)],h.id=l,await((n=e?.transport)==null?void 0:n[o(392)](h))},hS=async(e,t,r)=>{var n;const o=Me,s=Me,a={};a.jQBBS="sampling/createMessage",a.EZqgC="elicitation/create",a[o(370)]=s(376),a.aVeaL=s(332);const i=a,{id:l,method:c,params:u}=r;let g={};switch(c){case o(368):const d={};d.method=c,d[s(367)]=u,g=await t.request(d,ff);break;case i[s(391)]:const p={};p.method=c,p[s(367)]=u,g=await t[s(381)](p,$i);break;case i.EZqgC:const w={};w.method=c,w.params=u,g=await t.request(w,Ii);break;case i[s(370)]:const m={};m.method=c,g=await t[s(381)](m,Mr);break}const h={};return h[s(361)]=g,h.jsonrpc=i[s(387)],h.id=l,await((n=e?.[o(371)])==null?void 0:n.send(h)),g},mS=(e,t)=>{const r=Me,n={gXsjT:function(s,a){return s===a},oegpC:r(351),lZOUC:function(s,a,i,l){return s(a,i,l)},ifIKG:"2.0"},o=e._onrequest;e._onrequest=async(s,a)=>{var i,l,c,u,g;const h=r,d=r,{id:p,method:w}=s;try{n[h(333)](w,n.oegpC)?await o[h(386)](e,s,a):await n.lZOUC(fS,e,t,s)}catch(m){const{code:y,message:_,data:f}=m;try{if(y){const b={};b.code=y,b.message=_,b.data=f;const k={};k.error=b,k[h(394)]=n[d(331)],k.id=p,await((i=e?.transport)==null?void 0:i.send(k))}else(c=(l=e?.[d(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(b){(g=(u=e?.[h(371)])==null?void 0:u.onerror)==null||g.call(u,b)}}}},gS=(e,t)=>{const r=Me,n=Me,o={};o[r(363)]=function(a,i){return a!==i},o[r(398)]=r(353),o.hzhyg="notifications/cancelled";const s=o;e._onnotification=async a=>{var i,l;const c=r,u=n,{method:g,params:h}=a;if(s[c(363)](g,s[u(398)])&&(s[c(363)](g,s.hzhyg)||h?.forward))try{await t.notification(a)}catch(d){(l=(i=e?.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},vS=(e,t)=>async r=>{var n,o,s,a,i;const l=Me,c=Me,u={};u.SEmWX=l(332);const g=u;try{return await hS(e,t,r)}catch(h){const{code:d,message:p,data:w}=h;try{if(d){const m={};m[c(377)]=d,m.message=p,m.data=w;const y={};y[c(348)]=m,y.jsonrpc=g[l(338)],y.id=r.id,await((n=e?.transport)==null?void 0:n[c(392)](y))}else(s=(o=e?.transport)==null?void 0:o[c(339)])==null||s.call(o,h)}catch(m){(i=(a=e?.[l(371)])==null?void 0:a[c(339)])==null||i.call(a,m)}}},_S=(e,t)=>async r=>{var n,o,s;const a=Me,i=Me,l={};l.dtUgZ=function(h,d){return h!==d},l.jgCIb=a(353),l.uUjKY="2.0";const c=l,{method:u,params:g}=r;if(c.dtUgZ(u,c.jgCIb)&&(u!==a(400)||g?.forward))try{const h={...r};h[a(394)]=c[i(352)],await((n=t?.[a(371)])==null?void 0:n[a(392)](h))}catch(h){(s=(o=e?.[a(371)])==null?void 0:o[i(339)])==null||s.call(o,h)}};function Me(e,t){const r=Qs();return Me=function(n,o){return n=n-(-1017+-1439*-1+-97),r[n]},Me(e,t)}const yS=(e,t)=>async r=>{var n,o,s,a,i,l;const c=Me,u=Me,g={};g[c(401)]=u(332);const h=g;try{await((n=t?.transport)==null?void 0:n.send(r))}catch(d){const{code:p,message:w,data:m}=d;try{if(p){const y={};y.code=p,y[c(399)]=w,y.data=m;const _={};_[c(348)]=y,_[c(394)]=h.OhJjz,_.id=r.id,await((o=e?.[c(371)])==null?void 0:o.send(_))}else(a=(s=e?.transport)==null?void 0:s[u(339)])==null||a.call(s,d)}catch(y){(l=(i=e?.transport)==null?void 0:i.onerror)==null||l.call(i,y)}}},El=()=>{const e=Me,t=Me,r={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},n=[],o=(c,u)=>{const g=Me,h=Me;if(u){const d=[];for(const p of n)try{d.push(p(c,u))}catch{}for(const p of d)if(r[g(379)](p,null))return p}else for(const d of n)try{r[h(343)](d,c)}catch{}},s=c=>{const u=Me;r[u(384)](typeof c,u(369))&&!n.includes(c)&&n.push(c)},a=c=>{const u=n.indexOf(c);u!==-1&&n.splice(u,1*-6854+-264+7119)},i=()=>{const c=Me;n[c(374)]=7102*1+5522+-526*24},l={};return l[e(346)]=o,l[t(330)]=s,l.removeListener=a,l[e(359)]=i,l},wS=e=>{const t=Me,r=Me,n={xwPeb:function(o){return o()},Mfvzm:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(326)](El);e._onresponse=o,e[t(395)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[r(326)](El);e[r(328)]=o,e.addRequestListener=s,e[r(354)]=a,e[r(341)]=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(375)](El);e[t(342)]=o,e[t(327)]=s,e.removeNotificationListener=a,e.clearNotificationListener=i}};function Qs(){const e=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return Qs=function(){return e},Qs()}const bS=(e,{beforeInit:t,afterInit:r}={})=>{const n=Me,o=Me,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:n(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(393)][n(402)](),e._notificationHandlers[n(402)](),s.tqDZP(typeof t,s[n(380)])&&t(),s[n(362)](e._onresponse.name,s[n(360)])&&(e[o(349)]=e._onresponse),s[n(347)](wS,e),e.addResponseListener(i=>{const l=o;e.originalOnResponse[l(386)](e,i)}),s.tqDZP(typeof r,s[o(380)])&&s[n(397)](r),e[o(327)](i=>{const{method:l}=i,c=a.get(l);s.tqDZP(typeof c,s.cjSoZ)&&c(i)})},kS=Ft,SS=Ft;(function(e,t){const r=Ft,n=Ft,o=e();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(n(398))/4+parseInt(r(390))/5*(parseInt(n(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(n(395))/9)+parseInt(n(399))/10*(parseInt(n(385))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Xs,-1*-881393+2*180895+1*-644809);function Ft(e,t){const r=Xs();return Ft=function(n,o){return n=n-(-1861+-499*4+4241),r[n]},Ft(e,t)}function Xs(){const e=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return Xs=function(){return e},Xs()}const CS=()=>{const e=Ft,t=Ft,r={};r.REzPF=function(o,s){return o&s},r.suJHI=function(o,s){return o===s},r[e(386)]=function(o,s){return o&s},r[t(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[t(391)]():n.dHTfU.replace(/[xy]/g,o=>{const s=e,a=e,i=n[s(392)](crypto[s(384)](new Uint8Array(8663+2*-4331))[741*2+-1385*-2+4252*-1],15);return(n.suJHI(o,"x")?i:n[a(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},TS=e=>{const t=Ft,r=Ft,n=new Uint8Array(e);return crypto.getRandomValues(n),Array[t(401)](n,o=>o[r(403)](-3*1739+-6509+2*5871)[t(387)](2,"0")).join("")},vr={};vr[kS(391)]=CS,vr[SS(396)]=TS;const yt=Vt;(function(e,t){const r=Vt,n=Vt,o=e();for(;;)try{if(parseInt(r(521))/1*(parseInt(n(499))/2)+parseInt(n(543))/3*(parseInt(n(514))/4)+parseInt(r(502))/5*(parseInt(n(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ea,1472653*1+-2*-897917+-2275789);const $S=(e,t)=>{const r=Vt,n=Vt,o={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};mS(e,t),gS(e,t);const s=vS(t,e),a=o[r(510)](yS,t,e),i=o[n(549)](_S,t,e);t[n(537)](s),t[r(519)](a),t.addNotificationListener(i),e[n(556)]=()=>{const l=n;t.removeRequestListener(s),t[l(530)](a),t[l(529)](i)}},Il=(e,t,r)=>{const n=Vt,o={pMiva:function(i,l){return i instanceof l},TeTEy:n(546),fyZbd:function(i,l,c){return i(l,c)}},s=()=>{var i;const l=n;o.pMiva(r,$l)&&((i=r._eventSource)==null||i.addEventListener(o[l(547)],()=>{var c;const u=l;(c=r[u(509)])==null||c[u(546)]()})),$S(e,t)},a={};a.afterInit=s,o.fyZbd(bS,t,a)},Mm=(e,t=vr.randomUUID())=>{const r=Vt,n=Vt,o={OfssH:function(u,g,h){return u(g,h)}},s={};s[r(528)]=t;const a=s,i={};i[r(528)]=t;const l={};l[n(558)]=i,l[r(534)]=r(524);const c={requestInit:l,eventSourceInit:{async fetch(u,g){const h=r,d=n,p=new Headers(g?.[h(558)]||{});Object.entries(a)[d(498)](([m,y])=>{p[d(527)](m,y)});const w={...g};return w[d(558)]=p,o.OfssH(fetch,u,w)},withCredentials:!0}};return e&&(c.requestInit[r(558)].Authorization=r(533)+e,a.Authorization="Bearer "+e),c},Nm=(e,t=vr[yt(517)]())=>{const r=yt,n=yt,o={};o.nwQhY="include";const s=o,a={};a["stream-session-id"]=t;const i={};i.headers=a,i.credentials=s[r(520)];const l={};l[r(544)]=i;const c=l;return e&&(c.requestInit.headers[n(552)]=n(533)+e),c},xl=async(e,t,r)=>{const n=yt,o=yt,s={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},a=s.CFfFC(r);try{return await e[n(538)](a),a}catch(i){if(i instanceof kt){const l=await t();return await a[o(505)](l),await s[n(525)](xl,e,t,r)}else throw i}};function Vt(e,t){const r=ea();return Vt=function(n,o){return n=n-498,r[n]},Vt(e,t)}const Am=(e,t)=>{const r=yt,n=yt,o={};o.RsKXs=function(a,i){return a in i},o.PBhps="waitForOAuthCode",o[r(535)]="function",o[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=o;if(s.RsKXs(s[n(551)],e))return e[n(523)];if(typeof t===s.yTKoP)return t;throw new Error(s.RZhOv)},ES=async e=>{const t=yt,r=yt,n={TFSRn:function(x,M,P){return x(M,P)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(x){return x()},WIVYl:function(x,M,P,U){return x(M,P,U)},jniGY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:g}=e,h={};h.authProvider=l,h.requestInit=c,h.eventSourceInit=u;const d=h,p=i||vr.randomUUID(),w=n[t(506)](Mm,a,p);if(c){const x={...w.requestInit,...c};x.headers={...w[t(544)].headers,...c.headers},d.requestInit=x}else d[r(544)]=w.requestInit;if(u){const x={...w[t(559)],...u};d.eventSourceInit=x}else d.eventSourceInit=w.eventSourceInit;const m={};m.listChanged=!0;const y={};y.roots=m,y.sampling={},y[t(511)]={};const _=y,f={};f[r(536)]=n.HwvVa,f.version=t(526);const b={};b.capabilities=_;const k=new Js(f,b),S=()=>new $l(new URL(s),d);let C=n[r(504)](S);if(l){const x=n[t(506)](Am,l,g);C=await n[r(513)](xl,k,x,S)}else await k[t(538)](C);n[r(513)](Il,k,o,C),C[r(557)]=C[r(542)].searchParams[r(532)](n.jniGY);const I={};return I.transport=C,I.sessionId=C[t(557)],I};function ea(){const e=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return ea=function(){return e},ea()}const IS=async e=>{const t=yt,r=yt,n={Vajmx:t(500),biJOc:function(x){return x()},zXcpO:function(x,M,P){return x(M,P)},zDnjZ:function(x,M,P,U){return x(M,P,U)},FQMAh:function(x,M,P,U){return x(M,P,U)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:g}=e,h={};h.authProvider=l,h.requestInit=c,h.reconnectionOptions=u;const d=h,p=i||vr.randomUUID(),w=Nm(a,p);if(c){const x={...w.requestInit,...c};x.headers={...w.requestInit.headers,...c.headers},d[t(544)]=x}else d.requestInit=w.requestInit;const m={};m.listChanged=!0;const y={};y[r(550)]=m,y.sampling={},y.elicitation={};const _=y,f={};f[t(536)]=n[r(508)],f[t(555)]="1.0.0";const b={};b.capabilities=_;const k=new Js(f,b),S=()=>new Ko(new URL(s),d);let C=n[t(503)](S);if(l){const x=n[t(501)](Am,l,g);C=await n.zDnjZ(xl,k,x,S)}else await k.connect(C);n.FQMAh(Il,k,o,C);const I={};return I.transport=C,I[r(557)]=C.sessionId,I},xS=async e=>{const t=yt,r=yt,n={QgzDy:t(540),jkaVB:function(y,_,f,b){return y(_,f,b)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l.listChanged=!0;const c={};c[t(550)]=l,c[t(515)]={},c[r(511)]={};const u=c,g={};g.name=n[r(548)],g[r(555)]=r(526);const h={};h.capabilities=u;const d=new Js(g,h),p=i||vr[r(517)](),w=new Pm(new URL(s+t(522)+p+r(554)+a));await d.connect(w),n.jkaVB(Il,d,o,w);const m={};return m[t(512)]=w,m[r(557)]=p,m},no=dt,ta=dt;function dt(e,t){const r=ra();return dt=function(n,o){return n=n-(-16761+51*337),r[n]},dt(e,t)}(function(e,t){const r=dt,n=dt,o=e();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(n(449))/5)+-parseInt(n(455))/6+-parseInt(r(427))/7+-parseInt(n(438))/8*(parseInt(n(459))/9)+parseInt(r(430))/10*(parseInt(n(436))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(ra,-220880+1*-333337+-2*-384996);function ra(){const e=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return ra=function(){return e},ra()}const RS=()=>vr.randomBytes(3485*1+-261+-3184);class PC{constructor(t){const r=dt,n=dt;this._callBackPromise={};const{clientMetadata:o,state:s,redirectCallback:a,getAuthCodeByState:i,waitForOAuthCode:l}=t;this[r(428)]=o,this[r(454)]=o[r(445)][0],this._state=s||RS(),this._redirectCallback=a||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[n(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=dt,c=dt,u={qITTp:function(p,w,m){return p(w,m)},qcFPW:l(452)},g=await u.qITTp(fetch,t,{method:u[l(453)]});!g.ok&&((n=(r=this._callBackPromise).reject)==null||n.call(r,c(446)+g.statusText));const h=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!h.ok){(s=(o=this[l(433)]).reject)==null||s.call(o,"Failed to fetch auth code: "+h.statusText);return}const d=await h[l(431)]();(i=(a=this[c(433)])[l(456)])==null||i.call(a,d[l(432)])}async getAuthCodeByStateFunction(t,r){const n=dt,o=dt,s={};s.tuSmb=n(429);const a=s,i={};i[n(460)]=a.tuSmb;const l={};return l[o(441)]=r,fetch(t,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const t=dt,r=this[t(433)];return()=>new Promise((n,o)=>{const s=t;r.resolve=n,r[s(434)]=o})}get redirectUrl(){return this[dt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[no(447)](){return this[no(444)]}[ta(435)](t){const r=no;this[r(444)]=t}[ta(457)](){return this[ta(439)]}saveTokens(t){this._tokens=t}[ta(450)](t){this[no(443)](t)}saveCodeVerifier(t){this._codeVerifier=t}codeVerifier(){if(!this[no(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(e,t){for(var r=oa,n=oa,o=e();;)try{var s=parseInt(r(361))/1*(parseInt(n(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(n(354))/6*(parseInt(r(360))/7)+parseInt(n(362))/8+parseInt(n(364))/9+-parseInt(n(356))/10*(parseInt(r(355))/11);if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(na,-73523*-3+1*-407717+530518);function na(){var e=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return na=function(){return e},na()}function oa(e,t){var r=na();return oa=function(n,o){n=n-(-1*-642+503*-5+2227);var s=r[n];return s},oa(e,t)}class PS{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Js(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:d,sessionId:p}=s==="sse"?await ES(u):s==="socket"?await xS(u):await IS(u);d.onerror=async w=>{i?.(w)},g={transport:d,sessionId:p}})(),g}const l=new URL(r);let c;if(s==="channel"&&(c=new pS(r),await this.client.connect(c)),s==="sse"){const u=Mm(n,o);c=new $l(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Pm(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=Nm(n,o);c=new Ko(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,Jn,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(Ei,t)}onCreateMessage(t){this.client.setRequestHandler(Ti,t)}onListRoots(t){this.client.setRequestHandler(pf,t)}onToolListChanged(t){this.client.setNotificationHandler(lf,t)}onPromptListChanged(t){this.client.setNotificationHandler(of,t)}onResourceListChanged(t){this.client.setNotificationHandler(ef,t)}onResourceUpdated(t){this.client.setNotificationHandler(tf,t)}onLoggingMessage(t){this.client.setNotificationHandler(uf,t)}async onPagehide(t){t.persisted||(OS(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const OS=e=>e instanceof Ko,qm=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]=td({description:o,inputSchema:Rn({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function MS(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
80
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);i(l,c),a(l,u)}};function s({schema:l}){const c={},u={};for(const m in l){if(m==="__proto__")continue;const f=Array.isArray(l[m])?c:u;f[m]=l[m]}return[c,u]}function i(l,c=l.schema){const{gen:u,data:m,it:f}=l;if(Object.keys(c).length===0)return;const p=u.let("missing");for(const h in c){const v=c[h];if(v.length===0)continue;const _=(0,n.propertyInData)(u,m,h,f.opts.ownProperties);l.setParams({property:h,depsCount:v.length,deps:v.join(", ")}),f.allErrors?u.if(_,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${_} && (${(0,n.checkMissingProp)(l,v,p)})`),(0,n.reportMissingProp)(l,p),u.else())}}e.validatePropertyDeps=i;function a(l,c=l.schema){const{gen:u,data:m,keyword:f,it:p}=l,h=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(p,c[v])||(u.if((0,n.propertyInData)(u,m,v,p.opts.ownProperties),()=>{const _=l.subschema({keyword:f,schemaProp:v},h);l.mergeValidEvaluated(_,h)},()=>u.var(h,!0)),l.ok(h))}e.validateSchemaDeps=a,e.default=o})(_c)),_c}var da={},zg;function iT(){if(zg)return da;zg=1,Object.defineProperty(da,"__esModule",{value:!0});const e=we(),t=ke(),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:i,data:a,it:l}=o;if((0,t.alwaysValidSchema)(l,i))return;const c=s.name("valid");s.forIn("key",a,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 da.default=n,da}var pa={},Zg;function Fg(){if(Zg)return pa;Zg=1,Object.defineProperty(pa,"__esModule",{value:!0});const e=zt(),t=we(),r=$r(),n=ke(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:i})=>(0,t._)`{additionalProperty: ${i.additionalProperty}}`},code(i){const{gen:a,schema:l,parentSchema:c,data:u,errsCount:m,it:f}=i;if(!m)throw new Error("ajv implementation error");const{allErrors:p,opts:h}=f;if(f.props=!0,h.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(f,l))return;const v=(0,e.allSchemaProperties)(c.properties),_=(0,e.allSchemaProperties)(c.patternProperties);w(),i.ok((0,t._)`${m} === ${r.default.errors}`);function w(){a.forIn("key",u,$=>{!v.length&&!_.length?b($):a.if(g($),()=>b($))})}function g($){let k;if(v.length>8){const I=(0,n.schemaRefOrVal)(f,c.properties,"properties");k=(0,e.isOwnProperty)(a,I,$)}else v.length?k=(0,t.or)(...v.map(I=>(0,t._)`${$} === ${I}`)):k=t.nil;return _.length&&(k=(0,t.or)(k,..._.map(I=>(0,t._)`${(0,e.usePattern)(i,I)}.test(${$})`))),(0,t.not)(k)}function y($){a.code((0,t._)`delete ${u}[${$}]`)}function b($){if(h.removeAdditional==="all"||h.removeAdditional&&l===!1){y($);return}if(l===!1){i.setParams({additionalProperty:$}),i.error(),p||a.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(f,l)){const k=a.name("valid");h.removeAdditional==="failing"?(S($,k,!1),a.if((0,t.not)(k),()=>{i.reset(),y($)})):(S($,k),p||a.if((0,t.not)(k),()=>a.break()))}}function S($,k,I){const P={keyword:"additionalProperties",dataProp:$,dataPropType:n.Type.Str};I===!1&&Object.assign(P,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(P,k)}}};return pa.default=s,pa}var ha={},Vg;function lT(){if(Vg)return ha;Vg=1,Object.defineProperty(ha,"__esModule",{value:!0});const e=Ds(),t=zt(),r=ke(),n=Fg(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,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)(a);for(const _ of m)u.definedProperties.add(_);u.opts.unevaluated&&m.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(i,(0,r.toHash)(m),u.props));const f=m.filter(_=>!(0,r.alwaysValidSchema)(u,a[_]));if(f.length===0)return;const p=i.name("valid");for(const _ of f)h(_)?v(_):(i.if((0,t.propertyInData)(i,c,_,u.opts.ownProperties)),v(_),u.allErrors||i.else().var(p,!0),i.endIf()),s.it.definedProperties.add(_),s.ok(p);function h(_){return u.opts.useDefaults&&!u.compositeRule&&a[_].default!==void 0}function v(_){s.subschema({keyword:"properties",schemaProp:_,dataProp:_},p)}}};return ha.default=o,ha}var fa={},Hg;function cT(){if(Hg)return fa;Hg=1,Object.defineProperty(fa,"__esModule",{value:!0});const e=zt(),t=we(),r=ke(),n=ke(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,data:l,parentSchema:c,it:u}=s,{opts:m}=u,f=(0,e.allSchemaProperties)(a),p=f.filter(b=>(0,r.alwaysValidSchema)(u,a[b]));if(f.length===0||p.length===f.length&&(!u.opts.unevaluated||u.props===!0))return;const h=m.strictSchema&&!m.allowMatchingProperties&&c.properties,v=i.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(i,u.props));const{props:_}=u;w();function w(){for(const b of f)h&&g(b),u.allErrors?y(b):(i.var(v,!0),y(b),i.if(v))}function g(b){for(const S in h)new RegExp(b).test(S)&&(0,r.checkStrictMode)(u,`property ${S} matches pattern ${b} (use allowMatchingProperties)`)}function y(b){i.forIn("key",l,S=>{i.if((0,t._)`${(0,e.usePattern)(s,b)}.test(${S})`,()=>{const $=p.includes(b);$||s.subschema({keyword:"patternProperties",schemaProp:b,dataProp:S,dataPropType:n.Type.Str},v),u.opts.unevaluated&&_!==!0?i.assign((0,t._)`${_}[${S}]`,!0):!$&&!u.allErrors&&i.if((0,t.not)(v),()=>i.break())})})}}};return fa.default=o,fa}var ma={},Bg;function uT(){if(Bg)return ma;Bg=1,Object.defineProperty(ma,"__esModule",{value:!0});const e=ke(),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 i=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return ma.default=t,ma}var ga={},Jg;function dT(){if(Jg)return ga;Jg=1,Object.defineProperty(ga,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:zt().validateUnion,error:{message:"must match a schema in anyOf"}};return ga.default=t,ga}var _a={},Wg;function pT(){if(Wg)return _a;Wg=1,Object.defineProperty(_a,"__esModule",{value:!0});const e=we(),t=ke(),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:i,parentSchema:a,it:l}=o;if(!Array.isArray(i))throw new Error("ajv implementation error");if(l.opts.discriminator&&a.discriminator)return;const c=i,u=s.let("valid",!1),m=s.let("passing",null),f=s.name("_valid");o.setParams({passing:m}),s.block(p),o.result(u,()=>o.reset(),()=>o.error(!0));function p(){c.forEach((h,v)=>{let _;(0,t.alwaysValidSchema)(l,h)?s.var(f,!0):_=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},f),v>0&&s.if((0,e._)`${f} && ${u}`).assign(u,!1).assign(m,(0,e._)`[${m}, ${v}]`).else(),s.if(f,()=>{s.assign(u,!0),s.assign(m,v),_&&o.mergeEvaluated(_,e.Name)})})}}};return _a.default=n,_a}var va={},Gg;function hT(){if(Gg)return va;Gg=1,Object.defineProperty(va,"__esModule",{value:!0});const e=ke(),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 i=n.name("valid");o.forEach((a,l)=>{if((0,e.alwaysValidSchema)(s,a))return;const c=r.subschema({keyword:"allOf",schemaProp:l},i);r.ok(i),r.mergeEvaluated(c)})}};return va.default=t,va}var ya={},Kg;function fT(){if(Kg)return ya;Kg=1,Object.defineProperty(ya,"__esModule",{value:!0});const e=we(),t=ke(),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:i,parentSchema:a,it:l}=s;a.then===void 0&&a.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=i.let("valid",!0),f=i.name("_valid");if(p(),s.reset(),c&&u){const v=i.let("ifClause");s.setParams({ifClause:v}),i.if(f,h("then",v),h("else",v))}else c?i.if(f,h("then")):i.if((0,e.not)(f),h("else"));s.pass(m,()=>s.error(!0));function p(){const v=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);s.mergeEvaluated(v)}function h(v,_){return()=>{const w=s.subschema({keyword:v},f);i.assign(m,f),s.mergeValidEvaluated(w,m),_?i.assign(_,(0,e._)`${v}`):s.setParams({ifClause:v})}}}};function o(s,i){const a=s.schema[i];return a!==void 0&&!(0,t.alwaysValidSchema)(s,a)}return ya.default=n,ya}var wa={},Yg;function mT(){if(Yg)return wa;Yg=1,Object.defineProperty(wa,"__esModule",{value:!0});const e=ke(),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 wa.default=t,wa}var Qg;function gT(){if(Qg)return ia;Qg=1,Object.defineProperty(ia,"__esModule",{value:!0});const e=Ag(),t=nT(),r=qg(),n=oT(),o=sT(),s=aT(),i=iT(),a=Fg(),l=lT(),c=cT(),u=uT(),m=dT(),f=pT(),p=hT(),h=fT(),v=mT();function _(w=!1){const g=[u.default,m.default,f.default,p.default,h.default,v.default,i.default,a.default,s.default,l.default,c.default];return w?g.push(t.default,n.default):g.push(e.default,r.default),g.push(o.default),g}return ia.default=_,ia}var ba={},Sa={},Xg;function _T(){if(Xg)return Sa;Xg=1,Object.defineProperty(Sa,"__esModule",{value:!0});const e=we(),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:i,$data:a,schema:l,schemaCode:c,it:u}=n,{opts:m,errSchemaPath:f,schemaEnv:p,self:h}=u;if(!m.validateFormats)return;a?v():_();function v(){const w=s.scopeValue("formats",{ref:h.formats,code:m.code.formats}),g=s.const("fDef",(0,e._)`${w}[${c}]`),y=s.let("fType"),b=s.let("format");s.if((0,e._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>s.assign(y,(0,e._)`${g}.type || "string"`).assign(b,(0,e._)`${g}.validate`),()=>s.assign(y,(0,e._)`"string"`).assign(b,g)),n.fail$data((0,e.or)(S(),$()));function S(){return m.strictSchema===!1?e.nil:(0,e._)`${c} && !${b}`}function $(){const k=p.$async?(0,e._)`(${g}.async ? await ${b}(${i}) : ${b}(${i}))`:(0,e._)`${b}(${i})`,I=(0,e._)`(typeof ${b} == "function" ? ${k} : ${b}.test(${i}))`;return(0,e._)`${b} && ${b} !== true && ${y} === ${o} && !${I}`}}function _(){const w=h.formats[l];if(!w){S();return}if(w===!0)return;const[g,y,b]=$(w);g===o&&n.pass(k());function S(){if(m.strictSchema===!1){h.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${f}"`}}function $(I){const P=I instanceof RegExp?(0,e.regexpCode)(I):m.code.formats?(0,e._)`${m.code.formats}${(0,e.getProperty)(l)}`:void 0,L=s.scopeValue("formats",{key:l,ref:I,code:P});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${L}.validate`]:["string",I,L]}function k(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!p.$async)throw new Error("async format in sync schema");return(0,e._)`await ${b}(${i})`}return typeof y=="function"?(0,e._)`${b}(${i})`:(0,e._)`${b}.test(${i})`}}}};return Sa.default=r,Sa}var e1;function vT(){if(e1)return ba;e1=1,Object.defineProperty(ba,"__esModule",{value:!0});const t=[_T().default];return ba.default=t,ba}var Jr={},t1;function yT(){return t1||(t1=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.contentVocabulary=Jr.metadataVocabulary=void 0,Jr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Jr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Jr}var r1;function wT(){if(r1)return Hs;r1=1,Object.defineProperty(Hs,"__esModule",{value:!0});const e=VE(),t=rT(),r=gT(),n=vT(),o=yT(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Hs.default=s,Hs}var $a={},bo={},n1;function bT(){if(n1)return bo;n1=1,Object.defineProperty(bo,"__esModule",{value:!0}),bo.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(bo.DiscrError=e={})),bo}var o1;function ST(){if(o1)return $a;o1=1,Object.defineProperty($a,"__esModule",{value:!0});const e=we(),t=bT(),r=hc(),n=Fs(),o=ke(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:a,tagName:l}})=>a===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:a,tag:l,tagName:c}})=>(0,e._)`{error: ${a}, tag: ${c}, tagValue: ${l}}`},code(a){const{gen:l,data:c,schema:u,parentSchema:m,it:f}=a,{oneOf:p}=m;if(!f.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=u.propertyName;if(typeof h!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!p)throw new Error("discriminator: requires oneOf keyword");const v=l.let("valid",!1),_=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(h)}`);l.if((0,e._)`typeof ${_} == "string"`,()=>w(),()=>a.error(!1,{discrError:t.DiscrError.Tag,tag:_,tagName:h})),a.ok(v);function w(){const b=y();l.if(!1);for(const S in b)l.elseIf((0,e._)`${_} === ${S}`),l.assign(v,g(b[S]));l.else(),a.error(!1,{discrError:t.DiscrError.Mapping,tag:_,tagName:h}),l.endIf()}function g(b){const S=l.name("valid"),$=a.subschema({keyword:"oneOf",schemaProp:b},S);return a.mergeEvaluated($,e.Name),S}function y(){var b;const S={},$=I(m);let k=!0;for(let N=0;N<p.length;N++){let j=p[N];if(j?.$ref&&!(0,o.schemaHasRulesButRef)(j,f.self.RULES)){const F=j.$ref;if(j=r.resolveRef.call(f.self,f.schemaEnv.root,f.baseId,F),j instanceof r.SchemaEnv&&(j=j.schema),j===void 0)throw new n.default(f.opts.uriResolver,f.baseId,F)}const D=(b=j?.properties)===null||b===void 0?void 0:b[h];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);k=k&&($||I(j)),P(D,N)}if(!k)throw new Error(`discriminator: "${h}" must be required`);return S;function I({required:N}){return Array.isArray(N)&&N.includes(h)}function P(N,j){if(N.const)L(N.const,j);else if(N.enum)for(const D of N.enum)L(D,j);else throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`)}function L(N,j){if(typeof N!="string"||N in S)throw new Error(`discriminator: "${h}" values must be unique strings`);S[N]=j}}}};return $a.default=i,$a}const $T={$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 s1;function a1(){return s1||(s1=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=zE(),n=wT(),o=ST(),s=$T,i=["/properties"],a="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(h=>this.addVocabulary(h)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const h=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(h,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=Ds();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=we();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=pc();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return m.default}});var f=Fs();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})(As,As.exports)),As.exports}var i1=a1();const CT=Si(i1);var Ca={exports:{}},vc={},l1;function kT(){return l1||(l1=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(N,j){return{validate:N,compare:j}}e.fullFormats={date:t(s,i),time:t(l(!0),c),"date-time":t(f(!0),p),"iso-time":t(l(),u),"iso-date-time":t(f(),h),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:y,int32:{type:"number",validate:$},int64:{type:"number",validate:k},float:{type:"number",validate:I},double:{type:"number",validate:I},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,i),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,p),"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,h),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(N){return N%4===0&&(N%100!==0||N%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(N){const j=n.exec(N);if(!j)return!1;const D=+j[1],F=+j[2],ne=+j[3];return F>=1&&F<=12&&ne>=1&&ne<=(F===2&&r(D)?29:o[F])}function i(N,j){if(N&&j)return N>j?1:N<j?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(N){return function(D){const F=a.exec(D);if(!F)return!1;const ne=+F[1],ue=+F[2],ie=+F[3],re=F[4],he=F[5]==="-"?-1:1,V=+(F[6]||0),M=+(F[7]||0);if(V>23||M>59||N&&!re)return!1;if(ne<=23&&ue<=59&&ie<60)return!0;const Z=ue-M*he,U=ne-V*he-(Z<0?1:0);return(U===23||U===-1)&&(Z===59||Z===-1)&&ie<61}}function c(N,j){if(!(N&&j))return;const D=new Date("2020-01-01T"+N).valueOf(),F=new Date("2020-01-01T"+j).valueOf();if(D&&F)return D-F}function u(N,j){if(!(N&&j))return;const D=a.exec(N),F=a.exec(j);if(D&&F)return N=D[1]+D[2]+D[3],j=F[1]+F[2]+F[3],N>j?1:N<j?-1:0}const m=/t|\s/i;function f(N){const j=l(N);return function(F){const ne=F.split(m);return ne.length===2&&s(ne[0])&&j(ne[1])}}function p(N,j){if(!(N&&j))return;const D=new Date(N).valueOf(),F=new Date(j).valueOf();if(D&&F)return D-F}function h(N,j){if(!(N&&j))return;const[D,F]=N.split(m),[ne,ue]=j.split(m),ie=i(D,ne);if(ie!==void 0)return ie||c(F,ue)}const v=/\/|:/,_=/^(?:[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(N){return v.test(N)&&_.test(N)}const g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(N){return g.lastIndex=0,g.test(N)}const b=-2147483648,S=2**31-1;function $(N){return Number.isInteger(N)&&N<=S&&N>=b}function k(N){return Number.isInteger(N)}function I(){return!0}const P=/[^\\]\\Z/;function L(N){if(P.test(N))return!1;try{return new RegExp(N),!0}catch{return!1}}})(vc)),vc}var yc={},c1;function ET(){return c1||(c1=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=a1(),r=we(),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:a,schemaCode:l})=>(0,r.str)`should be ${o[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>(0,r._)`{comparison: ${o[a].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(a){const{gen:l,data:c,schemaCode:u,keyword:m,it:f}=a,{opts:p,self:h}=f;if(!p.validateFormats)return;const v=new t.KeywordCxt(f,h.RULES.all.format.definition,"format");v.$data?_():w();function _(){const y=l.scopeValue("formats",{ref:h.formats,code:p.code.formats}),b=l.const("fmt",(0,r._)`${y}[${v.schemaCode}]`);a.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,g(b)))}function w(){const y=v.schema,b=h.formats[y];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${m}": format "${y}" does not define "compare" function`);const S=l.scopeValue("formats",{key:y,ref:b,code:p.code.formats?(0,r._)`${p.code.formats}${(0,r.getProperty)(y)}`:void 0});a.fail$data(g(S))}function g(y){return(0,r._)`${y}.compare(${c}, ${u}) ${o[m].fail} 0`}},dependencies:["format"]};const i=a=>(a.addKeyword(e.formatLimitDefinition),a);e.default=i})(yc)),yc}var u1;function TT(){return u1||(u1=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=kT(),n=ET(),o=we(),s=new o.Name("fullFormats"),i=new o.Name("fastFormats"),a=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[m,f]=u.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,s],p=u.formats||r.formatNames;return l(c,p,m,f),u.keywords&&(0,n.default)(c),c};a.get=(c,u="full")=>{const f=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!f)throw new Error(`Unknown format "${c}"`);return f};function l(c,u,m,f){var p,h;(p=(h=c.opts.code).formats)!==null&&p!==void 0||(h.formats=(0,o._)`require("ajv-formats/dist/formats").${f}`);for(const v of u)c.addFormat(v,m[v])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a})(Ca,Ca.exports)),Ca.exports}var IT=TT();const d1=Si(IT);function RT(){const e=new CT({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return d1(e),e}let xT=class{constructor(t){this._ajv=t??RT()}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 PT{constructor(t){this._client=t}async*callToolStream(t,r=Ps,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,s),a=o.getToolOutputValidator(t.name);for await(const l of i){if(l.type==="result"&&a){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new pe(ye.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=a(c.structuredContent);if(!u.valid){yield{type:"error",error:new pe(ye.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof pe){yield{type:"error",error:u};return}yield{type:"error",error:new pe(ye.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 OT(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 MT(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 ka(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&&ka(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&ka(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&ka(r,t)}}function AT(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}}let wc=class extends xE{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 xT,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",x2,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",T2,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",C2,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new PT(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=PE(this._capabilities,t)}setRequestHandler(t,r){const o=q2(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ms(o)){const a=o;s=a._zod?.def?.value??a.value}else{const a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const i=s;if(i==="elicitation/create"){const a=async(l,c)=>{const u=Sr(M2,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new pe(ye.InvalidParams,`Invalid elicitation request: ${g}`)}const{params:m}=u.data;m.mode=m.mode??"form";const{supportsFormMode:f,supportsUrlMode:p}=AT(this._capabilities.elicitation);if(m.mode==="form"&&!f)throw new pe(ye.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!p)throw new pe(ye.InvalidParams,"Client does not support URL-mode elicitation requests");const h=await Promise.resolve(r(l,c));if(m.task){const g=Sr(_o,h);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new pe(ye.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}const v=Sr(oc,h);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new pe(ye.InvalidParams,`Invalid elicitation result: ${g}`)}const _=v.data,w=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{ka(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){const a=async(l,c)=>{const u=Sr(O2,l);if(!u.success){const h=u.error instanceof Error?u.error.message:String(u.error);throw new pe(ye.InvalidParams,`Invalid sampling request: ${h}`)}const{params:m}=u.data,f=await Promise.resolve(r(l,c));if(m.task){const h=Sr(_o,f);if(!h.success){const v=h.error instanceof Error?h.error.message:String(h.error);throw new pe(ye.InvalidParams,`Invalid task creation result: ${v}`)}return h.data}const p=Sr(nc,f);if(!p.success){const h=p.error instanceof Error?p.error.message:String(p.error);throw new pe(ye.InvalidParams,`Invalid sampling result: ${h}`)}return p.data};return super.setRequestHandler(t,a)}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:Ts,capabilities:this._capabilities,clientInfo:this._clientInfo}},m2,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Kk.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){OT(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&MT(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Fr,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},A2,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Fr,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},E2,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},k2,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},b2,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},S2,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},$2,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Fr,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Fr,r)}async callTool(t,r=Ps,n){if(this.isToolTaskRequired(t.name))throw new pe(ye.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 pe(ye.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const i=s(o.structuredContent);if(!i.valid)throw new pe(ye.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof pe?i:new pe(ye.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}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},R2,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=V7.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:i,debounceMs:a}=s.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{const m=await o();l(null,m)}catch(m){const f=m instanceof Error?m:new Error(String(m));l(f,null)}},u=()=>{if(a){const m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);const f=setTimeout(c,a);this._listChangedDebounceTimers.set(t,f)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};class p1 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(h1(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(h1(this),r)}}function NT(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function bc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(bc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${bc(e.cause)}`:e.message:`${e}`}function h1(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var f1=e=>{throw TypeError(e)},Sc=(e,t,r)=>t.has(e)||f1("Cannot "+r),$e=(e,t,r)=>(Sc(e,t,"read from private field"),r?r.call(e):t.get(e)),Fe=(e,t,r)=>t.has(e)?f1("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ue=(e,t,r,n)=>(Sc(e,t,"write to private field"),t.set(e,r),r),cr=(e,t,r)=>(Sc(e,t,"access private method"),r),ft,Wr,Cn,Ea,Ta,So,kn,$o,kr,En,Tn,In,Co,Zt,$c,Cc,kc,m1,Ec,Tc,ko,Ic,Rc;class Eo extends EventTarget{constructor(t,r){var n,o;super(),Fe(this,Zt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Fe(this,ft),Fe(this,Wr),Fe(this,Cn),Fe(this,Ea),Fe(this,Ta),Fe(this,So),Fe(this,kn),Fe(this,$o,null),Fe(this,kr),Fe(this,En),Fe(this,Tn,null),Fe(this,In,null),Fe(this,Co,null),Fe(this,Cc,async s=>{var i;$e(this,En).reset();const{body:a,redirected:l,status:c,headers:u}=s;if(c===204){cr(this,Zt,ko).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Ue(this,Cn,new URL(s.url)):Ue(this,Cn,void 0),c!==200){cr(this,Zt,ko).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){cr(this,Zt,ko).call(this,'Invalid content type, expected "text/event-stream"',c);return}if($e(this,ft)===this.CLOSED)return;Ue(this,ft,this.OPEN);const m=new Event("open");if((i=$e(this,Co))==null||i.call(this,m),this.dispatchEvent(m),typeof a!="object"||!a||!("getReader"in a)){cr(this,Zt,ko).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const f=new TextDecoder,p=a.getReader();let h=!0;do{const{done:v,value:_}=await p.read();_&&$e(this,En).feed(f.decode(_,{stream:!v})),v&&(h=!1,$e(this,En).reset(),cr(this,Zt,Ic).call(this))}while(h)}),Fe(this,kc,s=>{Ue(this,kr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&cr(this,Zt,Ic).call(this,bc(s))}),Fe(this,Ec,s=>{typeof s.id=="string"&&Ue(this,$o,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:$e(this,Cn)?$e(this,Cn).origin:$e(this,Wr).origin,lastEventId:s.id||""});$e(this,In)&&(!s.event||s.event==="message")&&$e(this,In).call(this,i),this.dispatchEvent(i)}),Fe(this,Tc,s=>{Ue(this,So,s)}),Fe(this,Rc,()=>{Ue(this,kn,void 0),$e(this,ft)===this.CONNECTING&&cr(this,Zt,$c).call(this)});try{if(t instanceof URL)Ue(this,Wr,t);else if(typeof t=="string")Ue(this,Wr,new URL(t,qT()));else throw new Error("Invalid URL")}catch{throw NT("An invalid or illegal string was specified")}Ue(this,En,cd({onEvent:$e(this,Ec),onRetry:$e(this,Tc)})),Ue(this,ft,this.CONNECTING),Ue(this,So,3e3),Ue(this,Ta,(n=r?.fetch)!=null?n:globalThis.fetch),Ue(this,Ea,(o=r?.withCredentials)!=null?o:!1),cr(this,Zt,$c).call(this)}get readyState(){return $e(this,ft)}get url(){return $e(this,Wr).href}get withCredentials(){return $e(this,Ea)}get onerror(){return $e(this,Tn)}set onerror(t){Ue(this,Tn,t)}get onmessage(){return $e(this,In)}set onmessage(t){Ue(this,In,t)}get onopen(){return $e(this,Co)}set onopen(t){Ue(this,Co,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(){$e(this,kn)&&clearTimeout($e(this,kn)),$e(this,ft)!==this.CLOSED&&($e(this,kr)&&$e(this,kr).abort(),Ue(this,ft,this.CLOSED),Ue(this,kr,void 0))}}ft=new WeakMap,Wr=new WeakMap,Cn=new WeakMap,Ea=new WeakMap,Ta=new WeakMap,So=new WeakMap,kn=new WeakMap,$o=new WeakMap,kr=new WeakMap,En=new WeakMap,Tn=new WeakMap,In=new WeakMap,Co=new WeakMap,Zt=new WeakSet,$c=function(){Ue(this,ft,this.CONNECTING),Ue(this,kr,new AbortController),$e(this,Ta)($e(this,Wr),cr(this,Zt,m1).call(this)).then($e(this,Cc)).catch($e(this,kc))},Cc=new WeakMap,kc=new WeakMap,m1=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...$e(this,$o)?{"Last-Event-ID":$e(this,$o)}:void 0},cache:"no-store",signal:(e=$e(this,kr))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ec=new WeakMap,Tc=new WeakMap,ko=function(e,t){var r;$e(this,ft)!==this.CLOSED&&Ue(this,ft,this.CLOSED);const n=new p1("error",{code:t,message:e});(r=$e(this,Tn))==null||r.call(this,n),this.dispatchEvent(n)},Ic=function(e,t){var r;if($e(this,ft)===this.CLOSED)return;Ue(this,ft,this.CONNECTING);const n=new p1("error",{code:t,message:e});(r=$e(this,Tn))==null||r.call(this,n),this.dispatchEvent(n),Ue(this,kn,setTimeout($e(this,Rc),$e(this,So)))},Rc=new WeakMap,Eo.CONNECTING=0,Eo.OPEN=1,Eo.CLOSED=2;function qT(){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}function Ia(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function g1(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Ia(t.headers),...Ia(n.headers)}:t.headers};return e(r,o)}:e}const Qe=Qd().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:hi.custom,message:"URL must be parseable",fatal:!0}),Ga}).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"}),LT=Ce({resource:d().url(),authorization_servers:R(Qe).optional(),jwks_uri:d().url().optional(),scopes_supported:R(d()).optional(),bearer_methods_supported:R(d()).optional(),resource_signing_alg_values_supported:R(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:te().optional(),authorization_details_types_supported:R(d()).optional(),dpop_signing_alg_values_supported:R(d()).optional(),dpop_bound_access_tokens_required:te().optional()}),_1=Ce({issuer:d(),authorization_endpoint:Qe,token_endpoint:Qe,registration_endpoint:Qe.optional(),scopes_supported:R(d()).optional(),response_types_supported:R(d()),response_modes_supported:R(d()).optional(),grant_types_supported:R(d()).optional(),token_endpoint_auth_methods_supported:R(d()).optional(),token_endpoint_auth_signing_alg_values_supported:R(d()).optional(),service_documentation:Qe.optional(),revocation_endpoint:Qe.optional(),revocation_endpoint_auth_methods_supported:R(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:R(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:R(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:R(d()).optional(),code_challenge_methods_supported:R(d()).optional(),client_id_metadata_document_supported:te().optional()}),UT=Ce({issuer:d(),authorization_endpoint:Qe,token_endpoint:Qe,userinfo_endpoint:Qe.optional(),jwks_uri:Qe,registration_endpoint:Qe.optional(),scopes_supported:R(d()).optional(),response_types_supported:R(d()),response_modes_supported:R(d()).optional(),grant_types_supported:R(d()).optional(),acr_values_supported:R(d()).optional(),subject_types_supported:R(d()),id_token_signing_alg_values_supported:R(d()),id_token_encryption_alg_values_supported:R(d()).optional(),id_token_encryption_enc_values_supported:R(d()).optional(),userinfo_signing_alg_values_supported:R(d()).optional(),userinfo_encryption_alg_values_supported:R(d()).optional(),userinfo_encryption_enc_values_supported:R(d()).optional(),request_object_signing_alg_values_supported:R(d()).optional(),request_object_encryption_alg_values_supported:R(d()).optional(),request_object_encryption_enc_values_supported:R(d()).optional(),token_endpoint_auth_methods_supported:R(d()).optional(),token_endpoint_auth_signing_alg_values_supported:R(d()).optional(),display_values_supported:R(d()).optional(),claim_types_supported:R(d()).optional(),claims_supported:R(d()).optional(),service_documentation:d().optional(),claims_locales_supported:R(d()).optional(),ui_locales_supported:R(d()).optional(),claims_parameter_supported:te().optional(),request_parameter_supported:te().optional(),request_uri_parameter_supported:te().optional(),require_request_uri_registration:te().optional(),op_policy_uri:Qe.optional(),op_tos_uri:Qe.optional(),client_id_metadata_document_supported:te().optional()}),jT=C({...UT.shape,..._1.pick({code_challenge_methods_supported:!0}).shape}),DT=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:cp().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),zT=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),v1=Qe.optional().or(O("").transform(()=>{})),ZT=C({redirect_uris:R(Qe),token_endpoint_auth_method:d().optional(),grant_types:R(d()).optional(),response_types:R(d()).optional(),client_name:d().optional(),client_uri:Qe.optional(),logo_uri:v1,scope:d().optional(),contacts:R(d()).optional(),tos_uri:v1,policy_uri:d().optional(),jwks_uri:Qe.optional(),jwks:tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),FT=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:A().optional(),client_secret_expires_at:A().optional()}).strip(),VT=ZT.merge(FT);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function HT(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function BT({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 Ve 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 xc extends Ve{}xc.errorCode="invalid_request";class Ra extends Ve{}Ra.errorCode="invalid_client";class xa extends Ve{}xa.errorCode="invalid_grant";class Pa extends Ve{}Pa.errorCode="unauthorized_client";class Pc extends Ve{}Pc.errorCode="unsupported_grant_type";class Oc extends Ve{}Oc.errorCode="invalid_scope";class Mc extends Ve{}Mc.errorCode="access_denied";class Rn extends Ve{}Rn.errorCode="server_error";class Ac extends Ve{}Ac.errorCode="temporarily_unavailable";class Nc extends Ve{}Nc.errorCode="unsupported_response_type";class qc extends Ve{}qc.errorCode="unsupported_token_type";class Lc extends Ve{}Lc.errorCode="invalid_token";class Uc extends Ve{}Uc.errorCode="method_not_allowed";class jc extends Ve{}jc.errorCode="too_many_requests";class Oa extends Ve{}Oa.errorCode="invalid_client_metadata";class Dc extends Ve{}Dc.errorCode="insufficient_scope";class zc extends Ve{}zc.errorCode="invalid_target";const JT={[xc.errorCode]:xc,[Ra.errorCode]:Ra,[xa.errorCode]:xa,[Pa.errorCode]:Pa,[Pc.errorCode]:Pc,[Oc.errorCode]:Oc,[Mc.errorCode]:Mc,[Rn.errorCode]:Rn,[Ac.errorCode]:Ac,[Nc.errorCode]:Nc,[qc.errorCode]:qc,[Lc.errorCode]:Lc,[Uc.errorCode]:Uc,[jc.errorCode]:jc,[Oa.errorCode]:Oa,[Dc.errorCode]:Dc,[zc.errorCode]:zc};class Rt extends Error{constructor(t){super(t??"Unauthorized")}}function WT(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Zc="code",Fc="S256";function GT(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&&WT(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 KT(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":YT(o,s,r);return;case"client_secret_post":QT(o,s,n);return;case"none":XT(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function YT(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 QT(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function XT(e,t){t.set("client_id",e)}async function y1(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=zT.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=JT[o]||Rn;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Rn(o)}}async function Gr(e,t){try{return await Vc(e,t)}catch(r){if(r instanceof Ra||r instanceof Pa)return await e.invalidateCredentials?.("all"),await Vc(e,t);if(r instanceof xa)return await e.invalidateCredentials?.("tokens"),await Vc(e,t);throw r}}async function Vc(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await rI(t,{resourceMetadataUrl:o},s),i.authorization_servers&&i.authorization_servers.length>0&&(a=i.authorization_servers[0])}catch{}a||(a=new URL("/",t));const l=await tI(t,e,i),c=await iI(a,{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 _=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!eI(w))throw new Oa(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(_&&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 y=await pI(a,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(y),u=y}}const m=!e.redirectUrl;if(r!==void 0||m){const _=await dI(e,a,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}const f=await e.tokens();if(f?.refresh_token)try{const _=await uI(a,{metadata:c,clientInformation:u,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof Ve)||_ instanceof Rn))throw _}const p=e.state?await e.state():void 0,{authorizationUrl:h,codeVerifier:v}=await lI(a,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(h),"REDIRECT"}function eI(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function tI(e,t,r){const n=HT(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!BT({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 Ma(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Hc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Hc(e,"scope")||void 0,a=Hc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Hc(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 rI(e,t,r=fetch){const n=await sI(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 LT.parse(await n.json())}async function Bc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Bc(e,void 0,r):void 0;throw n}}function nI(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function w1(e,t,r=fetch){return await Bc(e,{"MCP-Protocol-Version":t},r)}function oI(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function sI(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??Ts;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=nI(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await w1(i,s,r);if(!n?.metadataUrl&&oI(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await w1(l,s,r)}return a}function aI(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 iI(e,{fetchFn:t=fetch,protocolVersion:r=Ts}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=aI(e);for(const{url:s,type:i}of o){const a=await Bc(s,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?_1.parse(await a.json()):jT.parse(await a.json())}}}async function lI(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Zc))throw new Error(`Incompatible auth server: does not support response type ${Zc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Fc))throw new Error(`Incompatible auth server: does not support code challenge method ${Fc}`)}else a=new URL("/authorize",e);const l=await Gi(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",Zc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",Fc),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:c}}function cI(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function b1(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){const a=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,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],m=GT(n,u);KT(m,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await y1(c);return DT.parse(await c.json())}async function uI(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await b1(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function dI(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const i=e.clientMetadata.scope;let a;if(e.prepareTokenRequest&&(a=await e.prepareTokenRequest(i)),!a){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();a=cI(o,c,e.redirectUrl)}const l=await e.clientInformation();return b1(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function pI(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 y1(s);return VT.parse(await s.json())}let hI=class extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}},S1=class{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=g1(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Rt("No auth provider");let t;try{t=await Gr(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 Rt;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=Ia(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 Eo(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const a=await t(o,{...s,headers:i});if(a.status===401&&a.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=Ma(a);this._resourceMetadataUrl=l,this._scope=c}return a}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new hI(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(i){n(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let i;try{i=yn.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}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 Rt("No auth provider");if(await Gr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rt("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:i,scope:a}=Ma(o);if(this._resourceMetadataUrl=i,this._scope=a,await Gr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rt;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 fI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class xn extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class mI{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=g1(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??fI}async _authThenStart(){if(!this._authProvider)throw new Rt("No auth provider");let t;try{t=await Gr(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 Rt;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=Ia(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 xn(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 i,a=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Pr({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){const{value:p,done:h}=await u.read();if(h)break;if(p.id&&(i=p.id,a=!0,o?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{const v=yn.parse(JSON.parse(p.data));po(v)&&(l=!0,s!==void 0&&(v.id=s)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}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 Rt("No auth provider");if(await Gr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rt("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:jl(t)?t.id:void 0}).catch(f=>this.onerror?.(f));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),l=a.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!a.ok){const f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new xn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:p,scope:h}=Ma(a);if(this._resourceMetadataUrl=p,this._scope=h,await Gr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Rt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){const{resourceMetadataUrl:p,scope:h,error:v}=Ma(a);if(v==="insufficient_scope"){const _=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new xn(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=_??void 0,await Gr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Rt;return this.send(t)}}throw new xn(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),p7(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}const u=(Array.isArray(t)?t:[t]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,m=a.headers.get("content-type");if(u)if(m?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(m?.includes("application/json")){const f=await a.json(),p=Array.isArray(f)?f.map(h=>yn.parse(h)):[yn.parse(f)];for(const h of p)this.onmessage?.(h)}else throw await a.body?.cancel(),new xn(-1,`Unexpected content type: ${m}`);else await a.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 xn(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})}}const gI="mcp";let _I=class{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,gI),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=yn.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 Pn=Ft;(function(e,t){const r=Ft,n=Ft,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())}})(Aa,-118057+3521*-35+-2099*-233);const vI=()=>{const e=Ft,t=Ft,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(i,a){return i!==a},r[t(394)]=t(414),r.ktWqD=function(i,a){return i!==a},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}},yI=(e,t,r)=>{const n=Ft,o=Ft,s={};s.eOzBp=function(a,l){return a!==l},s.ooaJk="undefined",s[n(402)]=function(a,l){return a===l},s[n(421)]="function";const i=s;i[o(389)](typeof window,i.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&i.pTvSc(typeof e[o(423)],i[n(421)])&&e.postMessage(t,r)};class $1{constructor(t){this._port=t}async[Pn(401)](){const t=Pn,r=Pn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const i=t;try{const a=yn.parse(n.data.message);(o=this.onmessage)==null||o.call(this,a,n[i(412)][i(428)])}catch(a){const l=new Error("MessageChannel failed to parse message: "+a);(s=this[i(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,i=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,i)},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 i;const a=Ft,l=Ft;try{const c={};c[a(404)]=r?.[a(404)];const u={};u[a(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[a(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(i=this.onerror)==null||i.call(this,u),s(u)}})}async close(){var t,r;const n=Pn,o=Pn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class wI extends $1{constructor(t,r=vI()){const n=Pn,o={lSpBh:function(i,a,l,c){return i(a,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](yI,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function Aa(){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 Aa=function(){return e},Aa()}function Ft(e,t){const r=Aa();return Ft=function(n,o){return n=n-(17227+1*-16844),r[n]},Ft(e,t)}(function(e,t){const r=Oe,n=Oe,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())}})(Na,-411935*1+228107+208149*2);const bI=async(e,t,r)=>{var n;const o=Oe,s=Oe,i={};i.VRyiJ="tools/list",i.VkPYu="tools/call",i[o(475)]=o(411),i.SoCaE="resources/templates/list",i[s(484)]="resources/read",i[o(461)]="prompts/get",i.srIIC=s(477),i[s(436)]=s(478),i[s(442)]=o(437),i.dEmVs=o(465);const a=i,{id:l,method:c,params:u}=r;let m={};switch(c){case a.VRyiJ:m=await t.listTools(u);break;case a.VkPYu:m=await t.callTool(u);break;case a.fgMSD:m=await t.listResources(u);break;case a[s(466)]:m=await t.listResourceTemplates(u);break;case a.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 a[s(461)]:m=await t[s(414)](u);break;case a[o(412)]:m=await t[o(491)](u);break;case a[o(436)]:m=await t[o(478)]();break;case a.kkNqg:m=await t.complete(u);break;case o(464):m=await t.setLoggingLevel(u?.[s(443)]);break}const f={};f.result=m,f.jsonrpc=a[s(472)],f.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](f))},SI=async(e,t,r)=>{var n;const o=Oe,s=Oe,i={};i[o(487)]=s(462),i.ypHTC="ping",i.fPExS=o(465);const a=i,{id:l,method:c,params:u}=r;let m={};switch(c){case"roots/list":const p={};p.method=c,p[s(446)]=u,m=await t[o(469)](p,N2);break;case"sampling/createMessage":const h={};h[o(481)]=c,h[o(446)]=u,m=await t.request(h,nc);break;case a[o(487)]:const v={};v.method=c,v[s(446)]=u,m=await t.request(v,oc);break;case a.ypHTC:const _={};_.method=c,m=await t.request(_,Fr);break}const f={};return f.result=m,f.jsonrpc=a.fPExS,f.id=l,await((n=e?.transport)==null?void 0:n.send(f)),m};function Oe(e,t){const r=Na();return Oe=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Oe(e,t)}const $I=(e,t)=>{const r=Oe,n=Oe,o={vYlhn:function(i,a){return i===a},DhPFX:r(470),NYVNC:function(i,a,l,c){return i(a,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(i,a)=>{var l,c,u,m,f;const p=n,h=r,{id:v,method:_}=i;try{o[p(451)](_,o.DhPFX)?await s.call(e,i,a):await o[h(474)](bI,e,t,i)}catch(w){const{code:g,message:y,data:b}=w;try{if(g){const S={};S[h(485)]=g,S[p(422)]=y,S.data=b;const $={};$[h(448)]=S,$.jsonrpc=o[p(417)],$.id=v,await((l=e?.transport)==null?void 0:l[h(460)]($))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(S){(f=(m=e?.transport)==null?void 0:m.onerror)==null||f.call(m,S)}}}},CI=(e,t)=>{const r=Oe,n=Oe,o={};o[r(476)]=r(439),o[r(431)]=function(i,a){return i!==a},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async i=>{var a,l;const c=r,u=n,{method:m,params:f}=i;if(m!==s[c(476)]&&(s.QWYMz(m,s.UPdQt)||f?.[u(490)]))try{await t[c(445)](i)}catch(p){(l=(a=e?.[c(488)])==null?void 0:a[c(480)])==null||l.call(a,p)}}},kI=(e,t)=>async r=>{var n,o,s,i,a;const l=Oe,c=Oe,u={TJhyV:function(m,f,p,h){return m(f,p,h)},MMNTY:l(465)};try{return await u.TJhyV(SI,e,t,r)}catch(m){const{code:f,message:p,data:h}=m;try{if(f){const v={};v.code=f,v[l(422)]=p,v[c(419)]=h;const _={};_[l(448)]=v,_[l(424)]=u.MMNTY,_.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](_))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,m)}catch(v){(a=(i=e?.[l(488)])==null?void 0:i.onerror)==null||a.call(i,v)}}},EI=(e,t)=>async r=>{var n,o,s;const i=Oe,a=Oe,l={};l.xmcLM=function(f,p){return f!==p},l.xSWLt="notifications/initialized",l[i(420)]=a(453);const c=l,{method:u,params:m}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[a(420)])||m?.[a(490)]))try{const f={...r};f.jsonrpc=i(465),await((n=t?.[i(488)])==null?void 0:n.send(f))}catch(f){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,f)}};function Na(){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 Na=function(){return e},Na()}const TI=(e,t)=>async r=>{var n,o,s,i,a,l;const c=Oe,u=Oe,m={};m.kSvAZ=c(465);const f=m;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(p){const{code:h,message:v,data:_}=p;try{if(h){const w={};w.code=h,w.message=v,w.data=_;const g={};g.error=w,g[u(424)]=f.kSvAZ,g.id=r.id,await((o=e?.transport)==null?void 0:o.send(g))}else(i=(s=e?.transport)==null?void 0:s[c(480)])==null||i.call(s,p)}catch(w){(l=(a=e?.[c(488)])==null?void 0:a[u(480)])==null||l.call(a,w)}}},Jc=()=>{const e=Oe,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Oe;if(c){const m=[];for(const f of r)try{m.push(f(l,c))}catch{}for(const f of m)if(t.rgPZO(f,null))return f}else for(const m of r)try{t[u(427)](m,l)}catch{}},o=l=>{const c=Oe,u=Oe;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Oe,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},i=()=>{const l=Oe;r[l(430)]=-505*7+1322+2213},a={};return a.handleListener=n,a[e(447)]=o,a.removeListener=s,a.clearListener=i,a},II=e=>{const t=Oe,r=Oe,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(423)](Jc);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=i,e.clearResponseListener=a}{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(489)](Jc);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=i,e.clearRequestListener=a}{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n.jsmFN(Jc);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=i,e[r(426)]=a}},RI=(e,{beforeInit:t,afterInit:r}={})=>{const n=Oe,o=Oe,s={HucXo:function(a,l){return a===l},HicFO:n(468),JMaxV:function(a){return a()},DclXr:function(a,l){return a(l)},UynHf:function(a,l){return a===l},yCyFn:function(a){return a()}},i=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(II,e),e[o(438)](a=>{const l=n;e.originalOnResponse[l(440)](e,a)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](a=>{const l=o,{method:c}=a,u=i[l(483)](c);s[l(467)](typeof u,"function")&&u(a)})},xI=ur;(function(e,t){const r=ur,n=ur,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())}})(qa,995159+-6*-266138+-1619768);const PI=()=>{const e=ur,t=ur,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,i=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?i:n[s(209)](i,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},OI=e=>{const t=ur,r=ur,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)]("")},Er={};Er[xI(211)]=PI,Er.randomBytes=OI;function ur(e,t){const r=qa();return ur=function(n,o){return n=n-(-7373+7187*1+395),r[n]},ur(e,t)}function qa(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return qa=function(){return e},qa()}function dr(e,t){const r=La();return dr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},dr(e,t)}const Vt=dr,To=dr;(function(e,t){const r=dr,n=dr,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())}})(La,-4*308317+753182*2+658196);const MI=(e,t)=>{const r=dr,n=dr,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)]($I,e,t),CI(e,t);const s=o[n(283)](kI,t,e),i=o[n(294)](TI,t,e),a=o[r(277)](EI,t,e);t.addRequestListener(s),t.addResponseListener(i),t[n(287)](a),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(i),t[c(252)](a)}},Wc=(e,t,r)=>{const n={QhPqi:function(i,a){return i instanceof a},AIICR:"close",Qalmc:function(i,a,l){return i(a,l)}},o=()=>{var i;n.QhPqi(r,S1)&&((i=r._eventSource)==null||i.addEventListener(n.AIICR,()=>{var a;(a=r[dr(295)])==null||a.close()})),n.Qalmc(MI,e,t)},s={};s.afterInit=o,n.Qalmc(RI,t,s)},C1=(e,t=Er[Vt(299)]())=>{const r=Vt,n=Vt,o={RVabx:function(u,m,f){return u(m,f)},crCTs:"include"},s={};s["sse-session-id"]=t;const i=s,a={};a["sse-session-id"]=t;const l={};l.headers=a,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,m){const f=r,p=r,h=new Headers(m?.[f(268)]||{});Object.entries(i).forEach(([_,w])=>{h.set(_,w)});const v={...m};return v.headers=h,o[p(279)](fetch,u,v)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,i.Authorization=n(256)+e),c},k1=(e,t=Er[Vt(299)]())=>{const r=To,n=Vt,o={};o[r(271)]="include";const s=o,i={};i["stream-session-id"]=t;const a={};a[n(268)]=i,a.credentials=s[r(271)];const l={};l.requestInit=a;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},Gc=async(e,t,r)=>{const n=Vt,o=Vt,s={rRtFD:function(a){return a()},ToRAF:function(a,l){return a instanceof l}},i=s[n(276)](r);try{return await e[o(260)](i),i}catch(a){if(s[n(275)](a,Rt)){const l=await t();return await i[n(257)](l),await Gc(e,t,r)}else throw a}},E1=(e,t)=>{const r=To,n=To,o={};o[r(267)]=function(i,a){return i in a},o.timcZ="waitForOAuthCode",o[r(253)]=function(i,a){return i===a},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 La(){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 La=function(){return e},La()}const AI=async e=>{const t=To,r=Vt,n={GKDjq:function(P,L,N){return P(L,N)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(P){return P()},kdowC:function(P,L,N,j){return P(L,N,j)},KkViY:"sessionId"},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:m}=e,f={};f[r(305)]=l,f.requestInit=c,f.eventSourceInit=u;const p=f,h=a||Er[r(299)](),v=n[t(289)](C1,i,h);if(c){const P={...v.requestInit,...c};P[r(268)]={...v[r(280)][t(268)],...c.headers},p.requestInit=P}else p.requestInit=v[t(280)];if(u){const P={...v[t(270)],...u};p.eventSourceInit=P}else p.eventSourceInit=v[t(270)];const _={};_[t(254)]=!0;const w={};w.roots=_,w[t(298)]={},w[r(303)]={};const g=w,y={};y.name=n[r(261)],y[t(288)]=n.mcbiU;const b={};b[t(251)]=g;const S=new wc(y,b),$=()=>new S1(new URL(s),p);let k=n[t(282)]($);if(l){const P=E1(l,m);k=await n[t(263)](Gc,S,P,$)}else await S.connect(k);Wc(S,o,k),k.sessionId=k[r(274)].searchParams[t(297)](n.KkViY);const I={};return I.transport=k,I.sessionId=k[r(286)],I},NI=async e=>{const t=To,r=Vt,n={wfHUn:function(P,L,N){return P(L,N)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(P){return P()},PdsSn:function(P,L,N,j){return P(L,N,j)}},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:m}=e,f={};f.authProvider=l,f.requestInit=c,f.reconnectionOptions=u;const p=f,h=a||Er.randomUUID(),v=n[r(272)](k1,i,h);if(c){const P={...v[t(280)],...c};P.headers={...v.requestInit[t(268)],...c.headers},p.requestInit=P}else p[r(280)]=v[r(280)];const _={};_[r(254)]=!0;const w={};w.roots=_,w[t(298)]={},w[t(303)]={};const g=w,y={};y.name=n[t(262)],y.version=n.omKPe;const b={};b.capabilities=g;const S=new wc(y,b),$=()=>new mI(new URL(s),p);let k=n.rSiEq($);if(l){const P=n[t(272)](E1,l,m);k=await n[t(296)](Gc,S,P,$)}else await S[t(260)](k);n.PdsSn(Wc,S,o,k);const I={};return I.transport=k,I[r(286)]=k[r(286)],I},qI=async e=>{const t=Vt,r=Vt,n={eZwNI:function(w,g,y,b){return w(g,y,b)}},{client:o,url:s,token:i,sessionId:a}=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 f={};f[r(251)]=u;const p=new wc(m,f),h=a||Er[r(299)](),v=new _I(new URL(s+"?sessionId="+h+r(265)+i));await p.connect(v),n[t(259)](Wc,p,o,v);const _={};return _.transport=v,_[r(286)]=h,_},Tr=Ht,Io=Ht;(function(e,t){const r=Ht,n=Ht,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())}})(Ua,1297719+-42747*-22+-1289197);function Ht(e,t){const r=Ua();return Ht=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Ht(e,t)}const LI=()=>Er.randomBytes(-8746+-382*-23);class KR{constructor(t){const r=Ht,n=Ht,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:i,redirectCallback:a,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=i||o.HbwOh(LI),this._redirectCallback=a||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,i,a;const l=Ht,c=Ht,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 f=await this[c(195)](this._redirectUrl,this[l(197)]);if(!f.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+f[c(205)]);return}const p=await f.json();(a=(i=this._callBackPromise).resolve)==null||a.call(i,p.code)}async[Tr(191)](t,r){const n=Tr,o={};o.xAOmI="POST";const s=o,i={};i["Content-Type"]=n(217);const a={};return a.state=r,fetch(t,{method:s.xAOmI,headers:i,body:new URLSearchParams(a)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=Ht;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[Tr(206)]}get[Io(190)](){return this._clientMetadata}[Tr(213)](){return this[Tr(197)]}[Io(218)](){return this[Io(200)]}[Tr(194)](t){this._clientInformation=t}tokens(){return this[Io(210)]}saveTokens(t){const r=Io;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[Tr(212)](){const t=Tr,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function Ua(){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 Ua=function(){return e},Ua()}(function(e,t){for(var r=Da,n=Da,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())}})(ja,262*-2438+1346066*-1+2*1373311);function ja(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return ja=function(){return e},ja()}function Da(e,t){var r=ja();return Da=function(n,o){n=n-287;var s=r[n];return s},Da(e,t)}function za(e){return!!e._zod}function Za(e,t){return za(e)?ei(e,t):e.safeParse(t)}function T1(e){var t,r;if(!e)return;let n;if(za(e)?n=(r=(t=e._zod)===null||t===void 0?void 0:t.def)===null||r===void 0?void 0:r.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function UI(e){var t;if(za(e)){const i=(t=e._zod)===null||t===void 0?void 0:t.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}const n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const o=e.value;if(o!==void 0)return o}function I1(e){const t=T1(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const n=UI(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function R1(e,t){const r=Za(e,t);if(!r.success)throw r.error;return r.data}const jI=6e4;class DI{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.setNotificationHandler(rl,r=>{const n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(ol,r=>{this._onprogress(r)}),this.setRequestHandler(nl,r=>({}))}_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),wt.fromError(rt.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){var r,n,o;this._transport=t;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};const i=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=l=>{i?.(l),this._onerror(l)};const a=(o=this._transport)===null||o===void 0?void 0:o.onmessage;this._transport.onmessage=(l,c)=>{a?.(l,c),tl(l)||o5(l)?this._onresponse(l):r0(l)?this._onrequest(l,c):n5(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var t;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);const n=wt.fromError(rt.ConnectionClosed,"Connection closed");for(const o of r.values())o(n)}_onerror(t){var r;(r=this.onerror)===null||r===void 0||r.call(this,t)}_onnotification(t){var r;const n=(r=this._notificationHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){var n,o;const s=(n=this._requestHandlers.get(t.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,i=this._transport;if(s===void 0){i?.send({jsonrpc:"2.0",id:t.id,error:{code:rt.MethodNotFound,message:"Method not found"}}).catch(c=>this._onerror(new Error(`Failed to send an error response: ${c}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const l={signal:a.signal,sessionId:i?.sessionId,_meta:(o=t.params)===null||o===void 0?void 0:o._meta,sendNotification:c=>this.notification(c,{relatedRequestId:t.id}),sendRequest:(c,u,m)=>this.request(c,u,{...m,relatedRequestId:t.id}),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(t,l)).then(c=>{if(!a.signal.aborted)return i?.send({result:c,jsonrpc:"2.0",id:t.id})},c=>{var u;if(!a.signal.aborted)return i?.send({jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(c.code)?c.code:rt.InternalError,message:(u=c.message)!==null&&u!==void 0?u:"Internal error",...c.data!==void 0&&{data:c.data}}})}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).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 i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){i(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),tl(t))n(t);else{const o=wt.fromError(t.error.code,t.error.message,t.error.data);n(o)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}=n??{};return new Promise((a,l)=>{var c,u,m,f,p,h;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(t.method),(u=n?.signal)===null||u===void 0||u.throwIfAborted();const v=this._requestMessageId++,_={...t,jsonrpc:"2.0",id:v};n?.onprogress&&(this._progressHandlers.set(v,n.onprogress),_.params={...t.params,_meta:{...((m=t.params)===null||m===void 0?void 0:m._meta)||{},progressToken:v}});const w=b=>{var S;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`))),l(b)};this._responseHandlers.set(v,b=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(b instanceof Error)return l(b);try{const $=Za(r,b.result);$.success?a($.data):l($.error)}catch($){l($)}}}),(f=n?.signal)===null||f===void 0||f.addEventListener("abort",()=>{var b;w((b=n?.signal)===null||b===void 0?void 0:b.reason)});const g=(p=n?.timeout)!==null&&p!==void 0?p:jI,y=()=>w(wt.fromError(rt.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(v,g,n?.maxTotalTimeout,y,(h=n?.resetTimeoutOnProgress)!==null&&h!==void 0?h:!1),this._transport.send(_,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(v),l(b)})})}async notification(t,r){var n,o;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(t.method),((o=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;const c={...t,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(c,r).catch(u=>this._onerror(u))});return}const a={...t,jsonrpc:"2.0"};await this._transport.send(a,r)}setRequestHandler(t,r){const n=I1(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const i=R1(t,o);return Promise.resolve(r(i,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=I1(t);this._notificationHandlers.set(n,o=>{const s=R1(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}}function x1(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zI(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const i=r[o];x1(i)&&x1(s)?r[o]={...i,...s}:r[o]=s}return r}function ZI(){const e=new i1.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return d1(e),e}class FI{constructor(t){this._ajv=t??ZI()}getValidator(t){var r;const n="$id"in t&&typeof t.$id=="string"?(r=this._ajv.getSchema(t.$id))!==null&&r!==void 0?r:this._ajv.compile(t):this._ajv.compile(t);return o=>n(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}function Fa(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&&Fa(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)Fa(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)Fa(r,t)}}function VI(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 HI extends DI{constructor(t,r){var n,o;super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(o=r?.jsonSchemaValidator)!==null&&o!==void 0?o:new FI}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=zI(this._capabilities,t)}setRequestHandler(t,r){var n,o,s;const i=T1(t),a=i?.method;if(!a)throw new Error("Schema is missing a method literal");let l;if(za(a)){const u=a,m=(n=u._zod)===null||n===void 0?void 0:n.def;l=(o=m?.value)!==null&&o!==void 0?o:u.value}else{const u=a,m=u._def;l=(s=m?.value)!==null&&s!==void 0?s:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");if(l==="elicitation/create"){const u=async(m,f)=>{var p,h,v;const _=Za(ll,m);if(!_.success){const P=_.error instanceof Error?_.error.message:String(_.error);throw new wt(rt.InvalidParams,`Invalid elicitation request: ${P}`)}const{params:w}=_.data,g=(p=w.mode)!==null&&p!==void 0?p:"form",{supportsFormMode:y,supportsUrlMode:b}=VI(this._capabilities.elicitation);if(g==="form"&&!y)throw new wt(rt.InvalidParams,"Client does not support form-mode elicitation requests");if(g==="url"&&!b)throw new wt(rt.InvalidParams,"Client does not support URL-mode elicitation requests");const S=await Promise.resolve(r(m,f)),$=Za(x0,S);if(!$.success){const P=$.error instanceof Error?$.error.message:String($.error);throw new wt(rt.InvalidParams,`Invalid elicitation result: ${P}`)}const k=$.data,I=g==="form"?w.requestedSchema:void 0;if(g==="form"&&k.action==="accept"&&k.content&&I&&!((v=(h=this._capabilities.elicitation)===null||h===void 0?void 0:h.form)===null||v===void 0)&&v.applyDefaults)try{Fa(I,k.content)}catch{}return k};return super.setRequestHandler(t,u)}return super.setRequestHandler(t,r)}assertCapability(t,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[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:us,capabilities:this._capabilities,clientInfo:this._clientInfo}},i0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!t5.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"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){var r,n,o,s,i;switch(t){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.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(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.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(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.completions))throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){var r;switch(t){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){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}}async ping(t){return this.request({method:"ping"},hn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},P0,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},hn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},S0,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},v0,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},h0,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},f0,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},m0,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},hn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},hn,r)}async callTool(t,r=ms,n){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 wt(rt.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const i=s(o.structuredContent);if(!i.valid)throw new wt(rt.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof wt?i:new wt(rt.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}cacheToolOutputSchemas(t){this._cachedToolOutputValidators.clear();for(const r of t)if(r.outputSchema){const n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},k0,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class BI extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class JI{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=Qf(r?.fetch,r?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new qt("No auth provider");let r;try{r=await zr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(t=this.onerror)===null||t===void 0||t.call(this,n),n}if(r!=="AUTHORIZED")throw new qt;return await this._startOrAuth()}async _commonHeaders(){var t;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(t=this._requestInit)===null||t===void 0?void 0:t.headers})}_startOrAuth(){var t,r,n;const o=(n=(r=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((s,i)=>{this._eventSource=new Eo(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await o(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:m,scope:f}=bs(u);this._resourceMetadataUrl=m,this._scope=f}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(s,i);return}const c=new BI(a.code,a.message,a);i(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;const c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){i(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=a=>{var l,c;const u=a;let m;try{m=pn.parse(JSON.parse(u.data))}catch(f){(l=this.onerror)===null||l===void 0||l.call(this,f);return}(c=this.onmessage)===null||c===void 0||c.call(this,m)}})}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 qt("No auth provider");if(await zr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qt("Failed to authorize")}async close(){var t,r,n;(t=this._abortController)===null||t===void 0||t.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t){var r,n,o;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,i);if(!a.ok){if(a.status===401&&this._authProvider){const{resourceMetadataUrl:c,scope:u}=bs(a);if(this._resourceMetadataUrl=c,this._scope=u,await zr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qt;return this.send(t)}const l=await a.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${l}`)}}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}}const WI="mcp";class GI{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,WI),this._socket.onerror=n=>{var o;const s="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(s),(o=this.onerror)===null||o===void 0||o.call(this,s)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var o,s;let i;try{i=pn.parse(JSON.parse(n.data))}catch(a){(o=this.onerror)===null||o===void 0||o.call(this,a);return}(s=this.onmessage)===null||s===void 0||s.call(this,i)}})}async close(){var t;(t=this._socket)===null||t===void 0||t.close()}send(t){return new Promise((r,n)=>{var o;if(!this._socket){n(new Error("Not connected"));return}(o=this._socket)===null||o===void 0||o.send(JSON.stringify(t)),r()})}}class KI{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new HI(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:i,onError:a}=t;if(i===!0){const u={client:this.client,url:r,token:n,sessionId:o};let m;return await(async()=>{const{transport:p,sessionId:h}=s==="sse"?await AI(u):s==="socket"?await qI(u):await NI(u);p.onerror=async v=>{a?.(v)},m={transport:p,sessionId:h}})(),m}const l=new URL(r);let c;if(s==="channel"&&(c=new wI(r),await this.client.connect(c)),s==="sse"){const u=C1(n,o);c=new JI(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new GI(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=k1(n,o);c=new El(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,ms,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(ll,t)}onCreateMessage(t){this.client.setRequestHandler(R0,t)}onListRoots(t){this.client.setRequestHandler(O0,t)}onToolListChanged(t){this.client.setNotificationHandler(E0,t)}onPromptListChanged(t){this.client.setNotificationHandler($0,t)}onResourceListChanged(t){this.client.setNotificationHandler(g0,t)}onResourceUpdated(t){this.client.setNotificationHandler(_0,t)}onLoggingMessage(t){this.client.setNotificationHandler(I0,t)}async onPagehide(t){t.persisted||(YI(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const YI=e=>e instanceof El,P1=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const i=async(a,l)=>e.callTool({name:n,arguments:a},{signal:l?.abortSignal});t[n]=_p({description:o,inputSchema:Wn({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}};function QI(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
79
81
 
80
82
  # 工具调用
81
83
 
82
84
  `;return r+=`你可以根据需要调用以下工具:
83
85
 
84
86
  `,r+=`<tools>
85
- `,t.forEach(([n,o])=>{const s=o,a=s.description||"无描述",i=s.parameters||s.inputSchema||{};r+=`${JSON.stringify({name:n,description:a,parameters:i},null,2)}
87
+ `,t.forEach(([n,o])=>{const s=o,i=s.description||"无描述",a=s.parameters||s.inputSchema||{};r+=`${JSON.stringify({name:n,description:i,parameters:a},null,2)}
86
88
  `}),r+=`</tools>
87
89
 
88
90
  `,r+=`## 工具调用格式
@@ -109,23 +111,23 @@ ${t}:`]}}function Mf({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??vo
109
111
  `,r+=`- 必须严格按照 XML 格式调用工具
110
112
  `,r+=`- arguments 必须是有效的 JSON 格式
111
113
  `,r+=`- 如果不需要调用工具,直接给出最终答案即可
112
- `,r}function Lm(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 NS={openai:Bf,deepseek:Qf};class AS{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],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=NS[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 Ko(new URL(t.url)):"type"in t&&t.type==="extension"?r=new Y7(t.sessionId):r=t,t.useAISdkClient??!1){const o=await o4({transport:r});return o.__transport__=r,o}else{const o=new PS({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 Yo||r&&r instanceof Om)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 qm(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=MS(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
113
- ${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.messages];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===ni?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 h=this._buildMessagesForModel(i,l,u),{tools:d,...p}=s,m=(await a0({model:this.llm(n),messages:h,...p})).text,y={role:"assistant",content:m};l.push(y),a.push(y);const _=Lm(m,r);if(!_)return this.messages=a,{text:m,response:{messages:a}};const f=await this._executeReActToolCall(_.toolName,_.arguments,r),S={role:"user",content:`<tool_response>
114
- ${f.success?JSON.stringify(f.result):`工具执行失败 - ${f.error}`}
115
- </tool_response>`};l.push(S),a.push(S)}return this.messages=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((h,d)=>{l=h,c=d});return{fullStream:new ReadableStream({async start(h){let d=[...t];const p=t[0]?.role==="system"?t[0]:null,w=p?t.slice(1):[...t];let m=0,y="";const _=s.maxImages??3;try{for(;m<o;){m++;const f=a._buildMessagesForModel(p,w,_),{tools:b,...k}=s;delete k.system,delete k.onFinish;const S=await ni({...k,model:i,messages:f});let C="";for await(const ee of S.fullStream)ee.type==="text-delta"?(C+=ee.text||"",h.enqueue({type:"text-delta",text:ee.text})):ee.type==="text-start"?h.enqueue({type:"text-start"}):ee.type==="text-end"||h.enqueue(ee);y+=C;const I={role:"assistant",content:y};w.push(I),d.push(I);const x=Lm(y,r);if(!x){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}if(x.toolName==="computer"&&x.arguments?.action==="terminate"){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}const M=`react-${Date.now()}`;h.enqueue({type:"tool-input-start",id:M,toolName:x.toolName});const P=JSON.stringify(x.arguments,null,2);h.enqueue({type:"tool-input-delta",id:M,delta:P});const U=await a._executeReActToolCall(x.toolName,x.arguments,r);let z,F=U.result;if(U.success&&U.result&&typeof U.result=="object"&&U.result.screenshot){z=U.result.screenshot;const{screenshot:ee,...pe}=U.result;F=pe}let te="";U.success?F&&Array.isArray(F.content)&&F.content.length>0&&F.content[0].text?te=F.content[0].text:te=JSON.stringify(F):te=`工具执行失败 - ${U.error}`;let ie=`<tool_response>
116
- ${te}
117
- </tool_response>`;z&&(ie+=`
118
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),h.enqueue({type:"tool-result",toolCallId:M,result:ie});const se=z?{role:"user",content:[{type:"text",text:ie},{type:"image",image:z}]}:{role:"user",content:ie};w.push(se),d.push(se),y=""}h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d})}catch(f){h.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:Xa(n),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const a=t(s);return a?.response?.then(i=>{this.messages.push(...i.messages)}),a}async chat(t){return this._chat(a0,t)}async chatStream(t){return this._chat(ni,t)}}var mn={},Rl,jm;function qS(){return jm||(jm=1,Rl=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Rl}var Pl={},_r={},Um;function zr(){if(Um)return _r;Um=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 _r.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},_r.getSymbolTotalCodewords=function(n){return t[n]},_r.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},_r.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},_r.isKanjiModeEnabled=function(){return typeof e<"u"},_r.toSJIS=function(n){return e(n)},_r}var Ol={},zm;function Ml(){return zm||(zm=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}}})(Ol)),Ol}var Nl,Dm;function LS(){if(Dm)return Nl;Dm=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++}},Nl=e,Nl}var Al,Zm;function jS(){if(Zm)return Al;Zm=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]},Al=e,Al}var ql={},Fm;function US(){return Fm||(Fm=1,(function(e){const t=zr().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}})(ql)),ql}var Ll={},Vm;function zS(){if(Vm)return Ll;Vm=1;const e=zr().getSymbolSize,t=7;return Ll.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Ll}var jl={},Hm;function DS(){return Hm||(Hm=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 h=0;h<s;h++){let d=o.get(g,h);d===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=d,i=1),d=o.get(h,g),d===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=d,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const 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}})(jl)),jl}var sa={},Bm;function Jm(){if(Bm)return sa;Bm=1;const e=Ml(),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 sa.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}},sa.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}},sa}var Ul={},oo={},Gm;function ZS(){if(Gm)return oo;Gm=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]})(),oo.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},oo.exp=function(n){return e[n]},oo.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},oo}var Wm;function FS(){return Wm||(Wm=1,(function(e){const t=ZS();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}})(Ul)),Ul}var zl,Km;function VS(){if(Km)return zl;Km=1;const e=FS();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},zl=t,zl}var Dl={},Zl={},Fl={},Ym;function Qm(){return Ym||(Ym=1,Fl.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Fl}var Ht={},Xm;function e2(){if(Xm)return Ht;Xm=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
119
- ]))+`;Ht.KANJI=new RegExp(r,"g"),Ht.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Ht.BYTE=new RegExp(n,"g"),Ht.NUMERIC=new RegExp(e,"g"),Ht.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Ht.testKanji=function(l){return o.test(l)},Ht.testNumeric=function(l){return s.test(l)},Ht.testAlphanumeric=function(l){return a.test(l)},Ht}var t2;function Dr(){return t2||(t2=1,(function(e){const t=Qm(),r=e2();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}}})(Zl)),Zl}var r2;function HS(){return r2||(r2=1,(function(e){const t=zr(),r=Jm(),n=Ml(),o=Dr(),s=Qm(),a=7973,i=t.getBCHDigit(a);function l(h,d,p){for(let w=1;w<=40;w++)if(d<=e.getCapacity(w,p,h))return w}function c(h,d){return o.getCharCountIndicator(h,d)+4}function u(h,d){let p=0;return h.forEach(function(w){const m=c(w.mode,d);p+=m+w.getBitsLength()}),p}function g(h,d){for(let p=1;p<=40;p++)if(u(h,p)<=e.getCapacity(p,d,o.MIXED))return p}e.from=function(d,p){return s.isValid(d)?parseInt(d,10):p},e.getCapacity=function(d,p,w){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof w>"u"&&(w=o.BYTE);const m=t.getSymbolTotalCodewords(d),y=r.getTotalCodewordsCount(d,p),_=(m-y)*8;if(w===o.MIXED)return _;const f=_-c(w,d);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(d,p){let w;const m=n.from(p,n.M);if(Array.isArray(d)){if(d.length>1)return g(d,m);if(d.length===0)return 1;w=d[0]}else w=d;return l(w.mode,w.getLength(),m)},e.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let p=d<<12;for(;t.getBCHDigit(p)-i>=0;)p^=a<<t.getBCHDigit(p)-i;return d<<12|p}})(Dl)),Dl}var Vl={},n2;function BS(){if(n2)return Vl;n2=1;const e=zr(),t=1335,r=21522,n=e.getBCHDigit(t);return Vl.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},Vl}var Hl={},Bl,o2;function JS(){if(o2)return Bl;o2=1;const e=Dr();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))},Bl=t,Bl}var Jl,s2;function GS(){if(s2)return Jl;s2=1;const e=Dr(),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)},Jl=r,Jl}var Gl,a2;function WS(){if(a2)return Gl;a2=1;const e=Dr();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)},Gl=t,Gl}var Wl,i2;function KS(){if(i2)return Wl;i2=1;const e=Dr(),t=zr();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]+`
120
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},Wl=r,Wl}var Kl={exports:{}},l2;function YS(){return l2||(l2=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,h,d,p,w,m;!i.empty();){l=i.pop(),c=l.value,g=l.cost,h=r[c]||{};for(u in h)h.hasOwnProperty(u)&&(d=h[u],p=g+d,w=a[u],m=typeof a[u]>"u",(m||w>p)&&(a[u]=p,i.push(u,p),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var y=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(y)}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})(Kl)),Kl.exports}var c2;function QS(){return c2||(c2=1,(function(e){const t=Dr(),r=JS(),n=GS(),o=WS(),s=KS(),a=e2(),i=zr(),l=YS();function c(y){return unescape(encodeURIComponent(y)).length}function u(y,_,f){const b=[];let k;for(;(k=y.exec(f))!==null;)b.push({data:k[0],index:k.index,mode:_,length:k[0].length});return b}function g(y){const _=u(a.NUMERIC,t.NUMERIC,y),f=u(a.ALPHANUMERIC,t.ALPHANUMERIC,y);let b,k;return i.isKanjiModeEnabled()?(b=u(a.BYTE,t.BYTE,y),k=u(a.KANJI,t.KANJI,y)):(b=u(a.BYTE_KANJI,t.BYTE,y),k=[]),_.concat(f,b,k).sort(function(C,I){return C.index-I.index}).map(function(C){return{data:C.data,mode:C.mode,length:C.length}})}function h(y,_){switch(_){case t.NUMERIC:return r.getBitsLength(y);case t.ALPHANUMERIC:return n.getBitsLength(y);case t.KANJI:return s.getBitsLength(y);case t.BYTE:return o.getBitsLength(y)}}function d(y){return y.reduce(function(_,f){const b=_.length-1>=0?_[_.length-1]:null;return b&&b.mode===f.mode?(_[_.length-1].data+=f.data,_):(_.push(f),_)},[])}function p(y){const _=[];for(let f=0;f<y.length;f++){const b=y[f];switch(b.mode){case t.NUMERIC:_.push([b,{data:b.data,mode:t.ALPHANUMERIC,length:b.length},{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.ALPHANUMERIC:_.push([b,{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.KANJI:_.push([b,{data:b.data,mode:t.BYTE,length:c(b.data)}]);break;case t.BYTE:_.push([{data:b.data,mode:t.BYTE,length:c(b.data)}])}}return _}function w(y,_){const f={},b={start:{}};let k=["start"];for(let S=0;S<y.length;S++){const C=y[S],I=[];for(let x=0;x<C.length;x++){const M=C[x],P=""+S+x;I.push(P),f[P]={node:M,lastCount:0},b[P]={};for(let U=0;U<k.length;U++){const z=k[U];f[z]&&f[z].node.mode===M.mode?(b[z][P]=h(f[z].lastCount+M.length,M.mode)-h(f[z].lastCount,M.mode),f[z].lastCount+=M.length):(f[z]&&(f[z].lastCount=M.length),b[z][P]=h(M.length,M.mode)+4+t.getCharCountIndicator(M.mode,_))}}k=I}for(let S=0;S<k.length;S++)b[k[S]].end=0;return{map:b,table:f}}function m(y,_){let f;const b=t.getBestModeForData(y);if(f=t.from(_,b),f!==t.BYTE&&f.bit<b.bit)throw new Error('"'+y+'" cannot be encoded with mode '+t.toString(f)+`.
121
- Suggested mode is: `+t.toString(b));switch(f===t.KANJI&&!i.isKanjiModeEnabled()&&(f=t.BYTE),f){case t.NUMERIC:return new r(y);case t.ALPHANUMERIC:return new n(y);case t.KANJI:return new s(y);case t.BYTE:return new o(y)}}e.fromArray=function(_){return _.reduce(function(f,b){return typeof b=="string"?f.push(m(b,null)):b.data&&f.push(m(b.data,b.mode)),f},[])},e.fromString=function(_,f){const b=g(_,i.isKanjiModeEnabled()),k=p(b),S=w(k,f),C=l.find_path(S.map,"start","end"),I=[];for(let x=1;x<C.length-1;x++)I.push(S.table[C[x]].node);return e.fromArray(d(I))},e.rawSplit=function(_){return e.fromArray(g(_,i.isKanjiModeEnabled()))}})(Hl)),Hl}var u2;function XS(){if(u2)return Pl;u2=1;const e=zr(),t=Ml(),r=LS(),n=jS(),o=US(),s=zS(),a=DS(),i=Jm(),l=VS(),c=HS(),u=BS(),g=Dr(),h=QS();function d(S,C){const I=S.size,x=s.getPositions(C);for(let M=0;M<x.length;M++){const P=x[M][0],U=x[M][1];for(let z=-1;z<=7;z++)if(!(P+z<=-1||I<=P+z))for(let F=-1;F<=7;F++)U+F<=-1||I<=U+F||(z>=0&&z<=6&&(F===0||F===6)||F>=0&&F<=6&&(z===0||z===6)||z>=2&&z<=4&&F>=2&&F<=4?S.set(P+z,U+F,!0,!0):S.set(P+z,U+F,!1,!0))}}function p(S){const C=S.size;for(let I=8;I<C-8;I++){const x=I%2===0;S.set(I,6,x,!0),S.set(6,I,x,!0)}}function w(S,C){const I=o.getPositions(C);for(let x=0;x<I.length;x++){const M=I[x][0],P=I[x][1];for(let U=-2;U<=2;U++)for(let z=-2;z<=2;z++)U===-2||U===2||z===-2||z===2||U===0&&z===0?S.set(M+U,P+z,!0,!0):S.set(M+U,P+z,!1,!0)}}function m(S,C){const I=S.size,x=c.getEncodedBits(C);let M,P,U;for(let z=0;z<18;z++)M=Math.floor(z/3),P=z%3+I-8-3,U=(x>>z&1)===1,S.set(M,P,U,!0),S.set(P,M,U,!0)}function y(S,C,I){const x=S.size,M=u.getEncodedBits(C,I);let P,U;for(P=0;P<15;P++)U=(M>>P&1)===1,P<6?S.set(P,8,U,!0):P<8?S.set(P+1,8,U,!0):S.set(x-15+P,8,U,!0),P<8?S.set(8,x-P-1,U,!0):P<9?S.set(8,15-P-1+1,U,!0):S.set(8,15-P-1,U,!0);S.set(x-8,8,1,!0)}function _(S,C){const I=S.size;let x=-1,M=I-1,P=7,U=0;for(let z=I-1;z>0;z-=2)for(z===6&&z--;;){for(let F=0;F<2;F++)if(!S.isReserved(M,z-F)){let te=!1;U<C.length&&(te=(C[U]>>>P&1)===1),S.set(M,z-F,te),P--,P===-1&&(U++,P=7)}if(M+=x,M<0||I<=M){M-=x,x=-x;break}}}function f(S,C,I){const x=new r;I.forEach(function(F){x.put(F.mode.bit,4),x.put(F.getLength(),g.getCharCountIndicator(F.mode,S)),F.write(x)});const M=e.getSymbolTotalCodewords(S),P=i.getTotalCodewordsCount(S,C),U=(M-P)*8;for(x.getLengthInBits()+4<=U&&x.put(0,4);x.getLengthInBits()%8!==0;)x.putBit(0);const z=(U-x.getLengthInBits())/8;for(let F=0;F<z;F++)x.put(F%2?17:236,8);return b(x,S,C)}function b(S,C,I){const x=e.getSymbolTotalCodewords(C),M=i.getTotalCodewordsCount(C,I),P=x-M,U=i.getBlocksCount(C,I),z=x%U,F=U-z,te=Math.floor(x/U),ie=Math.floor(P/U),se=ie+1,ee=te-ie,pe=new l(ee);let V=0;const O=new Array(U),Z=new Array(U);let j=0;const E=new Uint8Array(S.buffer);for(let fe=0;fe<U;fe++){const ae=fe<F?ie:se;O[fe]=E.slice(V,V+ae),Z[fe]=pe.encode(O[fe]),V+=ae,j=Math.max(j,ae)}const R=new Uint8Array(x);let $=0,H,G;for(H=0;H<j;H++)for(G=0;G<U;G++)H<O[G].length&&(R[$++]=O[G][H]);for(H=0;H<ee;H++)for(G=0;G<U;G++)R[$++]=Z[G][H];return R}function k(S,C,I,x){let M;if(Array.isArray(S))M=h.fromArray(S);else if(typeof S=="string"){let te=C;if(!te){const ie=h.rawSplit(S);te=c.getBestVersionForData(ie,I)}M=h.fromString(S,te||40)}else throw new Error("Invalid data");const P=c.getBestVersionForData(M,I);if(!P)throw new Error("The amount of data is too big to be stored in a QR Code");if(!C)C=P;else if(C<P)throw new Error(`
114
+ `,r}function O1(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,i=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:i}}catch{}return null}const XI={openai:n2,deepseek:c2};class eR{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],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=XI[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 El(new URL(t.url)):"type"in t&&t.type==="extension"?r=new Gk(t.sessionId):r=t,t.useAISdkClient??!1){const o=await XS({transport:r});return o.__transport__=r,o}else{const o=new KI({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 Ss||r&&r instanceof $1)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 P1(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=QI(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
115
+ ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,i=s.execute||s.call;return typeof i!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await i(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 a=[];o.message&&!o.messages?a.push({role:"user",content:o.message}):o.messages?a=[...o.messages]:a=[...this.messages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},m=a[0]?.role==="system"?a:[u,...a];return t===Ji?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 i=[];for(let a=r.length-1;a>=0;a--){const l=r[a];if(this._messageHasImage(l.content))if(s<n)i.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&i.unshift(u)}else i.unshift(l)}return o.push(...i),o}async _chatReActNonStream(t,r,n,o,s){let i=[...t];const a=t[0]?.role==="system"?t[0]:null,l=a?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const f=this._buildMessagesForModel(a,l,u),{tools:p,...h}=s,_=(await Sf({model:this.llm(n),messages:f,...h})).text,w={role:"assistant",content:_};l.push(w),i.push(w);const g=O1(_,r);if(!g)return this.messages=i,{text:_,response:{messages:i}};const y=await this._executeReActToolCall(g.toolName,g.arguments,r),$={role:"user",content:`<tool_response>
116
+ ${y.success?JSON.stringify(y.result):`工具执行失败 - ${y.error}`}
117
+ </tool_response>`};l.push($),i.push($)}return this.messages=i,{text:i[i.length-2]?.content||"",response:{messages:i}}}_chatReActStream(t,r,n,o,s){const i=this,a=this.llm(n);let l,c;const u=new Promise((f,p)=>{l=f,c=p});return{fullStream:new ReadableStream({async start(f){let p=[...t];const h=t[0]?.role==="system"?t[0]:null,v=h?t.slice(1):[...t];let _=0,w="";const g=s.maxImages??3;try{for(;_<o;){_++;const y=i._buildMessagesForModel(h,v,g),{tools:b,...S}=s;delete S.system,delete S.onFinish;const $=await Ji({...S,model:a,messages:y});let k="";for await(const re of $.fullStream)re.type==="text-delta"?(k+=re.text||"",f.enqueue({type:"text-delta",text:re.text})):re.type==="text-start"?f.enqueue({type:"text-start"}):re.type==="text-end"||f.enqueue(re);w+=k;const I={role:"assistant",content:w};v.push(I),p.push(I);const P=O1(w,r);if(!P){f.enqueue({type:"text-end"}),f.close(),i.messages=p,l({messages:p});return}if(P.toolName==="computer"&&P.arguments?.action==="terminate"){f.enqueue({type:"text-end"}),f.close(),i.messages=p,l({messages:p});return}const L=`react-${Date.now()}`;f.enqueue({type:"tool-input-start",id:L,toolName:P.toolName});const N=JSON.stringify(P.arguments,null,2);f.enqueue({type:"tool-input-delta",id:L,delta:N});const j=await i._executeReActToolCall(P.toolName,P.arguments,r);let D,F=j.result;if(j.success&&j.result&&typeof j.result=="object"&&j.result.screenshot){D=j.result.screenshot;const{screenshot:re,...he}=j.result;F=he}let ne="";j.success?F&&Array.isArray(F.content)&&F.content.length>0&&F.content[0].text?ne=F.content[0].text:ne=JSON.stringify(F):ne=`工具执行失败 - ${j.error}`;let ue=`<tool_response>
118
+ ${ne}
119
+ </tool_response>`;D&&(ue+=`
120
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),f.enqueue({type:"tool-result",toolCallId:L,result:ue});const ie=D?{role:"user",content:[{type:"text",text:ue},{type:"image",image:D}]}:{role:"user",content:ue};v.push(ie),p.push(ie),w=""}f.enqueue({type:"text-end"}),f.close(),i.messages=p,l({messages:p})}catch(y){f.error(y),c(y)}}}),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:Fi(n),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const i=t(s);return i?.response?.then(a=>{this.messages.push(...a.messages)}),i}async chat(t){return this._chat(Sf,t)}async chatStream(t){return this._chat(Ji,t)}}var On={},Kc,M1;function tR(){return M1||(M1=1,Kc=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Kc}var Yc={},Ir={},A1;function Kr(){if(A1)return Ir;A1=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 Ir.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},Ir.getSymbolTotalCodewords=function(n){return t[n]},Ir.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ir.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Ir.isKanjiModeEnabled=function(){return typeof e<"u"},Ir.toSJIS=function(n){return e(n)},Ir}var Qc={},N1;function Xc(){return N1||(N1=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}}})(Qc)),Qc}var eu,q1;function rR(){if(q1)return eu;q1=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++}},eu=e,eu}var tu,L1;function nR(){if(L1)return tu;L1=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]},tu=e,tu}var ru={},U1;function oR(){return U1||(U1=1,(function(e){const t=Kr().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let l=1;l<o-1;l++)a[l]=a[l-1]-i;return a.push(6),a.reverse()},e.getPositions=function(n){const o=[],s=e.getRowColCoords(n),i=s.length;for(let a=0;a<i;a++)for(let l=0;l<i;l++)a===0&&l===0||a===0&&l===i-1||a===i-1&&l===0||o.push([s[a],s[l]]);return o}})(ru)),ru}var nu={},j1;function sR(){if(j1)return nu;j1=1;const e=Kr().getSymbolSize,t=7;return nu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},nu}var ou={},D1;function aR(){return D1||(D1=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 i=0,a=0,l=0,c=null,u=null;for(let m=0;m<s;m++){a=l=0,c=u=null;for(let f=0;f<s;f++){let p=o.get(m,f);p===c?a++:(a>=5&&(i+=t.N1+(a-5)),c=p,a=1),p=o.get(f,m),p===u?l++:(l>=5&&(i+=t.N1+(l-5)),u=p,l=1)}a>=5&&(i+=t.N1+(a-5)),l>=5&&(i+=t.N1+(l-5))}return i},e.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let l=0;l<s-1;l++){const c=o.get(a,l)+o.get(a,l+1)+o.get(a+1,l)+o.get(a+1,l+1);(c===4||c===0)&&i++}return i*t.N2},e.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,l=0;for(let c=0;c<s;c++){a=l=0;for(let u=0;u<s;u++)a=a<<1&2047|o.get(c,u),u>=10&&(a===1488||a===93)&&i++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&i++}return i*t.N3},e.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let l=0;l<i;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/i/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 i=s.size;for(let a=0;a<i;a++)for(let l=0;l<i;l++)s.isReserved(l,a)||s.xor(l,a,r(o,l,a))},e.getBestMask=function(o,s){const i=Object.keys(e.Patterns).length;let a=0,l=1/0;for(let c=0;c<i;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,a=c)}return a}})(ou)),ou}var Va={},z1;function Z1(){if(z1)return Va;z1=1;const e=Xc(),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 Va.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}},Va.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}},Va}var su={},Ro={},F1;function iR(){if(F1)return Ro;F1=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]})(),Ro.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Ro.exp=function(n){return e[n]},Ro.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},Ro}var V1;function lR(){return V1||(V1=1,(function(e){const t=iR();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=t.mul(n[i],o[a]);return s},e.mod=function(n,o){let s=new Uint8Array(n);for(;s.length-o.length>=0;){const i=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}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}})(su)),su}var au,H1;function cR(){if(H1)return au;H1=1;const e=lR();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),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},au=t,au}var iu={},lu={},cu={},B1;function J1(){return B1||(B1=1,cu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),cu}var er={},W1;function G1(){if(W1)return er;W1=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
121
+ ]))+`;er.KANJI=new RegExp(r,"g"),er.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),er.BYTE=new RegExp(n,"g"),er.NUMERIC=new RegExp(e,"g"),er.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return er.testKanji=function(l){return o.test(l)},er.testNumeric=function(l){return s.test(l)},er.testAlphanumeric=function(l){return i.test(l)},er}var K1;function Yr(){return K1||(K1=1,(function(e){const t=J1(),r=G1();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,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<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,i){if(e.isValid(s))return s;try{return n(s)}catch{return i}}})(lu)),lu}var Y1;function uR(){return Y1||(Y1=1,(function(e){const t=Kr(),r=Z1(),n=Xc(),o=Yr(),s=J1(),i=7973,a=t.getBCHDigit(i);function l(f,p,h){for(let v=1;v<=40;v++)if(p<=e.getCapacity(v,h,f))return v}function c(f,p){return o.getCharCountIndicator(f,p)+4}function u(f,p){let h=0;return f.forEach(function(v){const _=c(v.mode,p);h+=_+v.getBitsLength()}),h}function m(f,p){for(let h=1;h<=40;h++)if(u(f,h)<=e.getCapacity(h,p,o.MIXED))return h}e.from=function(p,h){return s.isValid(p)?parseInt(p,10):h},e.getCapacity=function(p,h,v){if(!s.isValid(p))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const _=t.getSymbolTotalCodewords(p),w=r.getTotalCodewordsCount(p,h),g=(_-w)*8;if(v===o.MIXED)return g;const y=g-c(v,p);switch(v){case o.NUMERIC:return Math.floor(y/10*3);case o.ALPHANUMERIC:return Math.floor(y/11*2);case o.KANJI:return Math.floor(y/13);case o.BYTE:default:return Math.floor(y/8)}},e.getBestVersionForData=function(p,h){let v;const _=n.from(h,n.M);if(Array.isArray(p)){if(p.length>1)return m(p,_);if(p.length===0)return 1;v=p[0]}else v=p;return l(v.mode,v.getLength(),_)},e.getEncodedBits=function(p){if(!s.isValid(p)||p<7)throw new Error("Invalid QR Code version");let h=p<<12;for(;t.getBCHDigit(h)-a>=0;)h^=i<<t.getBCHDigit(h)-a;return p<<12|h}})(iu)),iu}var uu={},Q1;function dR(){if(Q1)return uu;Q1=1;const e=Kr(),t=1335,r=21522,n=e.getBCHDigit(t);return uu.getEncodedBits=function(s,i){const a=s.bit<<3|i;let l=a<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(a<<10|l)^r},uu}var du={},pu,X1;function pR(){if(X1)return pu;X1=1;const e=Yr();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,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),n.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),n.put(i,a*3+1))},pu=t,pu}var hu,e_;function hR(){if(e_)return hu;e_=1;const e=Yr(),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 i=t.indexOf(this.data[s])*45;i+=t.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},hu=r,hu}var fu,t_;function fR(){if(t_)return fu;t_=1;const e=Yr();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)},fu=t,fu}var mu,r_;function mR(){if(r_)return mu;r_=1;const e=Yr(),t=Kr();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]+`
122
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},mu=r,mu}var gu={exports:{}},n_;function gR(){return n_||(n_=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},i={};i[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var l,c,u,m,f,p,h,v,_;!a.empty();){l=a.pop(),c=l.value,m=l.cost,f=r[c]||{};for(u in f)f.hasOwnProperty(u)&&(p=f[u],h=m+p,v=i[u],_=typeof i[u]>"u",(_||v>h)&&(i[u]=h,a.push(u,h),s[u]=c))}if(typeof o<"u"&&typeof i[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})(gu)),gu.exports}var o_;function _R(){return o_||(o_=1,(function(e){const t=Yr(),r=pR(),n=hR(),o=fR(),s=mR(),i=G1(),a=Kr(),l=gR();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,g,y){const b=[];let S;for(;(S=w.exec(y))!==null;)b.push({data:S[0],index:S.index,mode:g,length:S[0].length});return b}function m(w){const g=u(i.NUMERIC,t.NUMERIC,w),y=u(i.ALPHANUMERIC,t.ALPHANUMERIC,w);let b,S;return a.isKanjiModeEnabled()?(b=u(i.BYTE,t.BYTE,w),S=u(i.KANJI,t.KANJI,w)):(b=u(i.BYTE_KANJI,t.BYTE,w),S=[]),g.concat(y,b,S).sort(function(k,I){return k.index-I.index}).map(function(k){return{data:k.data,mode:k.mode,length:k.length}})}function f(w,g){switch(g){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 p(w){return w.reduce(function(g,y){const b=g.length-1>=0?g[g.length-1]:null;return b&&b.mode===y.mode?(g[g.length-1].data+=y.data,g):(g.push(y),g)},[])}function h(w){const g=[];for(let y=0;y<w.length;y++){const b=w[y];switch(b.mode){case t.NUMERIC:g.push([b,{data:b.data,mode:t.ALPHANUMERIC,length:b.length},{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.ALPHANUMERIC:g.push([b,{data:b.data,mode:t.BYTE,length:b.length}]);break;case t.KANJI:g.push([b,{data:b.data,mode:t.BYTE,length:c(b.data)}]);break;case t.BYTE:g.push([{data:b.data,mode:t.BYTE,length:c(b.data)}])}}return g}function v(w,g){const y={},b={start:{}};let S=["start"];for(let $=0;$<w.length;$++){const k=w[$],I=[];for(let P=0;P<k.length;P++){const L=k[P],N=""+$+P;I.push(N),y[N]={node:L,lastCount:0},b[N]={};for(let j=0;j<S.length;j++){const D=S[j];y[D]&&y[D].node.mode===L.mode?(b[D][N]=f(y[D].lastCount+L.length,L.mode)-f(y[D].lastCount,L.mode),y[D].lastCount+=L.length):(y[D]&&(y[D].lastCount=L.length),b[D][N]=f(L.length,L.mode)+4+t.getCharCountIndicator(L.mode,g))}}S=I}for(let $=0;$<S.length;$++)b[S[$]].end=0;return{map:b,table:y}}function _(w,g){let y;const b=t.getBestModeForData(w);if(y=t.from(g,b),y!==t.BYTE&&y.bit<b.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(y)+`.
123
+ Suggested mode is: `+t.toString(b));switch(y===t.KANJI&&!a.isKanjiModeEnabled()&&(y=t.BYTE),y){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(g){return g.reduce(function(y,b){return typeof b=="string"?y.push(_(b,null)):b.data&&y.push(_(b.data,b.mode)),y},[])},e.fromString=function(g,y){const b=m(g,a.isKanjiModeEnabled()),S=h(b),$=v(S,y),k=l.find_path($.map,"start","end"),I=[];for(let P=1;P<k.length-1;P++)I.push($.table[k[P]].node);return e.fromArray(p(I))},e.rawSplit=function(g){return e.fromArray(m(g,a.isKanjiModeEnabled()))}})(du)),du}var s_;function vR(){if(s_)return Yc;s_=1;const e=Kr(),t=Xc(),r=rR(),n=nR(),o=oR(),s=sR(),i=aR(),a=Z1(),l=cR(),c=uR(),u=dR(),m=Yr(),f=_R();function p($,k){const I=$.size,P=s.getPositions(k);for(let L=0;L<P.length;L++){const N=P[L][0],j=P[L][1];for(let D=-1;D<=7;D++)if(!(N+D<=-1||I<=N+D))for(let F=-1;F<=7;F++)j+F<=-1||I<=j+F||(D>=0&&D<=6&&(F===0||F===6)||F>=0&&F<=6&&(D===0||D===6)||D>=2&&D<=4&&F>=2&&F<=4?$.set(N+D,j+F,!0,!0):$.set(N+D,j+F,!1,!0))}}function h($){const k=$.size;for(let I=8;I<k-8;I++){const P=I%2===0;$.set(I,6,P,!0),$.set(6,I,P,!0)}}function v($,k){const I=o.getPositions(k);for(let P=0;P<I.length;P++){const L=I[P][0],N=I[P][1];for(let j=-2;j<=2;j++)for(let D=-2;D<=2;D++)j===-2||j===2||D===-2||D===2||j===0&&D===0?$.set(L+j,N+D,!0,!0):$.set(L+j,N+D,!1,!0)}}function _($,k){const I=$.size,P=c.getEncodedBits(k);let L,N,j;for(let D=0;D<18;D++)L=Math.floor(D/3),N=D%3+I-8-3,j=(P>>D&1)===1,$.set(L,N,j,!0),$.set(N,L,j,!0)}function w($,k,I){const P=$.size,L=u.getEncodedBits(k,I);let N,j;for(N=0;N<15;N++)j=(L>>N&1)===1,N<6?$.set(N,8,j,!0):N<8?$.set(N+1,8,j,!0):$.set(P-15+N,8,j,!0),N<8?$.set(8,P-N-1,j,!0):N<9?$.set(8,15-N-1+1,j,!0):$.set(8,15-N-1,j,!0);$.set(P-8,8,1,!0)}function g($,k){const I=$.size;let P=-1,L=I-1,N=7,j=0;for(let D=I-1;D>0;D-=2)for(D===6&&D--;;){for(let F=0;F<2;F++)if(!$.isReserved(L,D-F)){let ne=!1;j<k.length&&(ne=(k[j]>>>N&1)===1),$.set(L,D-F,ne),N--,N===-1&&(j++,N=7)}if(L+=P,L<0||I<=L){L-=P,P=-P;break}}}function y($,k,I){const P=new r;I.forEach(function(F){P.put(F.mode.bit,4),P.put(F.getLength(),m.getCharCountIndicator(F.mode,$)),F.write(P)});const L=e.getSymbolTotalCodewords($),N=a.getTotalCodewordsCount($,k),j=(L-N)*8;for(P.getLengthInBits()+4<=j&&P.put(0,4);P.getLengthInBits()%8!==0;)P.putBit(0);const D=(j-P.getLengthInBits())/8;for(let F=0;F<D;F++)P.put(F%2?17:236,8);return b(P,$,k)}function b($,k,I){const P=e.getSymbolTotalCodewords(k),L=a.getTotalCodewordsCount(k,I),N=P-L,j=a.getBlocksCount(k,I),D=P%j,F=j-D,ne=Math.floor(P/j),ue=Math.floor(N/j),ie=ue+1,re=ne-ue,he=new l(re);let V=0;const M=new Array(j),Z=new Array(j);let U=0;const T=new Uint8Array($.buffer);for(let fe=0;fe<j;fe++){const le=fe<F?ue:ie;M[fe]=T.slice(V,V+le),Z[fe]=he.encode(M[fe]),V+=le,U=Math.max(U,le)}const x=new Uint8Array(P);let E=0,H,W;for(H=0;H<U;H++)for(W=0;W<j;W++)H<M[W].length&&(x[E++]=M[W][H]);for(H=0;H<re;H++)for(W=0;W<j;W++)x[E++]=Z[W][H];return x}function S($,k,I,P){let L;if(Array.isArray($))L=f.fromArray($);else if(typeof $=="string"){let ne=k;if(!ne){const ue=f.rawSplit($);ne=c.getBestVersionForData(ue,I)}L=f.fromString($,ne||40)}else throw new Error("Invalid data");const N=c.getBestVersionForData(L,I);if(!N)throw new Error("The amount of data is too big to be stored in a QR Code");if(!k)k=N;else if(k<N)throw new Error(`
122
124
  The chosen QR Code version cannot contain this amount of data.
123
- Minimum version required to store current data is: `+P+`.
124
- `);const U=f(C,I,M),z=e.getSymbolSize(C),F=new n(z);return d(F,C),p(F),w(F,C),y(F,I,0),C>=7&&m(F,C),_(F,U),isNaN(x)&&(x=a.getBestMask(F,y.bind(null,F,I))),a.applyMask(x,F),y(F,I,x),{modules:F,version:C,errorCorrectionLevel:I,maskPattern:x,segments:M}}return Pl.create=function(C,I){if(typeof C>"u"||C==="")throw new Error("No input text");let x=t.M,M,P;return typeof I<"u"&&(x=t.from(I.errorCorrectionLevel,t.M),M=c.from(I.version),P=a.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),k(C,M,x,P)},Pl}var Yl={},Ql={},d2;function p2(){return d2||(d2=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 h=0;h<c;h++)for(let d=0;d<c;d++){let p=(h*c+d)*4,w=s.color.light;if(h>=u&&d>=u&&h<c-u&&d<c-u){const m=Math.floor((h-u)/l),y=Math.floor((d-u)/l);w=g[i[m*a+y]?1:0]}n[p++]=w.r,n[p++]=w.g,n[p++]=w.b,n[p]=w.a}}})(Ql)),Ql}var f2;function eC(){return f2||(f2=1,(function(e){const t=p2();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"),h=g.createImageData(u,u);return t.qrToImageData(h.data,s,l),r(g,c,u),g.putImageData(h,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)}})(Yl)),Yl}var Xl={},h2;function tC(){if(h2)return Xl;h2=1;const e=p2();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 h=Math.floor(g%s),d=Math.floor(g/s);!h&&!c&&(c=!0),o[g]?(u++,g>0&&h>0&&o[g-1]||(i+=c?r("M",h+a,.5+d+a):r("m",l,0),l=0,c=!1),h+1<s&&o[g+1]||(i+=r("h",u),u=0)):l++}return i}return Xl.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,g=c+l.margin*2,h=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+g+"v"+g+'H0z"/>':"",d="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',p='viewBox="0 0 '+g+" "+g+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+p+' shape-rendering="crispEdges">'+h+d+`</svg>
125
- `;return typeof i=="function"&&i(null,m),m},Xl}var m2;function rC(){if(m2)return mn;m2=1;const e=qS(),t=XS(),r=eC(),n=tC();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),g=u.length,h=typeof u[g-1]=="function";if(!h&&!e())throw new Error("Callback required as last argument");if(h){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(d,p){try{const w=t.create(i,l);d(s(w,a,l))}catch(w){p(w)}})}try{const d=t.create(i,l);c(null,s(d,a,l))}catch(d){c(d)}}return mn.create=t.create,mn.toCanvas=o.bind(null,r.render),mn.toDataURL=o.bind(null,r.renderToDataURL),mn.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),mn}var nC=rC();const g2=dd(nC);class v2{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 g2.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return g2.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const oC={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class sC{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={...oC,...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=`
125
+ Minimum version required to store current data is: `+N+`.
126
+ `);const j=y(k,I,L),D=e.getSymbolSize(k),F=new n(D);return p(F,k),h(F),v(F,k),w(F,I,0),k>=7&&_(F,k),g(F,j),isNaN(P)&&(P=i.getBestMask(F,w.bind(null,F,I))),i.applyMask(P,F),w(F,I,P),{modules:F,version:k,errorCorrectionLevel:I,maskPattern:P,segments:L}}return Yc.create=function(k,I){if(typeof k>"u"||k==="")throw new Error("No input text");let P=t.M,L,N;return typeof I<"u"&&(P=t.from(I.errorCorrectionLevel,t.M),L=c.from(I.version),N=i.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),S(k,L,P,N)},Yc}var _u={},vu={},a_;function i_(){return a_||(a_=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,i=n.scale||4;return{width:s,scale:s?4:i,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 i=o.modules.size,a=o.modules.data,l=e.getScale(i,s),c=Math.floor((i+s.margin*2)*l),u=s.margin*l,m=[s.color.light,s.color.dark];for(let f=0;f<c;f++)for(let p=0;p<c;p++){let h=(f*c+p)*4,v=s.color.light;if(f>=u&&p>=u&&f<c-u&&p<c-u){const _=Math.floor((f-u)/l),w=Math.floor((p-u)/l);v=m[a[_*i+w]?1:0]}n[h++]=v.r,n[h++]=v.g,n[h++]=v.b,n[h]=v.a}}})(vu)),vu}var l_;function yR(){return l_||(l_=1,(function(e){const t=i_();function r(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,i,a){let l=a,c=i;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),i||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),m=c.getContext("2d"),f=m.createImageData(u,u);return t.qrToImageData(f.data,s,l),r(m,c,u),m.putImageData(f,0,0),c},e.renderToDataURL=function(s,i,a){let l=a;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),l||(l={});const c=e.render(s,i,l),u=l.type||"image/png",m=l.rendererOpts||{};return c.toDataURL(u,m.quality)}})(_u)),_u}var yu={},c_;function wR(){if(c_)return yu;c_=1;const e=i_();function t(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function r(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function n(o,s,i){let a="",l=0,c=!1,u=0;for(let m=0;m<o.length;m++){const f=Math.floor(m%s),p=Math.floor(m/s);!f&&!c&&(c=!0),o[m]?(u++,m>0&&f>0&&o[m-1]||(a+=c?r("M",f+i,.5+p+i):r("m",l,0),l=0,c=!1),f+1<s&&o[m+1]||(a+=r("h",u),u=0)):l++}return a}return yu.render=function(s,i,a){const l=e.getOptions(i),c=s.modules.size,u=s.modules.data,m=c+l.margin*2,f=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+m+"v"+m+'H0z"/>':"",p="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',h='viewBox="0 0 '+m+" "+m+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+h+' shape-rendering="crispEdges">'+f+p+`</svg>
127
+ `;return typeof a=="function"&&a(null,_),_},yu}var u_;function bR(){if(u_)return On;u_=1;const e=tR(),t=vR(),r=yR(),n=wR();function o(s,i,a,l,c){const u=[].slice.call(arguments,1),m=u.length,f=typeof u[m-1]=="function";if(!f&&!e())throw new Error("Callback required as last argument");if(f){if(m<2)throw new Error("Too few arguments provided");m===2?(c=a,a=i,i=l=void 0):m===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=i,i=void 0))}else{if(m<1)throw new Error("Too few arguments provided");return m===1?(a=i,i=l=void 0):m===2&&!i.getContext&&(l=a,a=i,i=void 0),new Promise(function(p,h){try{const v=t.create(a,l);p(s(v,i,l))}catch(v){h(v)}})}try{const p=t.create(a,l);c(null,s(p,i,l))}catch(p){c(p)}}return On.create=t.create,On.toCanvas=o.bind(null,r.render),On.toDataURL=o.bind(null,r.renderToDataURL),On.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),On}var SR=bR();const d_=Si(SR);class p_{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 d_.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return d_.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const $R={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class CR{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={...$R,...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=`
126
128
  <div class="${this.opts.className}__arrow"></div>
127
129
  <div class="${this.opts.className}__inner">${t}</div>
128
- `}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 _2="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(_2))return;const e=document.createElement("style");e.id=_2,e.textContent=`
130
+ `}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,i=6,[a,l="center"]=t.split("-");let c=0,u=0;return a==="top"?c=r.top+o-n.height-i:a==="bottom"?c=r.bottom+o+i:a==="left"?u=r.left+s-n.width-i:a==="right"&&(u=r.right+s+i),(a==="top"||a==="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),(a==="left"||a==="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,i=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+i.width<=o-5&&t+i.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 h_="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(h_))return;const e=document.createElement("style");e.id=h_,e.textContent=`
129
131
  .tiny-remoter-native-tooltip {
130
132
  position: absolute;
131
133
  z-index: 9999;
@@ -172,9 +174,9 @@ Minimum version required to store current data is: `+P+`.
172
174
  transform: translateY(-50%);
173
175
  border-right-color: rgba(0,0,0,.75);
174
176
  }
175
- `,document.head.appendChild(e)})();const aC="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",iC="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",lC="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",cC="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",uC="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",dC="https://agent.opentiny.design/tiny-robot",y2="https://ai.opentiny.design/next-remoter",w2=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:cC},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:aC},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:lC},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:iC}];class pC{constructor(t){if(this.isExpanded=!1,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 sC(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||y2,remoteUrl:t.remoteUrl||dC},this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?w2(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}):w2(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=`
177
+ `,document.head.appendChild(e)})();const kR="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",ER="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",TR="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",IR="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",RR="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",xR="https://agent.opentiny.design/tiny-robot",f_="https://ai.opentiny.design/next-remoter",m_=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:IR},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:kR},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:TR},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:ER}];class PR{constructor(t){if(this.isExpanded=!1,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 CR(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||f_,remoteUrl:t.remoteUrl||xR},this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?m_(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}):m_(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=`
176
178
  <div class="tiny-remoter-floating-block__icon">
177
- <img style="display: block; width: 56px;" src="${y2}/svgs/logo-next-no-bg-left.svg" alt="icon" />
179
+ <img style="display: block; width: 56px;" src="${f_}/svgs/logo-next-no-bg-left.svg" alt="icon" />
178
180
  </div>
179
181
  `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(r=>r.show!==!1).map(r=>`
180
182
  <div class="tiny-remoter-dropdown-item" data-action="${r.action}">
@@ -187,14 +189,14 @@ Minimum version required to store current data is: `+P+`.
187
189
  <div>
188
190
  ${r.showCopyIcon?`
189
191
  <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
190
- <img src="${uC}"/>
192
+ <img src="${RR}"/>
191
193
  </div>
192
194
  `:""}
193
195
  </div>
194
196
  </div>
195
197
  </div>
196
198
  </div>
197
- `).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.toggleDropdown()}),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()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const 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 v2((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
199
+ `).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.toggleDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const i=n.dataset.action;i&&this.handleAction(i);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()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const 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 p_((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
198
200
  <div style="text-align: center; padding: 32px;">
199
201
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
200
202
  <div style="
@@ -620,4 +622,4 @@ Minimum version required to store current data is: `+P+`.
620
622
  color: white;
621
623
  }
622
624
  }
623
- `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const fC=(e={})=>new pC(e);Jt.AgentModelProvider=AS,Jt.QrCode=v2,Jt.createRemoter=fC,Jt.getAISDKTools=qm,Object.defineProperty(Jt,Symbol.toStringTag,{value:"Module"})}));
625
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const OR=(e={})=>new PR(e);rr.AgentModelProvider=eR,rr.QrCode=p_,rr.createRemoter=OR,rr.getAISDKTools=P1,Object.defineProperty(rr,Symbol.toStringTag,{value:"Module"})}));