@opentiny/next-sdk 0.2.3 → 0.2.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,41 +1,41 @@
1
- (function(Ht,zr){typeof exports=="object"&&typeof module<"u"?zr(exports):typeof define=="function"&&define.amd?define(["exports"],zr):(Ht=typeof globalThis<"u"?globalThis:Ht||self,zr(Ht.WebAgent={}))})(this,(function(Ht){"use strict";var zr="vercel.ai.error",x1=Symbol.for(zr),Sc,R1=class $1 extends Error{constructor({name:t,message:r,cause:n}){super(r),this[Sc]=!0,this.name=t,this.cause=n}static isInstance(t){return $1.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}};Sc=x1;var he=R1,kc="AI_APICallError",Cc=`vercel.ai.error.${kc}`,P1=Symbol.for(Cc),$c,et=class extends he{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:kc,message:t,cause:a}),this[$c]=!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 he.hasMarker(t,Cc)}};$c=P1;var Ec="AI_EmptyResponseBodyError",Tc=`vercel.ai.error.${Ec}`,O1=Symbol.for(Tc),Ic,M1=class extends he{constructor({message:t="Empty response body"}={}){super({name:Ec,message:t}),this[Ic]=!0}static isInstance(t){return he.hasMarker(t,Tc)}};Ic=O1;function Zr(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var xc="AI_InvalidArgumentError",Rc=`vercel.ai.error.${xc}`,N1=Symbol.for(Rc),Pc,Oc=class extends he{constructor({message:t,cause:r,argument:n}){super({name:xc,message:t,cause:r}),this[Pc]=!0,this.argument=n}static isInstance(t){return he.hasMarker(t,Rc)}};Pc=N1;var Mc="AI_InvalidPromptError",Nc=`vercel.ai.error.${Mc}`,A1=Symbol.for(Nc),Ac,Fr=class extends he{constructor({prompt:t,message:r,cause:n}){super({name:Mc,message:`Invalid prompt: ${r}`,cause:n}),this[Ac]=!0,this.prompt=t}static isInstance(t){return he.hasMarker(t,Nc)}};Ac=A1;var qc="AI_InvalidResponseDataError",Lc=`vercel.ai.error.${qc}`,q1=Symbol.for(Lc),jc,Uc=class extends he{constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:qc,message:r}),this[jc]=!0,this.data=t}static isInstance(t){return he.hasMarker(t,Lc)}};jc=q1;var Dc="AI_JSONParseError",zc=`vercel.ai.error.${Dc}`,L1=Symbol.for(zc),Zc,fo=class extends he{constructor({text:t,cause:r}){super({name:Dc,message:`JSON parsing failed: Text: ${t}.
2
- Error message: ${Zr(r)}`,cause:r}),this[Zc]=!0,this.text=t}static isInstance(t){return he.hasMarker(t,zc)}};Zc=L1;var Fc="AI_LoadAPIKeyError",Vc=`vercel.ai.error.${Fc}`,j1=Symbol.for(Vc),Bc,ho=class extends he{constructor({message:t}){super({name:Fc,message:t}),this[Bc]=!0}static isInstance(t){return he.hasMarker(t,Vc)}};Bc=j1;var Hc="AI_NoSuchModelError",Jc=`vercel.ai.error.${Hc}`,U1=Symbol.for(Jc),Gc,Wc=class extends he{constructor({errorName:e=Hc,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[Gc]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return he.hasMarker(e,Jc)}};Gc=U1;var Kc="AI_TypeValidationError",Yc=`vercel.ai.error.${Kc}`,D1=Symbol.for(Yc),Qc,z1=class wc extends he{constructor({value:t,cause:r}){super({name:Kc,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
- Error message: ${Zr(r)}`,cause:r}),this[Qc]=!0,this.value=t}static isInstance(t){return he.hasMarker(t,Yc)}static wrap({value:t,cause:r}){return wc.isInstance(r)&&r.value===t?r:new wc({value:t,cause:r})}};Qc=D1;var vn=z1,Xc="AI_UnsupportedFunctionalityError",eu=`vercel.ai.error.${Xc}`,Z1=Symbol.for(eu),tu,ru=class extends he{constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:Xc,message:r}),this[tu]=!0,this.functionality=t}static isInstance(t){return he.hasMarker(t,eu)}};tu=Z1;class nu 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 ga(e){}function ou(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=ga,onError:r=ga,onRetry:n=ga,onComment:o}=e;let s="",i=!0,a,l="",c="";function u(v){const m=i?v.replace(/^\xEF\xBB\xBF/,""):v,[w,g]=F1(`${s}${m}`);for(const y of w)_(y);s=g,i=!1}function _(v){if(v===""){d();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const m=v.indexOf(":");if(m!==-1){const w=v.slice(0,m),g=v[m+1]===" "?2:1,y=v.slice(m+g);f(w,y,v);return}f(v,"",v)}function f(v,m,w){switch(v){case"event":c=m;break;case"data":l=`${l}${m}
4
- `;break;case"id":a=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):r(new nu(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:w}));break;default:r(new nu(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:m,line:w}));break}}function d(){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 p(v={}){s&&v.consume&&_(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:p}}function F1(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 Vr extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=ou({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 su=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 wn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const au={};function ar(e){return au}function iu(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 V1(e,t){return typeof t=="bigint"?t.toString():t}function _a(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ya(e){return e==null}function va(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function B1(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 Ee(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 mo(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function bn(e){return JSON.stringify(e)}const lu=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function go(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const H1=_a(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function _o(e){if(go(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(go(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const J1=new Set(["string","number","symbol"]);function Sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function br(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function te(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 G1(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const W1={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 K1(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 br(e,{...e._zod.def,shape:r,checks:[]})}function Y1(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 br(e,{...e._zod.def,shape:r,checks:[]})}function Q1(e,t){if(!_o(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 mo(this,"shape",n),n},checks:[]};return br(e,r)}function X1(e,t){return br(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return mo(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 br(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 br(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 yo(e){return typeof e=="string"?e:e?.message}function ir(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=yo(e.inst?._zod.def?.error?.(e))??yo(t?.error?.(e))??yo(r.customError?.(e))??yo(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function wa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Cn(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const cu=(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,V1,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},uu=J("$ZodError",cu),du=J("$ZodError",cu,{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 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 og=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 wn;if(i.issues.length){const a=new(o?.Err??e)(i.issues.map(l=>ir(l,s,ar())));throw lu(a,o?.callee),a}return i.value},sg=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=>ir(l,s,ar())));throw lu(a,o?.callee),a}return i.value},pu=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 wn;return s.issues.length?{success:!1,error:new(e??uu)(s.issues.map(i=>ir(i,o,ar())))}:{success:!0,data:s.value}},fu=pu(du),hu=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=>ir(i,o,ar())))}:{success:!0,data:s.value}},ag=hu(du),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})$/,mu=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 _g(){return new RegExp(gg,"u")}const yg=/^(?:(?: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])$/,vg=/^(([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])$/,Sg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gu=/^[A-Za-z0-9_-]*$/,kg=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Cg=/^\+(?:[0-9]){6,14}[0-9]$/,_u="(?:(?:\\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])))",$g=new RegExp(`^${_u}$`);function yu(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 Eg(e){return new RegExp(`^${yu(e)}$`)}function Tg(e){const t=yu({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(`^${_u}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]*$/,lt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),vu={number:"number",bigint:"bigint",object:"date"},wu=J("$ZodCheckLessThan",(e,t)=>{lt.init(e,t);const r=vu[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})}}),bu=J("$ZodCheckGreaterThan",(e,t)=>{lt.init(e,t);const r=vu[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)=>{lt.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):B1(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)=>{lt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=W1[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=xg)}),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})}}),Lg=J("$ZodCheckMaxLength",(e,t)=>{var r;lt.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=wa(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),jg=J("$ZodCheckMinLength",(e,t)=>{var r;lt.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=wa(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ug=J("$ZodCheckLengthEquals",(e,t)=>{var r;lt.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=wa(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})}}),vo=J("$ZodCheckStringFormat",(e,t)=>{var r,n;lt.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=()=>{})}),Dg=J("$ZodCheckRegex",(e,t)=>{vo.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})}}),zg=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Mg),vo.init(e,t)}),Zg=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ng),vo.init(e,t)}),Fg=J("$ZodCheckIncludes",(e,t)=>{lt.init(e,t);const r=Sn(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)=>{lt.init(e,t);const r=new RegExp(`^${Sn(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})}}),Bg=J("$ZodCheckEndsWith",(e,t)=>{lt.init(e,t);const r=new RegExp(`.*${Sn(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})}}),Hg=J("$ZodCheckOverwrite",(e,t)=>{lt.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(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 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,i,a)=>{let l=kn(s),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const _=s.issues.length,f=u._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new wn;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,s.issues.length!==_&&(l||(l=kn(s,_)))});else{if(s.issues.length===_)continue;l||(l=kn(s,_))}}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 wn;return a.then(l=>o(l,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{const s=fu(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ag(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ba=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}}),qe=J("$ZodStringFormat",(e,t)=>{vo.init(e,t),ba.init(e,t)}),Wg=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=hg),qe.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=mu(n))}else t.pattern??(t.pattern=mu());qe.init(e,t)}),Yg=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=mg),qe.init(e,t)}),Qg=J("$ZodURL",(e,t)=>{qe.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:kg.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=_g()),qe.init(e,t)}),e_=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pg),qe.init(e,t)}),t_=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ig),qe.init(e,t)}),r_=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=lg),qe.init(e,t)}),n_=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=cg),qe.init(e,t)}),o_=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ug),qe.init(e,t)}),s_=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=dg),qe.init(e,t)}),a_=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Tg(t)),qe.init(e,t)}),i_=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=$g),qe.init(e,t)}),l_=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Eg(t)),qe.init(e,t)}),c_=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fg),qe.init(e,t)}),u_=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=yg),qe.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),d_=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vg),qe.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})}}}),p_=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=wg),qe.init(e,t)}),f_=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=bg),qe.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 Su(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const h_=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Sg),qe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Su(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function m_(e){if(!gu.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Su(r)}const g_=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=gu),qe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{m_(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),__=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Cg),qe.init(e,t)});function y_(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 v_=J("$ZodJWT",(e,t)=>{qe.init(e,t),e._zod.check=r=>{y_(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),ku=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}}),w_=J("$ZodNumber",(e,t)=>{qg.init(e,t),ku.init(e,t)}),b_=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}}),S_=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}}),k_=J("$ZodAny",(e,t)=>{Oe.init(e,t),e._zod.parse=r=>r}),C_=J("$ZodUnknown",(e,t)=>{Oe.init(e,t),e._zod.parse=r=>r}),$_=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 E_=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 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=>Cu(c,r,i))):Cu(l,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function wo(e,t,r){e.issues.length&&t.issues.push(...Sr(r,e.issues)),t.value[r]=e.value}function $u(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 T_=J("$ZodObject",(e,t)=>{Oe.init(e,t);const r=_a(()=>{const _=Object.keys(t.shape);for(const d of _)if(!(t.shape[d]instanceof Oe))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const f=G1(t.shape);return{shape:t.shape,keys:_,keySet:new Set(_),numKeys:_.length,optionalKeys:new Set(f)}});Ee(e._zod,"propValues",()=>{const _=t.shape,f={};for(const d in _){const p=_[d]._zod;if(p.values){f[d]??(f[d]=new Set);for(const v of p.values)f[d].add(v)}}return f});const n=_=>{const f=new Jg(["shape","payload","ctx"]),d=r.value,p=g=>{const y=bn(g);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};f.write("const input = payload.value;");const v=Object.create(null);let m=0;for(const g of d.keys)v[g]=`key_${m++}`;f.write("const newResult = {}");for(const g of d.keys)if(d.optionalKeys.has(g)){const y=v[g];f.write(`const ${y} = ${p(g)};`);const b=bn(g);f.write(`
10
- if (${y}.issues.length) {
11
- if (input[${b}] === undefined) {
12
- if (${b} in input) {
13
- newResult[${b}] = undefined;
1
+ (function($r,Dn){typeof exports=="object"&&typeof module<"u"?Dn(exports):typeof define=="function"&&define.amd?define(["exports"],Dn):($r=typeof globalThis<"u"?globalThis:$r||self,Dn($r.WebAgent={}))})(this,(function($r){"use strict";var Dn="vercel.ai.error",Q_=Symbol.for(Dn),Qu,Xu,me=class J_ extends(Xu=Error,Qu=Q_,Xu){constructor({name:t,message:r,cause:n}){super(r),this[Qu]=!0,this.name=t,this.cause=n}static isInstance(t){return J_.hasMarker(t,Dn)}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}},ed="AI_APICallError",td=`vercel.ai.error.${ed}`,X_=Symbol.for(td),rd,nd,st=class extends(nd=me,rd=X_,nd){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:ed,message:t,cause:i}),this[rd]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return me.hasMarker(t,td)}},od="AI_EmptyResponseBodyError",sd=`vercel.ai.error.${od}`,ev=Symbol.for(sd),ad,id,tv=class extends(id=me,ad=ev,id){constructor({message:t="Empty response body"}={}){super({name:od,message:t}),this[ad]=!0}static isInstance(t){return me.hasMarker(t,sd)}};function hn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var ld="AI_InvalidArgumentError",cd=`vercel.ai.error.${ld}`,rv=Symbol.for(cd),ud,dd,pd=class extends(dd=me,ud=rv,dd){constructor({message:t,cause:r,argument:n}){super({name:ld,message:t,cause:r}),this[ud]=!0,this.argument=n}static isInstance(t){return me.hasMarker(t,cd)}},fd="AI_InvalidPromptError",hd=`vercel.ai.error.${fd}`,nv=Symbol.for(hd),md,gd,mn=class extends(gd=me,md=nv,gd){constructor({prompt:e,message:t,cause:r}){super({name:fd,message:`Invalid prompt: ${t}`,cause:r}),this[md]=!0,this.prompt=e}static isInstance(e){return me.hasMarker(e,hd)}},yd="AI_InvalidResponseDataError",_d=`vercel.ai.error.${yd}`,ov=Symbol.for(_d),vd,wd,ji=class extends(wd=me,vd=ov,wd){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:yd,message:r}),this[vd]=!0,this.data=t}static isInstance(t){return me.hasMarker(t,_d)}},bd="AI_JSONParseError",kd=`vercel.ai.error.${bd}`,sv=Symbol.for(kd),Cd,Td,Ss=class extends(Td=me,Cd=sv,Td){constructor({text:t,cause:r}){super({name:bd,message:`JSON parsing failed: Text: ${t}.
2
+ Error message: ${hn(r)}`,cause:r}),this[Cd]=!0,this.text=t}static isInstance(t){return me.hasMarker(t,kd)}},Sd="AI_LoadAPIKeyError",Id=`vercel.ai.error.${Sd}`,av=Symbol.for(Id),xd,Ed,Is=class extends(Ed=me,xd=av,Ed){constructor({message:t}){super({name:Sd,message:t}),this[xd]=!0}static isInstance(t){return me.hasMarker(t,Id)}},$d="AI_TooManyEmbeddingValuesForCallError",Rd=`vercel.ai.error.${$d}`,iv=Symbol.for(Rd),Pd,Nd,lv=class extends(Nd=me,Pd=iv,Nd){constructor(e){super({name:$d,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[Pd]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return me.hasMarker(e,Rd)}},Md="AI_TypeValidationError",Od=`vercel.ai.error.${Md}`,cv=Symbol.for(Od),Ad,qd,gn=class Ku extends(qd=me,Ad=cv,qd){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:Md,message:`${o}: Value: ${JSON.stringify(t)}.
3
+ Error message: ${hn(r)}`,cause:r}),this[Ad]=!0,this.value=t,this.context=n}static isInstance(t){return me.hasMarker(t,Od)}static wrap({value:t,cause:r,context:n}){var o,s,a;return Ku.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((s=r.context)==null?void 0:s.entityName)===n?.entityName&&((a=r.context)==null?void 0:a.entityId)===n?.entityId?r:new Ku({value:t,cause:r,context:n})}},Ld="AI_UnsupportedFunctionalityError",jd=`vercel.ai.error.${Ld}`,uv=Symbol.for(jd),Dd,Ud,vr=class extends(Ud=me,Dd=uv,Ud){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:Ld,message:r}),this[Dd]=!0,this.functionality=t}static isInstance(t){return me.hasMarker(t,jd)}};const zd=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 vo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Fd={};function Hr(e){return Fd}function Vd(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 dv(e,t){return typeof t=="bigint"?t.toString():t}function Di(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ui(e){return e==null}function zi(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function pv(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function Fe(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function xs(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function wo(e){return JSON.stringify(e)}const Zd=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Es(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const fv=Di(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function $s(e){if(Es(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Es(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const hv=new Set(["string","number","symbol"]);function bo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function de(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function mv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const gv={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 yv(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 yn(e,{...e._zod.def,shape:r,checks:[]})}function _v(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 yn(e,{...e._zod.def,shape:r,checks:[]})}function vv(e,t){if(!$s(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 xs(this,"shape",n),n},checks:[]};return yn(e,r)}function wv(e,t){return yn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return xs(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function bv(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 yn(t,{...t._zod.def,shape:o,checks:[]})}function kv(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 yn(t,{...t._zod.def,shape:o,checks:[]})}function ko(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _n(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Rs(e){return typeof e=="string"?e:e?.message}function Jr(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Rs(e.inst?._zod.def?.error?.(e))??Rs(t?.error?.(e))??Rs(r.customError?.(e))??Rs(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Fi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Co(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Bd=(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,dv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Hd=J("$ZodError",Bd),Jd=J("$ZodError",Bd,{Parent:Error});function Cv(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 Tv(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 Sv=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 vo;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>Jr(l,s,Hr())));throw Zd(i,o?.callee),i}return a.value},Iv=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=>Jr(l,s,Hr())));throw Zd(i,o?.callee),i}return a.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 vo;return s.issues.length?{success:!1,error:new(e??Hd)(s.issues.map(a=>Jr(a,o,Hr())))}:{success:!0,data:s.value}},Wd=Gd(Jd),Kd=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=>Jr(a,o,Hr())))}:{success:!0,data:s.value}},xv=Kd(Jd),Ev=/^[cC][^\s-]{8,}$/,$v=/^[0-9a-z]+$/,Rv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Pv=/^[0-9a-vA-V]{20}$/,Nv=/^[A-Za-z0-9]{27}$/,Mv=/^[a-zA-Z0-9_-]{21}$/,Ov=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Av=/^([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})$/,Yd=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)$/,qv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Lv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function jv(){return new RegExp(Lv,"u")}const Dv=/^(?:(?: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])$/,Uv=/^(([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})$/,zv=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Fv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(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}=))?$/,Qd=/^[A-Za-z0-9_-]*$/,Zv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Bv=/^\+(?:[0-9]){6,14}[0-9]$/,Xd="(?:(?:\\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])))",Hv=new RegExp(`^${Xd}$`);function ep(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 Jv(e){return new RegExp(`^${ep(e)}$`)}function Gv(e){const t=ep({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(`^${Xd}T(?:${n})$`)}const Wv=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Kv=/^\d+$/,Yv=/^-?\d+(?:\.\d+)?/i,Qv=/true|false/i,Xv=/null/i,e1=/^[^A-Z]*$/,t1=/^[^a-z]*$/,jt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tp={number:"number",bigint:"bigint",object:"date"},rp=J("$ZodCheckLessThan",(e,t)=>{jt.init(e,t);const r=tp[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})}}),np=J("$ZodCheckGreaterThan",(e,t)=>{jt.init(e,t);const r=tp[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})}}),r1=J("$ZodCheckMultipleOf",(e,t)=>{jt.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):pv(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})}}),n1=J("$ZodCheckNumberFormat",(e,t)=>{jt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=gv[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=Kv)}),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})}}),o1=J("$ZodCheckMaxLength",(e,t)=>{var r;jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ui(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=Fi(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),s1=J("$ZodCheckMinLength",(e,t)=>{var r;jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ui(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=Fi(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),a1=J("$ZodCheckLengthEquals",(e,t)=>{var r;jt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ui(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=Fi(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})}}),Ps=J("$ZodCheckStringFormat",(e,t)=>{var r,n;jt.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=()=>{})}),i1=J("$ZodCheckRegex",(e,t)=>{Ps.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})}}),l1=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=e1),Ps.init(e,t)}),c1=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=t1),Ps.init(e,t)}),u1=J("$ZodCheckIncludes",(e,t)=>{jt.init(e,t);const r=bo(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})}}),d1=J("$ZodCheckStartsWith",(e,t)=>{jt.init(e,t);const r=new RegExp(`^${bo(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})}}),p1=J("$ZodCheckEndsWith",(e,t)=>{jt.init(e,t);const r=new RegExp(`.*${bo(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})}}),f1=J("$ZodCheckOverwrite",(e,t)=>{jt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class h1{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
4
+ `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
5
+ `))}}const m1={major:4,minor:0,patch:0},Ge=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=m1;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=ko(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const m=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&i?.async===!1)throw new vo;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==m&&(l||(l=ko(s,m)))});else{if(s.issues.length===m)continue;l||(l=ko(s,m))}}return c?c.then(()=>s):s};e._zod.run=(s,a)=>{const i=e._zod.parse(s,a);if(i instanceof Promise){if(a.async===!1)throw new vo;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=Wd(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return xv(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Vi=J("$ZodString",(e,t)=>{Ge.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Wv(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}}),tt=J("$ZodStringFormat",(e,t)=>{Ps.init(e,t),Vi.init(e,t)}),g1=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Av),tt.init(e,t)}),y1=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=Yd(n))}else t.pattern??(t.pattern=Yd());tt.init(e,t)}),_1=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=qv),tt.init(e,t)}),v1=J("$ZodURL",(e,t)=>{tt.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:Zv.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})}}}),w1=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=jv()),tt.init(e,t)}),b1=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Mv),tt.init(e,t)}),k1=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ev),tt.init(e,t)}),C1=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=$v),tt.init(e,t)}),T1=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Rv),tt.init(e,t)}),S1=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Pv),tt.init(e,t)}),I1=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Nv),tt.init(e,t)}),x1=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Gv(t)),tt.init(e,t)}),E1=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Hv),tt.init(e,t)}),$1=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Jv(t)),tt.init(e,t)}),R1=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ov),tt.init(e,t)}),P1=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Dv),tt.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),N1=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Uv),tt.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})}}}),M1=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=zv),tt.init(e,t)}),O1=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Fv),tt.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 op(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const A1=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Vv),tt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{op(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function q1(e){if(!Qd.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return op(r)}const L1=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Qd),tt.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{q1(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),j1=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Bv),tt.init(e,t)});function D1(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 U1=J("$ZodJWT",(e,t)=>{tt.init(e,t),e._zod.check=r=>{D1(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),sp=J("$ZodNumber",(e,t)=>{Ge.init(e,t),e._zod.pattern=e._zod.bag.pattern??Yv,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}}),z1=J("$ZodNumber",(e,t)=>{n1.init(e,t),sp.init(e,t)}),F1=J("$ZodBoolean",(e,t)=>{Ge.init(e,t),e._zod.pattern=Qv,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}}),V1=J("$ZodNull",(e,t)=>{Ge.init(e,t),e._zod.pattern=Xv,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}}),Z1=J("$ZodAny",(e,t)=>{Ge.init(e,t),e._zod.parse=r=>r}),B1=J("$ZodUnknown",(e,t)=>{Ge.init(e,t),e._zod.parse=r=>r}),H1=J("$ZodNever",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function ap(e,t,r){e.issues.length&&t.issues.push(..._n(r,e.issues)),t.value[r]=e.value}const J1=J("$ZodArray",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const i=o[a],l=t.element._zod.run({value:i,issues:[]},n);l instanceof Promise?s.push(l.then(c=>ap(c,r,a))):ap(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Ns(e,t,r){e.issues.length&&t.issues.push(..._n(r,e.issues)),t.value[r]=e.value}function ip(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(..._n(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const G1=J("$ZodObject",(e,t)=>{Ge.init(e,t);const r=Di(()=>{const m=Object.keys(t.shape);for(const f of m)if(!(t.shape[f]instanceof Ge))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const p=mv(t.shape);return{shape:t.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set(p)}});Fe(e._zod,"propValues",()=>{const m=t.shape,p={};for(const f in m){const g=m[f]._zod;if(g.values){p[f]??(p[f]=new Set);for(const v of g.values)p[f].add(v)}}return p});const n=m=>{const p=new h1(["shape","payload","ctx"]),f=r.value,g=_=>{const h=wo(_);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const _ of f.keys)v[_]=`key_${y++}`;p.write("const newResult = {}");for(const _ of f.keys)if(f.optionalKeys.has(_)){const h=v[_];p.write(`const ${h} = ${g(_)};`);const S=wo(_);p.write(`
6
+ if (${h}.issues.length) {
7
+ if (input[${S}] === undefined) {
8
+ if (${S} in input) {
9
+ newResult[${S}] = undefined;
14
10
  }
15
11
  } else {
16
12
  payload.issues = payload.issues.concat(
17
- ${y}.issues.map((iss) => ({
13
+ ${h}.issues.map((iss) => ({
18
14
  ...iss,
19
- path: iss.path ? [${b}, ...iss.path] : [${b}],
15
+ path: iss.path ? [${S}, ...iss.path] : [${S}],
20
16
  }))
21
17
  );
22
18
  }
23
- } else if (${y}.value === undefined) {
24
- if (${b} in input) newResult[${b}] = undefined;
19
+ } else if (${h}.value === undefined) {
20
+ if (${S} in input) newResult[${S}] = undefined;
25
21
  } else {
26
- newResult[${b}] = ${y}.value;
22
+ newResult[${S}] = ${h}.value;
27
23
  }
28
- `)}else{const y=v[g];f.write(`const ${y} = ${p(g)};`),f.write(`
29
- if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
24
+ `)}else{const h=v[_];p.write(`const ${h} = ${g(_)};`),p.write(`
25
+ if (${h}.issues.length) payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
30
26
  ...iss,
31
- path: iss.path ? [${bn(g)}, ...iss.path] : [${bn(g)}]
32
- })));`),f.write(`newResult[${bn(g)}] = ${y}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");const w=f.compile();return(g,y)=>w(_,g,y)};let o;const s=go,i=!au.jitless,l=i&&H1.value,c=t.catchall;let u;e._zod.parse=(_,f)=>{u??(u=r.value);const d=_.value;if(!s(d))return _.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),_;const p=[];if(i&&l&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),_=o(_,f);else{_.value={};const y=u.shape;for(const b of u.keys){const S=y[b],k=S._zod.run({value:d[b],issues:[]},f),C=S._zod.optin==="optional"&&S._zod.optout==="optional";k instanceof Promise?p.push(k.then(I=>C?$u(I,_,b,d):wo(I,_,b))):C?$u(k,_,b,d):wo(k,_,b)}}if(!c)return p.length?Promise.all(p).then(()=>_):_;const v=[],m=u.keySet,w=c._zod,g=w.def.type;for(const y of Object.keys(d)){if(m.has(y))continue;if(g==="never"){v.push(y);continue}const b=w.run({value:d[y],issues:[]},f);b instanceof Promise?p.push(b.then(S=>wo(S,_,y))):wo(b,_,y)}return v.length&&_.issues.push({code:"unrecognized_keys",keys:v,input:d,inst:e}),p.length?Promise.all(p).then(()=>_):_}});function Eu(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=>ir(s,n,ar())))}),t}const Tu=J("$ZodUnion",(e,t)=>{Oe.init(e,t),Ee(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ee(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ee(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Ee(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=>va(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=>Eu(i,r,e,n)):Eu(s,r,e,n)}}),I_=J("$ZodDiscriminatedUnion",(e,t)=>{Tu.init(e,t);const r=e._zod.parse;Ee(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=_a(()=>{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(!go(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)}}),x_=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),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>Iu(r,l,c)):Iu(r,s,i)}});function Sa(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(_o(e)&&_o(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=Sa(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=Sa(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 Iu(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=Sa(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 R_=J("$ZodRecord",(e,t)=>{Oe.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!_o(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(...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 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=>ir(c,n,ar())),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(...Sr(i,c.issues)),r.value[a.value]=c.value})):(l.issues.length&&r.issues.push(...Sr(i,l.issues)),r.value[a.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),P_=J("$ZodEnum",(e,t)=>{Oe.init(e,t);const r=iu(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>J1.has(typeof n)).map(n=>typeof n=="string"?Sn(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}}),O_=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"?Sn(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}}),M_=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(i=>(r.value=i,r));if(o instanceof Promise)throw new wn;return r.value=o,r}}),N_=J("$ZodOptional",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ee(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ee(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${va(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)}),A_=J("$ZodNullable",(e,t)=>{Oe.init(e,t),Ee(e._zod,"optin",()=>t.innerType._zod.optin),Ee(e._zod,"optout",()=>t.innerType._zod.optout),Ee(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${va(r.source)}|null)$`):void 0}),Ee(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)}),q_=J("$ZodDefault",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Ee(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=>xu(s,t)):xu(o,t)}});function xu(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const L_=J("$ZodPrefault",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Ee(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))}),j_=J("$ZodNonOptional",(e,t)=>{Oe.init(e,t),Ee(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=>Ru(s,e)):Ru(o,e)}});function Ru(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 U_=J("$ZodCatch",(e,t)=>{Oe.init(e,t),e._zod.optin="optional",Ee(e._zod,"optout",()=>t.innerType._zod.optout),Ee(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=>ir(i,n,ar()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>ir(s,n,ar()))},input:r.value}),r.issues=[]),r)}}),D_=J("$ZodPipe",(e,t)=>{Oe.init(e,t),Ee(e._zod,"values",()=>t.in._zod.values),Ee(e._zod,"optin",()=>t.in._zod.optin),Ee(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=>Pu(s,t,n)):Pu(o,t,n)}});function Pu(e,t,r){return kn(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const z_=J("$ZodReadonly",(e,t)=>{Oe.init(e,t),Ee(e._zod,"propValues",()=>t.innerType._zod.propValues),Ee(e._zod,"values",()=>t.innerType._zod.values),Ee(e._zod,"optin",()=>t.innerType._zod.optin),Ee(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(Ou):Ou(o)}});function Ou(e){return e.value=Object.freeze(e.value),e}const Z_=J("$ZodLazy",(e,t)=>{Oe.init(e,t),Ee(e._zod,"innerType",()=>t.getter()),Ee(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Ee(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Ee(e._zod,"optin",()=>e._zod.innerType._zod.optin),Ee(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),F_=J("$ZodCustom",(e,t)=>{lt.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=>Mu(s,r,n,e));Mu(o,r,n,e)}});function Mu(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(Cn(o))}}class Nu{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 V_(){return new Nu}const $n=V_();function B_(e,t){return new e({type:"string",...te(t)})}function H_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...te(t)})}function Au(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...te(t)})}function J_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...te(t)})}function G_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...te(t)})}function W_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...te(t)})}function K_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...te(t)})}function qu(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...te(t)})}function Y_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...te(t)})}function Q_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...te(t)})}function X_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...te(t)})}function ey(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...te(t)})}function ty(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...te(t)})}function ry(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...te(t)})}function ny(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...te(t)})}function oy(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...te(t)})}function sy(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...te(t)})}function ay(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...te(t)})}function iy(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...te(t)})}function Lu(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...te(t)})}function ly(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...te(t)})}function cy(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...te(t)})}function uy(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...te(t)})}function dy(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...te(t)})}function py(e,t){return new e({type:"string",format:"date",check:"string_format",...te(t)})}function fy(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...te(t)})}function hy(e,t){return new e({type:"string",format:"duration",check:"string_format",...te(t)})}function my(e,t){return new e({type:"number",checks:[],...te(t)})}function gy(e,t){return new e({type:"number",coerce:!0,checks:[],...te(t)})}function _y(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...te(t)})}function yy(e,t){return new e({type:"boolean",...te(t)})}function vy(e,t){return new e({type:"null",...te(t)})}function wy(e){return new e({type:"any"})}function by(e){return new e({type:"unknown"})}function Sy(e,t){return new e({type:"never",...te(t)})}function ju(e,t){return new wu({check:"less_than",...te(t),value:e,inclusive:!1})}function ka(e,t){return new wu({check:"less_than",...te(t),value:e,inclusive:!0})}function Uu(e,t){return new bu({check:"greater_than",...te(t),value:e,inclusive:!1})}function Ca(e,t){return new bu({check:"greater_than",...te(t),value:e,inclusive:!0})}function Du(e,t){return new Ag({check:"multiple_of",...te(t),value:e})}function zu(e,t){return new Lg({check:"max_length",...te(t),maximum:e})}function bo(e,t){return new jg({check:"min_length",...te(t),minimum:e})}function Zu(e,t){return new Ug({check:"length_equals",...te(t),length:e})}function ky(e,t){return new Dg({check:"string_format",format:"regex",...te(t),pattern:e})}function Cy(e){return new zg({check:"string_format",format:"lowercase",...te(e)})}function $y(e){return new Zg({check:"string_format",format:"uppercase",...te(e)})}function Ey(e,t){return new Fg({check:"string_format",format:"includes",...te(t),includes:e})}function Ty(e,t){return new Vg({check:"string_format",format:"starts_with",...te(t),prefix:e})}function Iy(e,t){return new Bg({check:"string_format",format:"ends_with",...te(t),suffix:e})}function En(e){return new Hg({check:"overwrite",tx:e})}function xy(e){return En(t=>t.normalize(e))}function Ry(){return En(e=>e.trim())}function Py(){return En(e=>e.toLowerCase())}function Oy(){return En(e=>e.toUpperCase())}function My(e,t,r){return new e({type:"array",element:t,...te(r)})}function Ny(e,t,r){const n=te(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Ay(e,t,r){return new e({type:"custom",check:"custom",fn:t,...te(r)})}class Fu{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??$n,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 _={...r,schemaPath:[...r.schemaPath,t],path:r.path},f=t._zod.parent;if(f)a.ref=f,this.process(f,_),this.seen.get(f).isParent=!0;else{const d=a.schema;switch(o.type){case"string":{const p=d;p.type="string";const{minimum:v,maximum:m,format:w,patterns:g,contentEncoding:y}=t._zod.bag;if(typeof v=="number"&&(p.minLength=v),typeof m=="number"&&(p.maxLength=m),w&&(p.format=s[w]??w,p.format===""&&delete p.format),y&&(p.contentEncoding=y),g&&g.size>0){const b=[...g];b.length===1?p.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 p=d,{minimum:v,maximum:m,format:w,multipleOf:g,exclusiveMaximum:y,exclusiveMinimum:b}=t._zod.bag;typeof w=="string"&&w.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof v=="number"&&(p.minimum=v,typeof b=="number"&&(b>=v?delete p.minimum:delete p.exclusiveMinimum)),typeof y=="number"&&(p.exclusiveMaximum=y),typeof m=="number"&&(p.maximum=m,typeof y=="number"&&(y<=m?delete p.maximum:delete p.exclusiveMaximum)),typeof g=="number"&&(p.multipleOf=g);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:v,maximum:m}=t._zod.bag;typeof v=="number"&&(p.minItems=v),typeof m=="number"&&(p.maxItems=m),p.type="array",p.items=this.process(o.element,{..._,path:[..._.path,"items"]});break}case"object":{const p=d;p.type="object",p.properties={};const v=o.shape;for(const g in v)p.properties[g]=this.process(v[g],{..._,path:[..._.path,"properties",g]});const m=new Set(Object.keys(v)),w=new Set([...m].filter(g=>{const y=o.shape[g]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));w.size>0&&(p.required=Array.from(w)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{..._,path:[..._.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=d;p.anyOf=o.options.map((v,m)=>this.process(v,{..._,path:[..._.path,"anyOf",m]}));break}case"intersection":{const p=d,v=this.process(o.left,{..._,path:[..._.path,"allOf",0]}),m=this.process(o.right,{..._,path:[..._.path,"allOf",1]}),w=y=>"allOf"in y&&Object.keys(y).length===1,g=[...w(v)?v.allOf:[v],...w(m)?m.allOf:[m]];p.allOf=g;break}case"tuple":{const p=d;p.type="array";const v=o.items.map((g,y)=>this.process(g,{..._,path:[..._.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?p.prefixItems=v:p.items=v,o.rest){const g=this.process(o.rest,{..._,path:[..._.path,"items"]});this.target==="draft-2020-12"?p.items=g:p.additionalItems=g}o.rest&&(p.items=this.process(o.rest,{..._,path:[..._.path,"items"]}));const{minimum:m,maximum:w}=t._zod.bag;typeof m=="number"&&(p.minItems=m),typeof w=="number"&&(p.maxItems=w);break}case"record":{const p=d;p.type="object",p.propertyNames=this.process(o.keyType,{..._,path:[..._.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{..._,path:[..._.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,v=iu(o.entries);v.every(m=>typeof m=="number")&&(p.type="number"),v.every(m=>typeof m=="string")&&(p.type="string"),p.enum=v;break}case"literal":{const p=d,v=[];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");v.push(Number(m))}else v.push(m);if(v.length!==0)if(v.length===1){const m=v[0];p.type=m===null?"null":typeof m,p.const=m}else v.every(m=>typeof m=="number")&&(p.type="number"),v.every(m=>typeof m=="string")&&(p.type="string"),v.every(m=>typeof m=="boolean")&&(p.type="string"),v.every(m=>m===null)&&(p.type="null"),p.enum=v;break}case"file":{const p=d,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:m,maximum:w,mime:g}=t._zod.bag;m!==void 0&&(v.minLength=m),w!==void 0&&(v.maxLength=w),g?g.length===1?(v.contentMediaType=g[0],Object.assign(p,v)):p.anyOf=g.map(y=>({...v,contentMediaType:y})):Object.assign(p,v);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,_);d.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,_),a.ref=o.innerType;break}case"success":{const p=d;p.type="boolean";break}case"default":{this.process(o.innerType,_),a.ref=o.innerType,d.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,_),a.ref=o.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,_),a.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,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=v.source;break}case"pipe":{const p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,_),a.ref=p;break}case"readonly":{this.process(o.innerType,_),a.ref=o.innerType,d.readOnly=!0;break}case"promise":{this.process(o.innerType,_),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,_),a.ref=o.innerType;break}case"lazy":{const p=t._zod.innerType;this.process(p,_),a.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(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 _=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,m=n.external.uri??(g=>g);if(v)return{ref:m(v)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${m("__shared")}#/${_}/${w}`}}if(u[1]===o)return{ref:"#"};const d=`#/${_}/`,p=u[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:d+p}},i=u=>{if(u[1].schema.$ref)return;const _=u[1],{ref:f,defId:d}=s(u);_.def={..._.schema},d&&(_.defId=d);const p=_.schema;for(const v in p)delete p[v];p.$ref=f};if(n.cycles==="throw")for(const u of this.seen.entries()){const _=u[1];if(_.cycle)throw new Error(`Cycle detected: #/${_.cycle?.join("/")}/<root>
33
-
34
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const _=u[1];if(t===u[0]){i(u);continue}if(n.external){const d=n.external.registry.get(u[0])?.id;if(t!==u[0]&&d){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(_.cycle){i(u);continue}if(_.count>1&&n.reused==="ref"){i(u);continue}}const a=(u,_)=>{const f=this.seen.get(u),d=f.def??f.schema,p={...d};if(f.ref===null)return;const v=f.ref;if(f.ref=null,v){a(v,_);const m=this.seen.get(v).schema;m.$ref&&_.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(m)):(Object.assign(d,m),Object.assign(d,p))}f.isParent||this.override({zodSchema:u,jsonSchema:d,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 _=u[1];_.def&&_.defId&&(c[_.defId]=_.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 Vu(e,t){if(e instanceof Nu){const n=new Fu(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 Fu(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 qy=J("ZodISODateTime",(e,t)=>{a_.init(e,t),je.init(e,t)});function Bu(e){return dy(qy,e)}const Ly=J("ZodISODate",(e,t)=>{i_.init(e,t),je.init(e,t)});function jy(e){return py(Ly,e)}const Uy=J("ZodISOTime",(e,t)=>{l_.init(e,t),je.init(e,t)});function Dy(e){return fy(Uy,e)}const zy=J("ZodISODuration",(e,t)=>{c_.init(e,t),je.init(e,t)});function Zy(e){return hy(zy,e)}const So=J("ZodError",(e,t)=>{uu.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}),Fy=og(So),Vy=sg(So),By=pu(So),$a=hu(So),Ne=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)=>br(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Fy(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>By(e,r,n),e.parseAsync=async(r,n)=>Vy(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(Av(r,n)),e.superRefine=r=>e.check(qv(r)),e.overwrite=r=>e.check(En(r)),e.optional=()=>ne(e),e.nullable=()=>rd(e),e.nullish=()=>ne(rd(e)),e.nonoptional=r=>Tv(e,r),e.array=()=>N(e),e.or=r=>re([e,r]),e.and=r=>Ia(e,r),e.transform=r=>Ra(e,ed(r)),e.default=r=>Cv(e,r),e.prefault=r=>Ev(e,r),e.catch=r=>xv(e,r),e.pipe=r=>Ra(e,r),e.readonly=()=>Ov(e),e.describe=r=>{const n=e.clone();return $n.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return $n.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return $n.get(e);const n=e.clone();return $n.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Hu=J("_ZodString",(e,t)=>{ba.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(ky(...n)),e.includes=(...n)=>e.check(Ey(...n)),e.startsWith=(...n)=>e.check(Ty(...n)),e.endsWith=(...n)=>e.check(Iy(...n)),e.min=(...n)=>e.check(bo(...n)),e.max=(...n)=>e.check(zu(...n)),e.length=(...n)=>e.check(Zu(...n)),e.nonempty=(...n)=>e.check(bo(1,...n)),e.lowercase=n=>e.check(Cy(n)),e.uppercase=n=>e.check($y(n)),e.trim=()=>e.check(Ry()),e.normalize=(...n)=>e.check(xy(...n)),e.toLowerCase=()=>e.check(Py()),e.toUpperCase=()=>e.check(Oy())}),Hy=J("ZodString",(e,t)=>{ba.init(e,t),Hu.init(e,t),e.email=r=>e.check(H_(Jy,r)),e.url=r=>e.check(qu(Gu,r)),e.jwt=r=>e.check(uy(lv,r)),e.emoji=r=>e.check(Y_(Wy,r)),e.guid=r=>e.check(Au(Ju,r)),e.uuid=r=>e.check(J_(ko,r)),e.uuidv4=r=>e.check(G_(ko,r)),e.uuidv6=r=>e.check(W_(ko,r)),e.uuidv7=r=>e.check(K_(ko,r)),e.nanoid=r=>e.check(Q_(Ky,r)),e.guid=r=>e.check(Au(Ju,r)),e.cuid=r=>e.check(X_(Yy,r)),e.cuid2=r=>e.check(ey(Qy,r)),e.ulid=r=>e.check(ty(Xy,r)),e.base64=r=>e.check(Lu(Wu,r)),e.base64url=r=>e.check(ly(av,r)),e.xid=r=>e.check(ry(ev,r)),e.ksuid=r=>e.check(ny(tv,r)),e.ipv4=r=>e.check(oy(rv,r)),e.ipv6=r=>e.check(sy(nv,r)),e.cidrv4=r=>e.check(ay(ov,r)),e.cidrv6=r=>e.check(iy(sv,r)),e.e164=r=>e.check(cy(iv,r)),e.datetime=r=>e.check(Bu(r)),e.date=r=>e.check(jy(r)),e.time=r=>e.check(Dy(r)),e.duration=r=>e.check(Zy(r))});function h(e){return B_(Hy,e)}const je=J("ZodStringFormat",(e,t)=>{qe.init(e,t),Hu.init(e,t)}),Jy=J("ZodEmail",(e,t)=>{Yg.init(e,t),je.init(e,t)}),Ju=J("ZodGUID",(e,t)=>{Wg.init(e,t),je.init(e,t)}),ko=J("ZodUUID",(e,t)=>{Kg.init(e,t),je.init(e,t)}),Gu=J("ZodURL",(e,t)=>{Qg.init(e,t),je.init(e,t)});function Gy(e){return qu(Gu,e)}const Wy=J("ZodEmoji",(e,t)=>{Xg.init(e,t),je.init(e,t)}),Ky=J("ZodNanoID",(e,t)=>{e_.init(e,t),je.init(e,t)}),Yy=J("ZodCUID",(e,t)=>{t_.init(e,t),je.init(e,t)}),Qy=J("ZodCUID2",(e,t)=>{r_.init(e,t),je.init(e,t)}),Xy=J("ZodULID",(e,t)=>{n_.init(e,t),je.init(e,t)}),ev=J("ZodXID",(e,t)=>{o_.init(e,t),je.init(e,t)}),tv=J("ZodKSUID",(e,t)=>{s_.init(e,t),je.init(e,t)}),rv=J("ZodIPv4",(e,t)=>{u_.init(e,t),je.init(e,t)}),nv=J("ZodIPv6",(e,t)=>{d_.init(e,t),je.init(e,t)}),ov=J("ZodCIDRv4",(e,t)=>{p_.init(e,t),je.init(e,t)}),sv=J("ZodCIDRv6",(e,t)=>{f_.init(e,t),je.init(e,t)}),Wu=J("ZodBase64",(e,t)=>{h_.init(e,t),je.init(e,t)});function Ku(e){return Lu(Wu,e)}const av=J("ZodBase64URL",(e,t)=>{g_.init(e,t),je.init(e,t)}),iv=J("ZodE164",(e,t)=>{__.init(e,t),je.init(e,t)}),lv=J("ZodJWT",(e,t)=>{v_.init(e,t),je.init(e,t)}),Ea=J("ZodNumber",(e,t)=>{ku.init(e,t),Ne.init(e,t),e.gt=(n,o)=>e.check(Uu(n,o)),e.gte=(n,o)=>e.check(Ca(n,o)),e.min=(n,o)=>e.check(Ca(n,o)),e.lt=(n,o)=>e.check(ju(n,o)),e.lte=(n,o)=>e.check(ka(n,o)),e.max=(n,o)=>e.check(ka(n,o)),e.int=n=>e.check(Yu(n)),e.safe=n=>e.check(Yu(n)),e.positive=n=>e.check(Uu(0,n)),e.nonnegative=n=>e.check(Ca(0,n)),e.negative=n=>e.check(ju(0,n)),e.nonpositive=n=>e.check(ka(0,n)),e.multipleOf=(n,o)=>e.check(Du(n,o)),e.step=(n,o)=>e.check(Du(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 my(Ea,e)}const cv=J("ZodNumberFormat",(e,t)=>{w_.init(e,t),Ea.init(e,t)});function Yu(e){return _y(cv,e)}const uv=J("ZodBoolean",(e,t)=>{b_.init(e,t),Ne.init(e,t)});function ce(e){return yy(uv,e)}const dv=J("ZodNull",(e,t)=>{S_.init(e,t),Ne.init(e,t)});function Ta(e){return vy(dv,e)}const pv=J("ZodAny",(e,t)=>{k_.init(e,t),Ne.init(e,t)});function tt(){return wy(pv)}const fv=J("ZodUnknown",(e,t)=>{C_.init(e,t),Ne.init(e,t)});function ke(){return by(fv)}const hv=J("ZodNever",(e,t)=>{$_.init(e,t),Ne.init(e,t)});function mv(e){return Sy(hv,e)}const gv=J("ZodArray",(e,t)=>{E_.init(e,t),Ne.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(bo(r,n)),e.nonempty=r=>e.check(bo(1,r)),e.max=(r,n)=>e.check(zu(r,n)),e.length=(r,n)=>e.check(Zu(r,n)),e.unwrap=()=>e.element});function N(e,t){return My(gv,e,t)}const Qu=J("ZodObject",(e,t)=>{T_.init(e,t),Ne.init(e,t),Ee(e,"shape",()=>t.shape),e.keyof=()=>be(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ke()}),e.loose=()=>e.clone({...e._zod.def,catchall:ke()}),e.strict=()=>e.clone({...e._zod.def,catchall:mv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Q1(e,r),e.merge=r=>X1(e,r),e.pick=r=>K1(e,r),e.omit=r=>Y1(e,r),e.partial=(...r)=>eg(td,e,r[0]),e.required=(...r)=>tg(nd,e,r[0])});function $(e,t){const r={type:"object",get shape(){return mo(this,"shape",{...e}),this.shape},...te(t)};return new Qu(r)}function Ue(e,t){return new Qu({type:"object",get shape(){return mo(this,"shape",{...e}),this.shape},catchall:ke(),...te(t)})}const Xu=J("ZodUnion",(e,t)=>{Tu.init(e,t),Ne.init(e,t),e.options=t.options});function re(e,t){return new Xu({type:"union",options:e,...te(t)})}const _v=J("ZodDiscriminatedUnion",(e,t)=>{Xu.init(e,t),I_.init(e,t)});function Ze(e,t,r){return new _v({type:"union",options:t,discriminator:e,...te(r)})}const yv=J("ZodIntersection",(e,t)=>{x_.init(e,t),Ne.init(e,t)});function Ia(e,t){return new yv({type:"intersection",left:e,right:t})}const vv=J("ZodRecord",(e,t)=>{R_.init(e,t),Ne.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function me(e,t,r){return new vv({type:"record",keyType:e,valueType:t,...te(r)})}const xa=J("ZodEnum",(e,t)=>{P_.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 xa({...t,checks:[],...te(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 xa({...t,checks:[],...te(o),entries:s})}});function be(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new xa({type:"enum",entries:r,...te(t)})}const wv=J("ZodLiteral",(e,t)=>{O_.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 q(e,t){return new wv({type:"literal",values:Array.isArray(e)?e:[e],...te(t)})}const bv=J("ZodTransform",(e,t)=>{M_.init(e,t),Ne.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Cn(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(Cn(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function ed(e){return new bv({type:"transform",transform:e})}const td=J("ZodOptional",(e,t)=>{N_.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ne(e){return new td({type:"optional",innerType:e})}const Sv=J("ZodNullable",(e,t)=>{A_.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function rd(e){return new Sv({type:"nullable",innerType:e})}const kv=J("ZodDefault",(e,t)=>{q_.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Cv(e,t){return new kv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const $v=J("ZodPrefault",(e,t)=>{L_.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ev(e,t){return new $v({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const nd=J("ZodNonOptional",(e,t)=>{j_.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Tv(e,t){return new nd({type:"nonoptional",innerType:e,...te(t)})}const Iv=J("ZodCatch",(e,t)=>{U_.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function xv(e,t){return new Iv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Rv=J("ZodPipe",(e,t)=>{D_.init(e,t),Ne.init(e,t),e.in=t.in,e.out=t.out});function Ra(e,t){return new Rv({type:"pipe",in:e,out:t})}const Pv=J("ZodReadonly",(e,t)=>{z_.init(e,t),Ne.init(e,t)});function Ov(e){return new Pv({type:"readonly",innerType:e})}const Mv=J("ZodLazy",(e,t)=>{Z_.init(e,t),Ne.init(e,t),e.unwrap=()=>e._zod.def.getter()});function od(e){return new Mv({type:"lazy",getter:e})}const Pa=J("ZodCustom",(e,t)=>{F_.init(e,t),Ne.init(e,t)});function Nv(e){const t=new lt({check:"custom"});return t._zod.check=e,t}function sd(e,t){return Ny(Pa,e??(()=>!0),t)}function Av(e,t={}){return Ay(Pa,e,t)}function qv(e){const t=Nv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Cn(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(Cn(o))}},e(r.value,r)));return t}function Co(e,t={error:`Input not instance of ${e.name}`}){const r=new Pa({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...te(t)});return r._zod.bag.Class=e,r}function ad(e,t){return Ra(ed(e),t)}const id={custom:"custom"};function ld(e){return gy(Ea,e)}var Y;(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"})(Y||(Y={}));function Br(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}async function Lv(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(cd());return}const s=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(s),r?.removeEventListener("abort",a)},a=()=>{i(),o(cd())};r?.addEventListener("abort",a)})}function cd(){return new DOMException("Delay was aborted","AbortError")}var $o=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 Tn(e){return Object.fromEntries([...e.headers])}var In=({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 Oc({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},xn=In();function Oa(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function kr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var jv=["fetch failed","failed to fetch"];function ud({error:e,url:t,requestBodyValues:r}){if(kr(e))return e;if(e instanceof TypeError&&jv.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 Rn(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 Uv(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 lr(e,...t){const r=new Headers(Uv(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var dd="3.0.18",Dv=()=>globalThis.fetch,pd=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=Dv()})=>{try{const i=await s(e,{method:"GET",headers:lr(t,`ai-sdk/provider-utils/${dd}`,Rn()),signal:o}),a=Tn(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw kr(c)||et.isInstance(c)?c:new et({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&&(kr(l)||et.isInstance(l))?l:new et({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}}catch(i){throw ud({error:i,url:e,requestBodyValues:{}})}};function zv({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 Zv({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ho({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ho({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 ho({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ho({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Eo({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 Fv=/"__proto__"\s*:/,Vv=/"constructor"\s*:/;function fd(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Fv.test(e)===!1&&Vv.test(e)===!1?t:Bv(t)}function Bv(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 Ma(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return fd(e)}try{return fd(e)}finally{Error.stackTraceLimit=t}}var To=Symbol.for("vercel.ai.validator");function Hv(e){return{[To]:!0,validate:e}}function Jv(e){return typeof e=="object"&&e!==null&&To in e&&e[To]===!0&&"validate"in e}function Hr(e){let t;return()=>(t==null&&(t=e()),t)}function Gv(e){return Jv(e)?e:typeof e=="function"?e():Wv(e)}function Wv(e){return Hv(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new vn({value:t,cause:r.issues})}})}async function Na({value:e,schema:t}){const r=await $t({value:e,schema:t});if(!r.success)throw vn.wrap({value:e,cause:r.error});return r.value}async function $t({value:e,schema:t}){const r=Gv(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:vn.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:vn.wrap({value:e,cause:n}),rawValue:e}}}async function Kv({text:e,schema:t}){try{const r=Ma(e);return t==null?r:Na({value:r,schema:t})}catch(r){throw fo.isInstance(r)||vn.isInstance(r)?r:new fo({text:e,cause:r})}}async function Cr({text:e,schema:t}){try{const r=Ma(e);return t==null?{success:!0,value:r,rawValue:r}:await $t({value:r,schema:t})}catch(r){return{success:!1,error:fo.isInstance(r)?r:new fo({text:e,cause:r}),rawValue:void 0}}}function hd(e){try{return Ma(e),!0}catch{return!1}}function Yv({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 Cr({text:r,schema:t}))}}))}async function md({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await $t({value:t[e],schema:r});if(!n.success)throw new Oc({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Qv=()=>globalThis.fetch,Jr=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Xv({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Xv=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=Qv()})=>{try{const a=await i(e,{method:"POST",headers:lr(t,`ai-sdk/provider-utils/${dd}`,Rn()),body:r.content,signal:s}),l=Tn(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw kr(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&&(kr(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 ud({error:a,url:e,requestBodyValues:r.values})}};function N$(e){return e}function gd(e){return{...e,type:"dynamic"}}async function jt(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 i=await n.text(),a=Tn(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 Kv({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)})}}},_d=e=>async({response:t})=>{const r=Tn(t);if(t.body==null)throw new M1({});return{responseHeaders:r,value:Yv({stream:t.body,schema:e})}},Gr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Cr({text:o,schema:e}),i=Tn(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}},ew=(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("/")},tw=Symbol("Let zodToJsonSchema decide on which parser to use"),yd={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"},rw=e=>typeof e=="string"?{...yd,name:e}:{...yd,...e};function ft(){return{}}function nw(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)!==Y.ZodAny&&(s.items=Te(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 ow(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 sw(){return{type:"boolean"}}function vd(e,t){return Te(e.type._def,t)}var aw=(e,t)=>Te(e.innerType._def,t);function wd(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>wd(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 iw(e)}}var iw=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 lw(e,t){return{...Te(e.innerType._def,t),default:e.defaultValue()}}function cw(e,t){return t.effectStrategy==="input"?Te(e.schema._def,t):ft()}function uw(e){return{type:"string",enum:Array.from(e.values)}}var dw=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function pw(e,t){const r=[Te(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Te(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(dw(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 fw(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 Aa=void 0,Et={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:()=>(Aa===void 0&&(Aa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Aa),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 bd(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":Tt(r,"email",n.message,t);break;case"format:idn-email":Tt(r,"idn-email",n.message,t);break;case"pattern:zod":rt(r,Et.email,n.message,t);break}break;case"url":Tt(r,"uri",n.message,t);break;case"uuid":Tt(r,"uuid",n.message,t);break;case"regex":rt(r,n.regex,n.message,t);break;case"cuid":rt(r,Et.cuid,n.message,t);break;case"cuid2":rt(r,Et.cuid2,n.message,t);break;case"startsWith":rt(r,RegExp(`^${qa(n.value,t)}`),n.message,t);break;case"endsWith":rt(r,RegExp(`${qa(n.value,t)}$`),n.message,t);break;case"datetime":Tt(r,"date-time",n.message,t);break;case"date":Tt(r,"date",n.message,t);break;case"time":Tt(r,"time",n.message,t);break;case"duration":Tt(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":{rt(r,RegExp(qa(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Tt(r,"ipv4",n.message,t),n.version!=="v4"&&Tt(r,"ipv6",n.message,t);break}case"base64url":rt(r,Et.base64url,n.message,t);break;case"jwt":rt(r,Et.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&rt(r,Et.ipv4Cidr,n.message,t),n.version!=="v4"&&rt(r,Et.ipv6Cidr,n.message,t);break}case"emoji":rt(r,Et.emoji(),n.message,t);break;case"ulid":{rt(r,Et.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Tt(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{rt(r,Et.base64,n.message,t);break}}break}case"nanoid":rt(r,Et.nanoid,n.message,t)}return r}function qa(e,t){return t.patternStrategy==="escape"?mw(e):e}var hw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mw(e){let t="";for(let r=0;r<e.length;r++)hw.has(e[r])||(t+="\\"),t+=e[r];return t}function Tt(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 rt(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:Sd(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Sd(t,n)}function Sd(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
27
+ path: iss.path ? [${wo(_)}, ...iss.path] : [${wo(_)}]
28
+ })));`),p.write(`newResult[${wo(_)}] = ${h}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(_,h)=>w(m,_,h)};let o;const s=Es,a=!Fd.jitless,l=a&&fv.value,c=t.catchall;let u;e._zod.parse=(m,p)=>{u??(u=r.value);const f=m.value;if(!s(f))return m.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),m;const g=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),m=o(m,p);else{m.value={};const h=u.shape;for(const S of u.keys){const k=h[S],C=k._zod.run({value:f[S],issues:[]},p),b=k._zod.optin==="optional"&&k._zod.optout==="optional";C instanceof Promise?g.push(C.then(E=>b?ip(E,m,S,f):Ns(E,m,S))):b?ip(C,m,S,f):Ns(C,m,S)}}if(!c)return g.length?Promise.all(g).then(()=>m):m;const v=[],y=u.keySet,w=c._zod,_=w.def.type;for(const h of Object.keys(f)){if(y.has(h))continue;if(_==="never"){v.push(h);continue}const S=w.run({value:f[h],issues:[]},p);S instanceof Promise?g.push(S.then(k=>Ns(k,m,h))):Ns(S,m,h)}return v.length&&m.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),g.length?Promise.all(g).then(()=>m):m}});function lp(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=>Jr(s,n,Hr())))}),t}const cp=J("$ZodUnion",(e,t)=>{Ge.init(e,t),Fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Fe(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>zi(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=>lp(a,r,e,n)):lp(s,r,e,n)}}),W1=J("$ZodDiscriminatedUnion",(e,t)=>{cp.init(e,t);const r=e._zod.parse;Fe(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const c of l)o[i].add(c)}}return o});const n=Di(()=>{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(!Es(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)}}),K1=J("$ZodIntersection",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>up(r,l,c)):up(r,s,a)}});function Zi(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($s(e)&&$s(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=Zi(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=Zi(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 up(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),ko(e))return e;const n=Zi(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 Y1=J("$ZodRecord",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!$s(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(..._n(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(..._n(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=>Jr(c,n,Hr())),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(..._n(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(..._n(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Q1=J("$ZodEnum",(e,t)=>{Ge.init(e,t);const r=Vd(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>hv.has(typeof n)).map(n=>typeof n=="string"?bo(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}}),X1=J("$ZodLiteral",(e,t)=>{Ge.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?bo(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}}),ew=J("$ZodTransform",(e,t)=>{Ge.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new vo;return r.value=o,r}}),tw=J("$ZodOptional",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${zi(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)}),rw=J("$ZodNullable",(e,t)=>{Ge.init(e,t),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${zi(r.source)}|null)$`):void 0}),Fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),nw=J("$ZodDefault",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>dp(s,t)):dp(o,t)}});function dp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const ow=J("$ZodPrefault",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),sw=J("$ZodNonOptional",(e,t)=>{Ge.init(e,t),Fe(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>pp(s,e)):pp(o,e)}});function pp(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 aw=J("$ZodCatch",(e,t)=>{Ge.init(e,t),e._zod.optin="optional",Fe(e._zod,"optout",()=>t.innerType._zod.optout),Fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(a=>Jr(a,n,Hr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Jr(s,n,Hr()))},input:r.value}),r.issues=[]),r)}}),iw=J("$ZodPipe",(e,t)=>{Ge.init(e,t),Fe(e._zod,"values",()=>t.in._zod.values),Fe(e._zod,"optin",()=>t.in._zod.optin),Fe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>fp(s,t,n)):fp(o,t,n)}});function fp(e,t,r){return ko(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const lw=J("$ZodReadonly",(e,t)=>{Ge.init(e,t),Fe(e._zod,"propValues",()=>t.innerType._zod.propValues),Fe(e._zod,"values",()=>t.innerType._zod.values),Fe(e._zod,"optin",()=>t.innerType._zod.optin),Fe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(hp):hp(o)}});function hp(e){return e.value=Object.freeze(e.value),e}const cw=J("$ZodLazy",(e,t)=>{Ge.init(e,t),Fe(e._zod,"innerType",()=>t.getter()),Fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),Fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),uw=J("$ZodCustom",(e,t)=>{jt.init(e,t),Ge.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>mp(s,r,n,e));mp(o,r,n,e)}});function mp(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(Co(o))}}class gp{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 dw(){return new gp}const To=dw();function pw(e,t){return new e({type:"string",...de(t)})}function fw(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...de(t)})}function yp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...de(t)})}function hw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...de(t)})}function mw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(t)})}function gw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(t)})}function yw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(t)})}function _p(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...de(t)})}function _w(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...de(t)})}function vw(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(t)})}function ww(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...de(t)})}function bw(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(t)})}function kw(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...de(t)})}function Cw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...de(t)})}function Tw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(t)})}function Sw(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(t)})}function Iw(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(t)})}function xw(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(t)})}function Ew(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(t)})}function vp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...de(t)})}function $w(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...de(t)})}function Rw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...de(t)})}function Pw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...de(t)})}function Nw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(t)})}function Mw(e,t){return new e({type:"string",format:"date",check:"string_format",...de(t)})}function Ow(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...de(t)})}function Aw(e,t){return new e({type:"string",format:"duration",check:"string_format",...de(t)})}function qw(e,t){return new e({type:"number",checks:[],...de(t)})}function Lw(e,t){return new e({type:"number",coerce:!0,checks:[],...de(t)})}function jw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...de(t)})}function Dw(e,t){return new e({type:"boolean",...de(t)})}function Uw(e,t){return new e({type:"null",...de(t)})}function zw(e){return new e({type:"any"})}function Fw(e){return new e({type:"unknown"})}function Vw(e,t){return new e({type:"never",...de(t)})}function wp(e,t){return new rp({check:"less_than",...de(t),value:e,inclusive:!1})}function Bi(e,t){return new rp({check:"less_than",...de(t),value:e,inclusive:!0})}function bp(e,t){return new np({check:"greater_than",...de(t),value:e,inclusive:!1})}function Hi(e,t){return new np({check:"greater_than",...de(t),value:e,inclusive:!0})}function kp(e,t){return new r1({check:"multiple_of",...de(t),value:e})}function Cp(e,t){return new o1({check:"max_length",...de(t),maximum:e})}function Ms(e,t){return new s1({check:"min_length",...de(t),minimum:e})}function Tp(e,t){return new a1({check:"length_equals",...de(t),length:e})}function Zw(e,t){return new i1({check:"string_format",format:"regex",...de(t),pattern:e})}function Bw(e){return new l1({check:"string_format",format:"lowercase",...de(e)})}function Hw(e){return new c1({check:"string_format",format:"uppercase",...de(e)})}function Jw(e,t){return new u1({check:"string_format",format:"includes",...de(t),includes:e})}function Gw(e,t){return new d1({check:"string_format",format:"starts_with",...de(t),prefix:e})}function Ww(e,t){return new p1({check:"string_format",format:"ends_with",...de(t),suffix:e})}function So(e){return new f1({check:"overwrite",tx:e})}function Kw(e){return So(t=>t.normalize(e))}function Yw(){return So(e=>e.trim())}function Qw(){return So(e=>e.toLowerCase())}function Xw(){return So(e=>e.toUpperCase())}function eb(e,t,r){return new e({type:"array",element:t,...de(r)})}function tb(e,t,r){const n=de(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function rb(e,t,r){return new e({type:"custom",check:"custom",fn:t,...de(r)})}class Sp{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??To,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const m={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,m),this.seen.get(p).isParent=!0;else{const f=i.schema;switch(o.type){case"string":{const g=f;g.type="string";const{minimum:v,maximum:y,format:w,patterns:_,contentEncoding:h}=t._zod.bag;if(typeof v=="number"&&(g.minLength=v),typeof y=="number"&&(g.maxLength=y),w&&(g.format=s[w]??w,g.format===""&&delete g.format),h&&(g.contentEncoding=h),_&&_.size>0){const S=[..._];S.length===1?g.pattern=S[0].source:S.length>1&&(i.schema.allOf=[...S.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const g=f,{minimum:v,maximum:y,format:w,multipleOf:_,exclusiveMaximum:h,exclusiveMinimum:S}=t._zod.bag;typeof w=="string"&&w.includes("int")?g.type="integer":g.type="number",typeof S=="number"&&(g.exclusiveMinimum=S),typeof v=="number"&&(g.minimum=v,typeof S=="number"&&(S>=v?delete g.minimum:delete g.exclusiveMinimum)),typeof h=="number"&&(g.exclusiveMaximum=h),typeof y=="number"&&(g.maximum=y,typeof h=="number"&&(h<=y?delete g.maximum:delete g.exclusiveMaximum)),typeof _=="number"&&(g.multipleOf=_);break}case"boolean":{const g=f;g.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const g=f,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(g.minItems=v),typeof y=="number"&&(g.maxItems=y),g.type="array",g.items=this.process(o.element,{...m,path:[...m.path,"items"]});break}case"object":{const g=f;g.type="object",g.properties={};const v=o.shape;for(const _ in v)g.properties[_]=this.process(v[_],{...m,path:[...m.path,"properties",_]});const y=new Set(Object.keys(v)),w=new Set([...y].filter(_=>{const h=o.shape[_]._zod;return this.io==="input"?h.optin===void 0:h.optout===void 0}));w.size>0&&(g.required=Array.from(w)),o.catchall?._zod.def.type==="never"?g.additionalProperties=!1:o.catchall?o.catchall&&(g.additionalProperties=this.process(o.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(g.additionalProperties=!1);break}case"union":{const g=f;g.anyOf=o.options.map((v,y)=>this.process(v,{...m,path:[...m.path,"anyOf",y]}));break}case"intersection":{const g=f,v=this.process(o.left,{...m,path:[...m.path,"allOf",0]}),y=this.process(o.right,{...m,path:[...m.path,"allOf",1]}),w=h=>"allOf"in h&&Object.keys(h).length===1,_=[...w(v)?v.allOf:[v],...w(y)?y.allOf:[y]];g.allOf=_;break}case"tuple":{const g=f;g.type="array";const v=o.items.map((_,h)=>this.process(_,{...m,path:[...m.path,"prefixItems",h]}));if(this.target==="draft-2020-12"?g.prefixItems=v:g.items=v,o.rest){const _=this.process(o.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?g.items=_:g.additionalItems=_}o.rest&&(g.items=this.process(o.rest,{...m,path:[...m.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(g.minItems=y),typeof w=="number"&&(g.maxItems=w);break}case"record":{const g=f;g.type="object",g.propertyNames=this.process(o.keyType,{...m,path:[...m.path,"propertyNames"]}),g.additionalProperties=this.process(o.valueType,{...m,path:[...m.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const g=f,v=Vd(o.entries);v.every(y=>typeof y=="number")&&(g.type="number"),v.every(y=>typeof y=="string")&&(g.type="string"),g.enum=v;break}case"literal":{const g=f,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];g.type=y===null?"null":typeof y,g.const=y}else v.every(y=>typeof y=="number")&&(g.type="number"),v.every(y=>typeof y=="string")&&(g.type="string"),v.every(y=>typeof y=="boolean")&&(g.type="string"),v.every(y=>y===null)&&(g.type="null"),g.enum=v;break}case"file":{const g=f,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:_}=t._zod.bag;y!==void 0&&(v.minLength=y),w!==void 0&&(v.maxLength=w),_?_.length===1?(v.contentMediaType=_[0],Object.assign(g,v)):g.anyOf=_.map(h=>({...v,contentMediaType:h})):Object.assign(g,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const g=this.process(o.innerType,m);f.anyOf=[g,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,m),i.ref=o.innerType;break}case"success":{const g=f;g.type="boolean";break}case"default":{this.process(o.innerType,m),i.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,m),i.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,m),i.ref=o.innerType;let g;try{g=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=g;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const g=f,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");g.type="string",g.pattern=v.source;break}case"pipe":{const g=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(g,m),i.ref=g;break}case"readonly":{this.process(o.innerType,m),i.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,m),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,m),i.ref=o.innerType;break}case"lazy":{const g=t._zod.innerType;this.process(g,m),i.ref=g;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&yt(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const m=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,y=n.external.uri??(_=>_);if(v)return{ref:y(v)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${y("__shared")}#/${m}/${w}`}}if(u[1]===o)return{ref:"#"};const f=`#/${m}/`,g=u[1].schema.id??`__schema${this.counter++}`;return{defId:g,ref:f+g}},a=u=>{if(u[1].schema.$ref)return;const m=u[1],{ref:p,defId:f}=s(u);m.def={...m.schema},f&&(m.defId=f);const g=m.schema;for(const v in g)delete g[v];g.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const m=u[1];if(m.cycle)throw new Error(`Cycle detected: #/${m.cycle?.join("/")}/<root>
29
+
30
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const m=u[1];if(t===u[0]){a(u);continue}if(n.external){const f=n.external.registry.get(u[0])?.id;if(t!==u[0]&&f){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(m.cycle){a(u);continue}if(m.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,m)=>{const p=this.seen.get(u),f=p.def??p.schema,g={...f};if(p.ref===null)return;const v=p.ref;if(p.ref=null,v){i(v,m);const y=this.seen.get(v).schema;y.$ref&&m.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(y)):(Object.assign(f,y),Object.assign(f,g))}p.isParent||this.override({zodSchema:u,jsonSchema:f,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const m=u[1];m.def&&m.defId&&(c[m.defId]=m.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function nb(e,t){if(e instanceof gp){const n=new Sp(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 Sp(t);return r.process(e),r.emit(e,t)}function yt(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 yt(o.element,r);case"object":{for(const s in o.shape)if(yt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(yt(s,r))return!0;return!1}case"intersection":return yt(o.left,r)||yt(o.right,r);case"tuple":{for(const s of o.items)if(yt(s,r))return!0;return!!(o.rest&&yt(o.rest,r))}case"record":return yt(o.keyType,r)||yt(o.valueType,r);case"map":return yt(o.keyType,r)||yt(o.valueType,r);case"set":return yt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return yt(o.innerType,r);case"lazy":return yt(o.getter(),r);case"default":return yt(o.innerType,r);case"prefault":return yt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return yt(o.in,r)||yt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const ob=J("ZodISODateTime",(e,t)=>{x1.init(e,t),at.init(e,t)});function Ip(e){return Nw(ob,e)}const sb=J("ZodISODate",(e,t)=>{E1.init(e,t),at.init(e,t)});function ab(e){return Mw(sb,e)}const ib=J("ZodISOTime",(e,t)=>{$1.init(e,t),at.init(e,t)});function lb(e){return Ow(ib,e)}const cb=J("ZodISODuration",(e,t)=>{R1.init(e,t),at.init(e,t)});function ub(e){return Aw(cb,e)}const Os=J("ZodError",(e,t)=>{Hd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Tv(e,r)},flatten:{value:r=>Cv(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}),db=Sv(Os),pb=Iv(Os),fb=Gd(Os),xp=Kd(Os),Ye=J("ZodType",(e,t)=>(Ge.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>yn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>db(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>fb(e,r,n),e.parseAsync=async(r,n)=>pb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>xp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(n3(r,n)),e.superRefine=r=>e.check(o3(r)),e.overwrite=r=>e.check(So(r)),e.optional=()=>ce(e),e.nullable=()=>jp(e),e.nullish=()=>ce(jp(e)),e.nonoptional=r=>Wb(e,r),e.array=()=>q(e),e.or=r=>oe([e,r]),e.and=r=>Gi(e,r),e.transform=r=>Ki(e,qp(r)),e.default=r=>Hb(e,r),e.prefault=r=>Gb(e,r),e.catch=r=>Yb(e,r),e.pipe=r=>Ki(e,r),e.readonly=()=>e3(e),e.describe=r=>{const n=e.clone();return To.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return To.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return To.get(e);const n=e.clone();return To.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Ep=J("_ZodString",(e,t)=>{Vi.init(e,t),Ye.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(Zw(...n)),e.includes=(...n)=>e.check(Jw(...n)),e.startsWith=(...n)=>e.check(Gw(...n)),e.endsWith=(...n)=>e.check(Ww(...n)),e.min=(...n)=>e.check(Ms(...n)),e.max=(...n)=>e.check(Cp(...n)),e.length=(...n)=>e.check(Tp(...n)),e.nonempty=(...n)=>e.check(Ms(1,...n)),e.lowercase=n=>e.check(Bw(n)),e.uppercase=n=>e.check(Hw(n)),e.trim=()=>e.check(Yw()),e.normalize=(...n)=>e.check(Kw(...n)),e.toLowerCase=()=>e.check(Qw()),e.toUpperCase=()=>e.check(Xw())}),hb=J("ZodString",(e,t)=>{Vi.init(e,t),Ep.init(e,t),e.email=r=>e.check(fw(mb,r)),e.url=r=>e.check(_p(Rp,r)),e.jwt=r=>e.check(Pw(Rb,r)),e.emoji=r=>e.check(_w(yb,r)),e.guid=r=>e.check(yp($p,r)),e.uuid=r=>e.check(hw(As,r)),e.uuidv4=r=>e.check(mw(As,r)),e.uuidv6=r=>e.check(gw(As,r)),e.uuidv7=r=>e.check(yw(As,r)),e.nanoid=r=>e.check(vw(_b,r)),e.guid=r=>e.check(yp($p,r)),e.cuid=r=>e.check(ww(vb,r)),e.cuid2=r=>e.check(bw(wb,r)),e.ulid=r=>e.check(kw(bb,r)),e.base64=r=>e.check(vp(Pp,r)),e.base64url=r=>e.check($w(Eb,r)),e.xid=r=>e.check(Cw(kb,r)),e.ksuid=r=>e.check(Tw(Cb,r)),e.ipv4=r=>e.check(Sw(Tb,r)),e.ipv6=r=>e.check(Iw(Sb,r)),e.cidrv4=r=>e.check(xw(Ib,r)),e.cidrv6=r=>e.check(Ew(xb,r)),e.e164=r=>e.check(Rw($b,r)),e.datetime=r=>e.check(Ip(r)),e.date=r=>e.check(ab(r)),e.time=r=>e.check(lb(r)),e.duration=r=>e.check(ub(r))});function d(e){return pw(hb,e)}const at=J("ZodStringFormat",(e,t)=>{tt.init(e,t),Ep.init(e,t)}),mb=J("ZodEmail",(e,t)=>{_1.init(e,t),at.init(e,t)}),$p=J("ZodGUID",(e,t)=>{g1.init(e,t),at.init(e,t)}),As=J("ZodUUID",(e,t)=>{y1.init(e,t),at.init(e,t)}),Rp=J("ZodURL",(e,t)=>{v1.init(e,t),at.init(e,t)});function gb(e){return _p(Rp,e)}const yb=J("ZodEmoji",(e,t)=>{w1.init(e,t),at.init(e,t)}),_b=J("ZodNanoID",(e,t)=>{b1.init(e,t),at.init(e,t)}),vb=J("ZodCUID",(e,t)=>{k1.init(e,t),at.init(e,t)}),wb=J("ZodCUID2",(e,t)=>{C1.init(e,t),at.init(e,t)}),bb=J("ZodULID",(e,t)=>{T1.init(e,t),at.init(e,t)}),kb=J("ZodXID",(e,t)=>{S1.init(e,t),at.init(e,t)}),Cb=J("ZodKSUID",(e,t)=>{I1.init(e,t),at.init(e,t)}),Tb=J("ZodIPv4",(e,t)=>{P1.init(e,t),at.init(e,t)}),Sb=J("ZodIPv6",(e,t)=>{N1.init(e,t),at.init(e,t)}),Ib=J("ZodCIDRv4",(e,t)=>{M1.init(e,t),at.init(e,t)}),xb=J("ZodCIDRv6",(e,t)=>{O1.init(e,t),at.init(e,t)}),Pp=J("ZodBase64",(e,t)=>{A1.init(e,t),at.init(e,t)});function Np(e){return vp(Pp,e)}const Eb=J("ZodBase64URL",(e,t)=>{L1.init(e,t),at.init(e,t)}),$b=J("ZodE164",(e,t)=>{j1.init(e,t),at.init(e,t)}),Rb=J("ZodJWT",(e,t)=>{U1.init(e,t),at.init(e,t)}),Ji=J("ZodNumber",(e,t)=>{sp.init(e,t),Ye.init(e,t),e.gt=(n,o)=>e.check(bp(n,o)),e.gte=(n,o)=>e.check(Hi(n,o)),e.min=(n,o)=>e.check(Hi(n,o)),e.lt=(n,o)=>e.check(wp(n,o)),e.lte=(n,o)=>e.check(Bi(n,o)),e.max=(n,o)=>e.check(Bi(n,o)),e.int=n=>e.check(Mp(n)),e.safe=n=>e.check(Mp(n)),e.positive=n=>e.check(bp(0,n)),e.nonnegative=n=>e.check(Hi(0,n)),e.negative=n=>e.check(wp(0,n)),e.nonpositive=n=>e.check(Bi(0,n)),e.multipleOf=(n,o)=>e.check(kp(n,o)),e.step=(n,o)=>e.check(kp(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function j(e){return qw(Ji,e)}const Pb=J("ZodNumberFormat",(e,t)=>{z1.init(e,t),Ji.init(e,t)});function Mp(e){return jw(Pb,e)}const Nb=J("ZodBoolean",(e,t)=>{F1.init(e,t),Ye.init(e,t)});function fe(e){return Dw(Nb,e)}const Mb=J("ZodNull",(e,t)=>{V1.init(e,t),Ye.init(e,t)});function qs(e){return Uw(Mb,e)}const Ob=J("ZodAny",(e,t)=>{Z1.init(e,t),Ye.init(e,t)});function vt(){return zw(Ob)}const Ab=J("ZodUnknown",(e,t)=>{B1.init(e,t),Ye.init(e,t)});function $e(){return Fw(Ab)}const qb=J("ZodNever",(e,t)=>{H1.init(e,t),Ye.init(e,t)});function Lb(e){return Vw(qb,e)}const jb=J("ZodArray",(e,t)=>{J1.init(e,t),Ye.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Ms(r,n)),e.nonempty=r=>e.check(Ms(1,r)),e.max=(r,n)=>e.check(Cp(r,n)),e.length=(r,n)=>e.check(Tp(r,n)),e.unwrap=()=>e.element});function q(e,t){return eb(jb,e,t)}const Op=J("ZodObject",(e,t)=>{G1.init(e,t),Ye.init(e,t),Fe(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:Lb()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>vv(e,r),e.merge=r=>wv(e,r),e.pick=r=>yv(e,r),e.omit=r=>_v(e,r),e.partial=(...r)=>bv(Lp,e,r[0]),e.required=(...r)=>kv(Dp,e,r[0])});function T(e,t){const r={type:"object",get shape(){return xs(this,"shape",{...e}),this.shape},...de(t)};return new Op(r)}function it(e,t){return new Op({type:"object",get shape(){return xs(this,"shape",{...e}),this.shape},catchall:$e(),...de(t)})}const Ap=J("ZodUnion",(e,t)=>{cp.init(e,t),Ye.init(e,t),e.options=t.options});function oe(e,t){return new Ap({type:"union",options:e,...de(t)})}const Db=J("ZodDiscriminatedUnion",(e,t)=>{Ap.init(e,t),W1.init(e,t)});function De(e,t,r){return new Db({type:"union",options:t,discriminator:e,...de(r)})}const Ub=J("ZodIntersection",(e,t)=>{K1.init(e,t),Ye.init(e,t)});function Gi(e,t){return new Ub({type:"intersection",left:e,right:t})}const zb=J("ZodRecord",(e,t)=>{Y1.init(e,t),Ye.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ge(e,t,r){return new zb({type:"record",keyType:e,valueType:t,...de(r)})}const Wi=J("ZodEnum",(e,t)=>{Q1.init(e,t),Ye.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 Wi({...t,checks:[],...de(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Wi({...t,checks:[],...de(o),entries:s})}});function _e(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Wi({type:"enum",entries:r,...de(t)})}const Fb=J("ZodLiteral",(e,t)=>{X1.init(e,t),Ye.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 $(e,t){return new Fb({type:"literal",values:Array.isArray(e)?e:[e],...de(t)})}const Vb=J("ZodTransform",(e,t)=>{ew.init(e,t),Ye.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Co(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(Co(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function qp(e){return new Vb({type:"transform",transform:e})}const Lp=J("ZodOptional",(e,t)=>{tw.init(e,t),Ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ce(e){return new Lp({type:"optional",innerType:e})}const Zb=J("ZodNullable",(e,t)=>{rw.init(e,t),Ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function jp(e){return new Zb({type:"nullable",innerType:e})}const Bb=J("ZodDefault",(e,t)=>{nw.init(e,t),Ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hb(e,t){return new Bb({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Jb=J("ZodPrefault",(e,t)=>{ow.init(e,t),Ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Gb(e,t){return new Jb({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Dp=J("ZodNonOptional",(e,t)=>{sw.init(e,t),Ye.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Wb(e,t){return new Dp({type:"nonoptional",innerType:e,...de(t)})}const Kb=J("ZodCatch",(e,t)=>{aw.init(e,t),Ye.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Yb(e,t){return new Kb({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Qb=J("ZodPipe",(e,t)=>{iw.init(e,t),Ye.init(e,t),e.in=t.in,e.out=t.out});function Ki(e,t){return new Qb({type:"pipe",in:e,out:t})}const Xb=J("ZodReadonly",(e,t)=>{lw.init(e,t),Ye.init(e,t)});function e3(e){return new Xb({type:"readonly",innerType:e})}const t3=J("ZodLazy",(e,t)=>{cw.init(e,t),Ye.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Yi(e){return new t3({type:"lazy",getter:e})}const Qi=J("ZodCustom",(e,t)=>{uw.init(e,t),Ye.init(e,t)});function r3(e){const t=new jt({check:"custom"});return t._zod.check=e,t}function Up(e,t){return tb(Qi,e??(()=>!0),t)}function n3(e,t={}){return rb(Qi,e,t)}function o3(e){const t=r3(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Co(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(Co(o))}},e(r.value,r)));return t}function Ls(e,t={error:`Input not instance of ${e.name}`}){const r=new Qi({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...de(t)});return r._zod.bag.Class=e,r}function zp(e,t){return Ki(qp(e),t)}const Fp={custom:"custom"};function Vp(e){return Lw(Ji,e)}var Ue;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Ue||(Ue={}));var Zp;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Zp||(Zp={}));const ue=Ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Gr=e=>{switch(typeof e){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return Number.isNaN(e)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(e)?ue.array:e===null?ue.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ue.promise:typeof Map<"u"&&e instanceof Map?ue.map:typeof Set<"u"&&e instanceof Set?ue.set:typeof Date<"u"&&e instanceof Date?ue.date:ue.object;default:return ue.unknown}},te=Ue.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Rr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof Rr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ue.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Rr.create=e=>new Rr(e);const Xi=(e,t)=>{let r;switch(e.code){case te.invalid_type:e.received===ue.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case te.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ue.jsonStringifyReplacer)}`;break;case te.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ue.joinValues(e.keys,", ")}`;break;case te.invalid_union:r="Invalid input";break;case te.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ue.joinValues(e.options)}`;break;case te.invalid_enum_value:r=`Invalid enum value. Expected ${Ue.joinValues(e.options)}, received '${e.received}'`;break;case te.invalid_arguments:r="Invalid function arguments";break;case te.invalid_return_type:r="Invalid function return type";break;case te.invalid_date:r="Invalid date";break;case te.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Ue.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case te.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case te.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case te.custom:r="Invalid input";break;case te.invalid_intersection_types:r="Intersection results could not be merged";break;case te.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case te.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ue.assertNever(e)}return{message:r}};let s3=Xi;function a3(){return s3}const i3=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}};function ae(e,t){const r=a3(),n=i3({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Xi?void 0:Xi].filter(o=>!!o)});e.common.issues.push(n)}class Zt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return xe;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,a=await o.value;n.push({key:s,value:a})}return Zt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return xe;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:t.value,value:n}}}const xe=Object.freeze({status:"aborted"}),Io=e=>({status:"dirty",value:e}),Kt=e=>({status:"valid",value:e}),Bp=e=>e.status==="aborted",Hp=e=>e.status==="dirty",Un=e=>e.status==="valid",js=e=>typeof Promise<"u"&&e instanceof Promise;var pe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(pe||(pe={}));class Wr{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Jp=(e,t)=>{if(Un(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Rr(e.common.issues);return this._error=r,this._error}}};function Oe(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:o}}class Le{get description(){return this._def.description}_getType(t){return Gr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Gr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Zt,ctx:{common:t.parent.common,data:t.data,parsedType:Gr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(js(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Gr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Jp(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Gr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Un(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Un(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Gr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(js(o)?o:Promise.resolve(o));return Jp(n,s)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:te.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Zn({schema:this,typeName:ne.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Qr.create(this,this._def)}nullable(){return Bn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wr.create(this)}promise(){return Fs.create(this,this._def)}or(t){return Us.create([this,t],this._def)}and(t){return zs.create(this,t,this._def)}transform(t){return new Zn({...Oe(this._def),schema:this,typeName:ne.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new rl({...Oe(this._def),innerType:this,defaultValue:r,typeName:ne.ZodDefault})}brand(){return new R3({typeName:ne.ZodBranded,type:this,...Oe(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new nl({...Oe(this._def),innerType:this,catchValue:r,typeName:ne.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return ol.create(this,t)}readonly(){return sl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const l3=/^c[^\s-]{8,}$/i,c3=/^[0-9a-z]+$/,u3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,d3=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,p3=/^[a-z0-9_-]{21}$/i,f3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,h3=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,m3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,g3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let el;const y3=/^(?:(?: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=/^(?:(?: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])$/,v3=/^(([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]))$/,w3=/^(([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])$/,b3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,k3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gp="((\\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])))",C3=new RegExp(`^${Gp}$`);function Wp(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function T3(e){return new RegExp(`^${Wp(e)}$`)}function S3(e){let t=`${Gp}T${Wp(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function I3(e,t){return!!((t==="v4"||!t)&&y3.test(e)||(t==="v6"||!t)&&v3.test(e))}function x3(e,t){if(!f3.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function E3(e,t){return!!((t==="v4"||!t)&&_3.test(e)||(t==="v6"||!t)&&w3.test(e))}class Kr extends Le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ue.string){const s=this._getOrReturnCtx(t);return ae(s,{code:te.invalid_type,expected:ue.string,received:s.parsedType}),xe}const n=new Zt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:te.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:te.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?ae(o,{code:te.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&ae(o,{code:te.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")m3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"email",code:te.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")el||(el=new RegExp(g3,"u")),el.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"emoji",code:te.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")d3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"uuid",code:te.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")p3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"nanoid",code:te.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")l3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"cuid",code:te.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")c3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"cuid2",code:te.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")u3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"ulid",code:te.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ae(o,{validation:"url",code:te.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"regex",code:te.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),ae(o,{code:te.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),ae(o,{code:te.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),ae(o,{code:te.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?S3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{code:te.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?C3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{code:te.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?T3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{code:te.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?h3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"duration",code:te.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?I3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"ip",code:te.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?x3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"jwt",code:te.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?E3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"cidr",code:te.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?b3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"base64",code:te.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?k3.test(t.data)||(o=this._getOrReturnCtx(t,o),ae(o,{validation:"base64url",code:te.invalid_string,message:s.message}),n.dirty()):Ue.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:te.invalid_string,...pe.errToObj(n)})}_addCheck(t){return new Kr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...pe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...pe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...pe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...pe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...pe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...pe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...pe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...pe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...pe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...pe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...pe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...pe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...pe.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...pe.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...pe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...pe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...pe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...pe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...pe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...pe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...pe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...pe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...pe.errToObj(r)})}nonempty(t){return this.min(1,pe.errToObj(t))}trim(){return new Kr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Kr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Kr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}Kr.create=e=>new Kr({checks:[],typeName:ne.ZodString,coerce:e?.coerce??!1,...Oe(e)});function $3(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}class zn extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ue.number){const s=this._getOrReturnCtx(t);return ae(s,{code:te.invalid_type,expected:ue.number,received:s.parsedType}),xe}let n;const o=new Zt;for(const s of this._def.checks)s.kind==="int"?Ue.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ae(n,{code:te.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:te.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:te.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?$3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),ae(n,{code:te.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ae(n,{code:te.not_finite,message:s.message}),o.dirty()):Ue.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,pe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,pe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,pe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,pe.toString(r))}setLimit(t,r,n,o){return new zn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:pe.toString(o)}]})}_addCheck(t){return new zn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:pe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:pe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:pe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:pe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:pe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:pe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:pe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:pe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:pe.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Ue.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}}zn.create=e=>new zn({checks:[],typeName:ne.ZodNumber,coerce:e?.coerce||!1,...Oe(e)});class xo extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ue.bigint)return this._getInvalidInput(t);let n;const o=new Zt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:te.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:te.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),ae(n,{code:te.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Ue.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return ae(r,{code:te.invalid_type,expected:ue.bigint,received:r.parsedType}),xe}gte(t,r){return this.setLimit("min",t,!0,pe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,pe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,pe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,pe.toString(r))}setLimit(t,r,n,o){return new xo({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:pe.toString(o)}]})}_addCheck(t){return new xo({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:pe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:pe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:pe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:pe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:pe.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}xo.create=e=>new xo({checks:[],typeName:ne.ZodBigInt,coerce:e?.coerce??!1,...Oe(e)});class Kp extends Le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ue.boolean){const n=this._getOrReturnCtx(t);return ae(n,{code:te.invalid_type,expected:ue.boolean,received:n.parsedType}),xe}return Kt(t.data)}}Kp.create=e=>new Kp({typeName:ne.ZodBoolean,coerce:e?.coerce||!1,...Oe(e)});class Ds extends Le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ue.date){const s=this._getOrReturnCtx(t);return ae(s,{code:te.invalid_type,expected:ue.date,received:s.parsedType}),xe}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return ae(s,{code:te.invalid_date}),xe}const n=new Zt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:te.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),ae(o,{code:te.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ue.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ds({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:pe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:pe.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}Ds.create=e=>new Ds({checks:[],coerce:e?.coerce||!1,typeName:ne.ZodDate,...Oe(e)});class Yp extends Le{_parse(t){if(this._getType(t)!==ue.symbol){const n=this._getOrReturnCtx(t);return ae(n,{code:te.invalid_type,expected:ue.symbol,received:n.parsedType}),xe}return Kt(t.data)}}Yp.create=e=>new Yp({typeName:ne.ZodSymbol,...Oe(e)});class Qp extends Le{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return ae(n,{code:te.invalid_type,expected:ue.undefined,received:n.parsedType}),xe}return Kt(t.data)}}Qp.create=e=>new Qp({typeName:ne.ZodUndefined,...Oe(e)});class Xp extends Le{_parse(t){if(this._getType(t)!==ue.null){const n=this._getOrReturnCtx(t);return ae(n,{code:te.invalid_type,expected:ue.null,received:n.parsedType}),xe}return Kt(t.data)}}Xp.create=e=>new Xp({typeName:ne.ZodNull,...Oe(e)});class ef extends Le{constructor(){super(...arguments),this._any=!0}_parse(t){return Kt(t.data)}}ef.create=e=>new ef({typeName:ne.ZodAny,...Oe(e)});class tf extends Le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Kt(t.data)}}tf.create=e=>new tf({typeName:ne.ZodUnknown,...Oe(e)});class Yr extends Le{_parse(t){const r=this._getOrReturnCtx(t);return ae(r,{code:te.invalid_type,expected:ue.never,received:r.parsedType}),xe}}Yr.create=e=>new Yr({typeName:ne.ZodNever,...Oe(e)});class rf extends Le{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return ae(n,{code:te.invalid_type,expected:ue.void,received:n.parsedType}),xe}return Kt(t.data)}}rf.create=e=>new rf({typeName:ne.ZodVoid,...Oe(e)});class wr extends Le{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ue.array)return ae(r,{code:te.invalid_type,expected:ue.array,received:r.parsedType}),xe;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(ae(r,{code:a?te.too_big:te.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(ae(r,{code:te.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(ae(r,{code:te.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new Wr(r,a,r.path,i)))).then(a=>Zt.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Wr(r,a,r.path,i)));return Zt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new wr({...this._def,minLength:{value:t,message:pe.toString(r)}})}max(t,r){return new wr({...this._def,maxLength:{value:t,message:pe.toString(r)}})}length(t,r){return new wr({...this._def,exactLength:{value:t,message:pe.toString(r)}})}nonempty(t){return this.min(1,t)}}wr.create=(e,t)=>new wr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ne.ZodArray,...Oe(t)});function Fn(e){if(e instanceof mt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Qr.create(Fn(n))}return new mt({...e._def,shape:()=>t})}else return e instanceof wr?new wr({...e._def,type:Fn(e.element)}):e instanceof Qr?Qr.create(Fn(e.unwrap())):e instanceof Bn?Bn.create(Fn(e.unwrap())):e instanceof vn?vn.create(e.items.map(t=>Fn(t))):e}class mt extends Le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=Ue.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ue.object){const c=this._getOrReturnCtx(t);return ae(c,{code:te.invalid_type,expected:ue.object,received:c.parsedType}),xe}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Yr&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=s[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Wr(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Yr){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(ae(o,{code:te.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const m=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Wr(o,m,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const m=await u.key,p=await u.value;c.push({key:m,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Zt.mergeObjectSync(n,c)):Zt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return pe.errToObj,new mt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:pe.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new mt({...this._def,unknownKeys:"strip"})}passthrough(){return new mt({...this._def,unknownKeys:"passthrough"})}extend(t){return new mt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new mt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ne.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new mt({...this._def,catchall:t})}pick(t){const r={};for(const n of Ue.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new mt({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ue.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new mt({...this._def,shape:()=>r})}deepPartial(){return Fn(this)}partial(t){const r={};for(const n of Ue.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new mt({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ue.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Qr;)s=s._def.innerType;r[n]=s}return new mt({...this._def,shape:()=>r})}keyof(){return af(Ue.objectKeys(this.shape))}}mt.create=(e,t)=>new mt({shape:()=>e,unknownKeys:"strip",catchall:Yr.create(),typeName:ne.ZodObject,...Oe(t)}),mt.strictCreate=(e,t)=>new mt({shape:()=>e,unknownKeys:"strict",catchall:Yr.create(),typeName:ne.ZodObject,...Oe(t)}),mt.lazycreate=(e,t)=>new mt({shape:e,unknownKeys:"strip",catchall:Yr.create(),typeName:ne.ZodObject,...Oe(t)});class Us extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new Rr(i.ctx.common.issues));return ae(r,{code:te.invalid_union,unionErrors:a}),xe}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new Rr(l));return ae(r,{code:te.invalid_union,unionErrors:i}),xe}}get options(){return this._def.options}}Us.create=(e,t)=>new Us({options:e,typeName:ne.ZodUnion,...Oe(t)});function tl(e,t){const r=Gr(e),n=Gr(t);if(e===t)return{valid:!0,data:e};if(r===ue.object&&n===ue.object){const o=Ue.objectKeys(t),s=Ue.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=tl(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===ue.array&&n===ue.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=tl(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ue.date&&n===ue.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class zs extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(Bp(s)||Bp(a))return xe;const i=tl(s.value,a.value);return i.valid?((Hp(s)||Hp(a))&&r.dirty(),{status:r.value,value:i.data}):(ae(n,{code:te.invalid_intersection_types}),xe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}zs.create=(e,t,r)=>new zs({left:e,right:t,typeName:ne.ZodIntersection,...Oe(r)});class vn extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.array)return ae(n,{code:te.invalid_type,expected:ue.array,received:n.parsedType}),xe;if(n.data.length<this._def.items.length)return ae(n,{code:te.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),xe;!this._def.rest&&n.data.length>this._def.items.length&&(ae(n,{code:te.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Wr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>Zt.mergeArray(r,a)):Zt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new vn({...this._def,rest:t})}}vn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vn({items:e,typeName:ne.ZodTuple,rest:null,...Oe(t)})};class nf extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.map)return ae(n,{code:te.invalid_type,expected:ue.map,received:n.parsedType}),xe;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Wr(n,i,n.path,[c,"key"])),value:s._parse(new Wr(n,l,n.path,[c,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of a){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return xe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}nf.create=(e,t,r)=>new nf({valueType:t,keyType:e,typeName:ne.ZodMap,...Oe(r)});class Eo extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.set)return ae(n,{code:te.invalid_type,expected:ue.set,received:n.parsedType}),xe;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ae(n,{code:te.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(ae(n,{code:te.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return xe;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>s._parse(new Wr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Eo({...this._def,minSize:{value:t,message:pe.toString(r)}})}max(t,r){return new Eo({...this._def,maxSize:{value:t,message:pe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Eo.create=(e,t)=>new Eo({valueType:e,minSize:null,maxSize:null,typeName:ne.ZodSet,...Oe(t)});class of extends Le{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}of.create=(e,t)=>new of({getter:e,typeName:ne.ZodLazy,...Oe(t)});class sf extends Le{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ae(r,{received:r.data,code:te.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:t.data}}get value(){return this._def.value}}sf.create=(e,t)=>new sf({value:e,typeName:ne.ZodLiteral,...Oe(t)});function af(e,t){return new Vn({values:e,typeName:ne.ZodEnum,...Oe(t)})}class Vn extends Le{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ae(r,{expected:Ue.joinValues(n),received:r.parsedType,code:te.invalid_type}),xe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return ae(r,{received:r.data,code:te.invalid_enum_value,options:n}),xe}return Kt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return Vn.create(t,{...this._def,...r})}exclude(t,r=this._def){return Vn.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}Vn.create=af;class lf extends Le{_parse(t){const r=Ue.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ue.string&&n.parsedType!==ue.number){const o=Ue.objectValues(r);return ae(n,{expected:Ue.joinValues(o),received:n.parsedType,code:te.invalid_type}),xe}if(this._cache||(this._cache=new Set(Ue.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Ue.objectValues(r);return ae(n,{received:n.data,code:te.invalid_enum_value,options:o}),xe}return Kt(t.data)}get enum(){return this._def.values}}lf.create=(e,t)=>new lf({values:e,typeName:ne.ZodNativeEnum,...Oe(t)});class Fs extends Le{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ue.promise&&r.common.async===!1)return ae(r,{code:te.invalid_type,expected:ue.promise,received:r.parsedType}),xe;const n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return Kt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Fs.create=(e,t)=>new Fs({type:e,typeName:ne.ZodPromise,...Oe(t)});class Zn extends Le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ne.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{ae(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return xe;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?xe:l.status==="dirty"||r.value==="dirty"?Io(l.value):l});{if(r.value==="aborted")return xe;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?xe:i.status==="dirty"||r.value==="dirty"?Io(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?xe:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?xe:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Un(a))return xe;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Un(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):xe);Ue.assertNever(o)}}Zn.create=(e,t,r)=>new Zn({schema:e,typeName:ne.ZodEffects,effect:t,...Oe(r)}),Zn.createWithPreprocess=(e,t,r)=>new Zn({schema:t,effect:{type:"preprocess",transform:e},typeName:ne.ZodEffects,...Oe(r)});class Qr extends Le{_parse(t){return this._getType(t)===ue.undefined?Kt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Qr.create=(e,t)=>new Qr({innerType:e,typeName:ne.ZodOptional,...Oe(t)});class Bn extends Le{_parse(t){return this._getType(t)===ue.null?Kt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Bn.create=(e,t)=>new Bn({innerType:e,typeName:ne.ZodNullable,...Oe(t)});class rl extends Le{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===ue.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}rl.create=(e,t)=>new rl({innerType:e,typeName:ne.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Oe(t)});class nl extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return js(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Rr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Rr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}nl.create=(e,t)=>new nl({innerType:e,typeName:ne.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Oe(t)});class cf extends Le{_parse(t){if(this._getType(t)!==ue.nan){const n=this._getOrReturnCtx(t);return ae(n,{code:te.invalid_type,expected:ue.nan,received:n.parsedType}),xe}return{status:"valid",value:t.data}}}cf.create=e=>new cf({typeName:ne.ZodNaN,...Oe(e)});class R3 extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class ol extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"?(r.dirty(),Io(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?xe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new ol({in:t,out:r,typeName:ne.ZodPipeline})}}class sl extends Le{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Un(o)&&(o.value=Object.freeze(o.value)),o);return js(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}sl.create=(e,t)=>new sl({innerType:e,typeName:ne.ZodReadonly,...Oe(t)});var ne;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ne||(ne={}));const We=Kr.create,br=zn.create;Yr.create;const Xr=wr.create,or=mt.create,al=Us.create;zs.create,vn.create;const Vs=Vn.create;Fs.create,Qr.create,Bn.create;class uf 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 il(e){}function df(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=il,onError:r=il,onRetry:n=il,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[w,_]=P3(`${s}${y}`);for(const h of w)m(h);s=_,a=!1}function m(v){if(v===""){f();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const w=v.slice(0,y),_=v[y+1]===" "?2:1,h=v.slice(y+_);p(w,h,v);return}p(v,"",v)}function p(v,y,w){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
31
+ `;break;case"id":i=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new uf(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new uf(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:y,line:w}));break}}function f(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
32
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function g(v={}){s&&v.consume&&m(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:g}}function P3(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
33
+ `,n);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){r=e.slice(n);break}else{const i=e.slice(n,a);t.push(i),n=a+1,e[n-1]==="\r"&&e[n]===`
34
+ `&&n++}}return[t,r]}class Hn extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=df({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}function Pt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function N3({tools:e=[],providerToolNames:t}){const r={},n={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];r[o.name]=s,n[s]=o.name}return{toProviderToolName:o=>{var s;return(s=r[o])!=null?s:o},toCustomToolName:o=>{var s;return(s=n[o])!=null?s:o}}}async function M3(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(pf());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(pf())};r?.addEventListener("abort",i)})}function pf(){return new DOMException("Delay was aborted","AbortError")}var $o=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 Jn(e){return Object.fromEntries([...e.headers])}var{btoa:O3,atob:A3}=globalThis;function Gn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=A3(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Wn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return O3(t)}function Kn(e){return e instanceof Uint8Array?Wn(e):e}function q3(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){n.append(o,s[0]);continue}const a=r?`${o}[]`:o;for(const i of s)n.append(a,i);continue}n.append(o,s)}return n}var ff="AI_DownloadError",hf=`vercel.ai.error.${ff}`,L3=Symbol.for(hf),mf,gf,en=class extends(gf=me,mf=L3,gf){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:ff,message:o,cause:n}),this[mf]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return me.hasMarker(e,hf)}},ll=2*1024*1024*1024;async function yf({response:e,url:t,maxBytes:r=ll}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let i=0;try{for(;;){const{done:u,value:m}=await s.read();if(u)break;if(i+=m.length,i>r)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(m)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(i);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}async function _f(e,t){var r,n;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new en({url:e,statusCode:o.status,statusText:o.statusText});const s=await yf({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:ll}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw en.isInstance(o)?o:new en({url:e,cause:o})}}var Ro=({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 pd({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Ot=Ro();function cl(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var j3=["fetch failed","failed to fetch"],D3=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function U3(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&D3.includes(t))}function vf({error:e,url:t,requestBodyValues:r}){if(wn(e))return e;if(e instanceof TypeError&&j3.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new st({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return U3(e)?new st({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Po(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 z3(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 tn(e,...t){const r=new Headers(z3(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var wf="4.0.15",F3=()=>globalThis.fetch,bf=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=F3()})=>{try{const a=await s(e,{method:"GET",headers:tn(t,`ai-sdk/provider-utils/${wf}`,Po()),signal:o}),i=Jn(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw wn(c)||st.isInstance(c)?c:new st({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(wn(l)||st.isInstance(l))?l:new st({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw vf({error:a,url:e,requestBodyValues:{}})}};function V3(e){return e!=null}function Z3({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 B3({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Is({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Is({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 Is({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Is({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Yn({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 H3(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 J3=/"__proto__"\s*:/,G3=/"constructor"\s*:/;function kf(e){const t=JSON.parse(e);return t===null||typeof t!="object"||J3.test(e)===!1&&G3.test(e)===!1?t:W3(t)}function W3(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 ul(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return kf(e)}try{return kf(e)}finally{Error.stackTraceLimit=t}}function dl(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=bn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(bn):bn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(bn)),e.allOf!=null&&(e.allOf=e.allOf.map(bn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(bn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=bn(t[r]);return e}function bn(e){return typeof e=="boolean"?e:dl(e)}var K3=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"},Y3=e=>typeof e=="string"?{...Cf,name:e}:{...Cf,...e};function Bt(){return{}}function Q3(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==ne.ZodAny&&(s.items=Ve(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function X3(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 e9(){return{type:"boolean"}}function Tf(e,t){return Ve(e.type._def,t)}var t9=(e,t)=>Ve(e.innerType._def,t);function Sf(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Sf(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 r9(e)}}var r9=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 n9(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function o9(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Bt()}function s9(e){return{type:"string",enum:Array.from(e.values)}}var a9=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function i9(e,t){const r=[Ve(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ve(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(a9(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 l9(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 pl=void 0,sr={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:()=>(pl===void 0&&(pl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pl),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 If(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":ar(r,"email",n.message,t);break;case"format:idn-email":ar(r,"idn-email",n.message,t);break;case"pattern:zod":At(r,sr.email,n.message,t);break}break;case"url":ar(r,"uri",n.message,t);break;case"uuid":ar(r,"uuid",n.message,t);break;case"regex":At(r,n.regex,n.message,t);break;case"cuid":At(r,sr.cuid,n.message,t);break;case"cuid2":At(r,sr.cuid2,n.message,t);break;case"startsWith":At(r,RegExp(`^${fl(n.value,t)}`),n.message,t);break;case"endsWith":At(r,RegExp(`${fl(n.value,t)}$`),n.message,t);break;case"datetime":ar(r,"date-time",n.message,t);break;case"date":ar(r,"date",n.message,t);break;case"time":ar(r,"time",n.message,t);break;case"duration":ar(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":{At(r,RegExp(fl(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&ar(r,"ipv4",n.message,t),n.version!=="v4"&&ar(r,"ipv6",n.message,t);break}case"base64url":At(r,sr.base64url,n.message,t);break;case"jwt":At(r,sr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&At(r,sr.ipv4Cidr,n.message,t),n.version!=="v4"&&At(r,sr.ipv6Cidr,n.message,t);break}case"emoji":At(r,sr.emoji(),n.message,t);break;case"ulid":{At(r,sr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ar(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{At(r,sr.base64,n.message,t);break}}break}case"nanoid":At(r,sr.nanoid,n.message,t)}return r}function fl(e,t){return t.patternStrategy==="escape"?u9(e):e}var c9=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function u9(e){let t="";for(let r=0;r<e.length;r++)c9.has(e[r])||(t+="\\"),t+=e[r];return t}function ar(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 At(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:xf(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=xf(t,n)}function xf(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
35
35
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
36
- ]))`;continue}}if(n.s&&o[c]==="."){s+=a?`${o[c]}\r
36
+ ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
37
37
  `:`[${o[c]}\r
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 kd(e,t){var r,n,o,s,i,a;const l={type:"object",additionalProperties:(r=Te(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===Y.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=bd(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Y.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===Y.ZodBranded&&e.keyType._def.type._def.typeName===Y.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=vd(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function gw(e,t){if(t.mapStrategy==="record")return kd(e,t);const r=Te(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ft(),n=Te(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ft();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function _w(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 yw(){return{not:ft()}}function vw(){return{type:"null"}}var La={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ww(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in La&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const i=La[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 bw(e,t)}var bw=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Te(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 Sw(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[La[e.innerType._def.typeName],"null"]};const r=Te(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function kw(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 Cw(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=Ew(a),c=Te(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=$w(e,t);return s!==void 0&&(r.additionalProperties=s),r}function $w(e,t){if(e.catchall._def.typeName!=="ZodNever")return Te(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 Ew(e){try{return e.isOptional()}catch{return!0}}var Tw=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Te(e.innerType._def,t);const n=Te(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ft()},n]}:ft()},Iw=(e,t)=>{if(t.pipeStrategy==="input")return Te(e.in._def,t);if(t.pipeStrategy==="output")return Te(e.out._def,t);const r=Te(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Te(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function xw(e,t){return Te(e.type._def,t)}function Rw(e,t){const n={type:"array",uniqueItems:!0,items:Te(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 Pw(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Te(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Te(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Te(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Ow(){return{not:ft()}}function Mw(){return ft()}var Nw=(e,t)=>Te(e.innerType._def,t),Aw=(e,t,r)=>{switch(t){case Y.ZodString:return bd(e,r);case Y.ZodNumber:return kw(e);case Y.ZodObject:return Cw(e,r);case Y.ZodBigInt:return ow(e);case Y.ZodBoolean:return sw();case Y.ZodDate:return wd(e,r);case Y.ZodUndefined:return Ow();case Y.ZodNull:return vw();case Y.ZodArray:return nw(e,r);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return ww(e,r);case Y.ZodIntersection:return pw(e,r);case Y.ZodTuple:return Pw(e,r);case Y.ZodRecord:return kd(e,r);case Y.ZodLiteral:return fw(e);case Y.ZodEnum:return uw(e);case Y.ZodNativeEnum:return _w(e);case Y.ZodNullable:return Sw(e,r);case Y.ZodOptional:return Tw(e,r);case Y.ZodMap:return gw(e,r);case Y.ZodSet:return Rw(e,r);case Y.ZodLazy:return()=>e.getter()._def;case Y.ZodPromise:return xw(e,r);case Y.ZodNaN:case Y.ZodNever:return yw();case Y.ZodEffects:return cw(e,r);case Y.ZodAny:return ft();case Y.ZodUnknown:return Mw();case Y.ZodDefault:return lw(e,r);case Y.ZodBranded:return vd(e,r);case Y.ZodReadonly:return Nw(e,r);case Y.ZodCatch:return aw(e,r);case Y.ZodPipeline:return Iw(e,r);case Y.ZodFunction:case Y.ZodVoid:case Y.ZodSymbol:return;default:return(n=>{})()}};function Te(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!==tw)return l}if(o&&!r){const l=qw(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=Aw(e,e.typeName,t),a=typeof i=="function"?Te(i(),t):i;if(a&&Lw(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var qw=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ew(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`),ft()):t.$refStrategy==="seen"?ft():void 0}},Lw=(e,t,r)=>(e.description&&(r.description=e.description),r),jw=e=>{const t=rw(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}]))}},Uw=(e,t)=>{var r;const n=jw(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,_])=>{var f;return{...c,[u]:(f=Te(_._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?f:ft()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Te(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:ft(),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},Dw=Uw;function zw(e,t){var r;const n=(r=void 0)!=null?r:!1;return Pn(()=>Dw(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 Zw(e,t){var r;const n=(r=void 0)!=null?r:!1;return Pn(()=>Vu(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 Fw(e){return"_zod"in e}function Er(e,t){return Fw(e)?Zw(e):zw(e)}var ja=Symbol.for("vercel.ai.schema");function Pn(e,{validate:t}={}){return{[ja]:!0,_type:void 0,[To]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Vw(e){return typeof e=="object"&&e!==null&&ja in e&&e[ja]===!0&&"jsonSchema"in e&&"validate"in e}function Io(e){return e==null?Pn({properties:{},additionalProperties:!1}):Vw(e)?e:typeof e=="function"?e():Er(e)}var{btoa:Bw,atob:Hw}=globalThis;function Ua(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=Hw(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function xo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return Bw(t)}function Jw(e){return e instanceof Uint8Array?xo(e):e}function Cd(e){return e?.replace(/\/$/,"")}function Gw(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*$d({execute:e,input:t,options:r}){const n=e(t,r);if(Gw(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 Da(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var za,Ed;function Ww(){if(Ed)return za;Ed=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,_)=>{for(var f in _)e(u,f,{get:_[f],enumerable:!0})},s=(u,_,f,d)=>{if(_&&typeof _=="object"||typeof _=="function")for(let p of r(_))!n.call(u,p)&&p!==f&&e(u,p,{get:()=>_[p],enumerable:!(d=t(_,p))||d.enumerable});return u},i=u=>s(e({},"__esModule",{value:!0}),u),a={};o(a,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),za=i(a);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return za}var Za,Td;function Kw(){if(Td)return Za;Td=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(_,f)=>{for(var d in f)e(_,d,{get:f[d],enumerable:!0})},s=(_,f,d,p)=>{if(f&&typeof f=="object"||typeof f=="function")for(let v of r(f))!n.call(_,v)&&v!==d&&e(_,v,{get:()=>f[v],enumerable:!(p=t(f,v))||p.enumerable});return _},i=_=>s(e({},"__esModule",{value:!0}),_),a={};o(a,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Za=i(a);var l=Ww();async function c(){return""}function u(){return""}return Za}var Id=Kw(),Yw="vercel.ai.gateway.error",Fa=Symbol.for(Yw),xd,Rd,ht=class E1 extends(Rd=Error,xd=Fa,Rd){constructor({message:t,statusCode:r=500,cause:n}){super(t),this[xd]=!0,this.statusCode=r,this.cause=n}static isInstance(t){return E1.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Fa in t&&t[Fa]===!0}},Pd="GatewayAuthenticationError",Qw=`vercel.ai.gateway.error.${Pd}`,Od=Symbol.for(Qw),Md,Nd,Va=class T1 extends(Nd=ht,Md=Od,Nd){constructor({message:t="Authentication failed",statusCode:r=401,cause:n}={}){super({message:t,statusCode:r,cause:n}),this[Md]=!0,this.name=Pd,this.type="authentication_error"}static isInstance(t){return ht.hasMarker(t)&&Od 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.
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 Ef(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===ne.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=If(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===ne.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===ne.ZodBranded&&e.keyType._def.type._def.typeName===ne.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=Tf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function d9(e,t){if(t.mapStrategy==="record")return Ef(e,t);const r=Ve(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Bt(),n=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Bt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function p9(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 f9(){return{not:Bt()}}function h9(){return{type:"null"}}var hl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function m9(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in hl&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=hl[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 g9(e,t)}var g9=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ve(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function y9(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[hl[e.innerType._def.typeName],"null"]};const r=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function _9(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 v9(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=b9(i),c=Ve(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=w9(e,t);return s!==void 0&&(r.additionalProperties=s),r}function w9(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ve(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function b9(e){try{return e.isOptional()}catch{return!0}}var k9=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Ve(e.innerType._def,t);const n=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Bt()},n]}:Bt()},C9=(e,t)=>{if(t.pipeStrategy==="input")return Ve(e.in._def,t);if(t.pipeStrategy==="output")return Ve(e.out._def,t);const r=Ve(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ve(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function T9(e,t){return Ve(e.type._def,t)}function S9(e,t){const n={type:"array",uniqueItems:!0,items:Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function I9(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ve(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ve(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function x9(){return{not:Bt()}}function E9(){return Bt()}var $9=(e,t)=>Ve(e.innerType._def,t),R9=(e,t,r)=>{switch(t){case ne.ZodString:return If(e,r);case ne.ZodNumber:return _9(e);case ne.ZodObject:return v9(e,r);case ne.ZodBigInt:return X3(e);case ne.ZodBoolean:return e9();case ne.ZodDate:return Sf(e,r);case ne.ZodUndefined:return x9();case ne.ZodNull:return h9();case ne.ZodArray:return Q3(e,r);case ne.ZodUnion:case ne.ZodDiscriminatedUnion:return m9(e,r);case ne.ZodIntersection:return i9(e,r);case ne.ZodTuple:return I9(e,r);case ne.ZodRecord:return Ef(e,r);case ne.ZodLiteral:return l9(e);case ne.ZodEnum:return s9(e);case ne.ZodNativeEnum:return p9(e);case ne.ZodNullable:return y9(e,r);case ne.ZodOptional:return k9(e,r);case ne.ZodMap:return d9(e,r);case ne.ZodSet:return S9(e,r);case ne.ZodLazy:return()=>e.getter()._def;case ne.ZodPromise:return T9(e,r);case ne.ZodNaN:case ne.ZodNever:return f9();case ne.ZodEffects:return o9(e,r);case ne.ZodAny:return Bt();case ne.ZodUnknown:return E9();case ne.ZodDefault:return n9(e,r);case ne.ZodBranded:return Tf(e,r);case ne.ZodReadonly:return $9(e,r);case ne.ZodCatch:return t9(e,r);case ne.ZodPipeline:return C9(e,r);case ne.ZodFunction:case ne.ZodVoid:case ne.ZodSymbol:return;default:return(n=>{})()}},P9=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Ve(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==K3)return l}if(o&&!r){const l=N9(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=R9(e,e.typeName,t),i=typeof a=="function"?Ve(a(),t):a;if(i&&M9(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var N9=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:P9(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}},M9=(e,t,r)=>(e.description&&(r.description=e.description),r),O9=e=>{const t=Y3(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}]))}},A9=(e,t)=>{var r;const n=O9(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,m])=>{var p;return{...c,[u]:(p=Ve(m._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:Bt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Ve(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:Bt(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},ml=Symbol.for("vercel.ai.schema");function be(e){let t;return()=>(t==null&&(t=e()),t)}function Qn(e,{validate:t}={}){return{[ml]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function q9(e){return typeof e=="object"&&e!==null&&ml in e&&e[ml]===!0&&"jsonSchema"in e&&"validate"in e}function kn(e){return e==null?Qn({properties:{},additionalProperties:!1}):q9(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?we(e):L9(e):e()}function L9(e){return Qn(()=>dl(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new gn({value:t,cause:r.issues})}}})}function j9(e,t){var r;const n=(r=void 0)!=null?r:!1;return Qn(()=>A9(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 D9(e,t){var r;const n=(r=void 0)!=null?r:!1;return Qn(()=>dl(nb(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await xp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function U9(e){return"_zod"in e}function we(e,t){return U9(e)?D9(e):j9(e)}async function Tt({value:e,schema:t,context:r}){const n=await Yt({value:e,schema:t,context:r});if(!n.success)throw gn.wrap({value:e,cause:n.error,context:r});return n.value}async function Yt({value:e,schema:t,context:r}){const n=kn(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:gn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:gn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function z9({text:e,schema:t}){try{const r=ul(e);return t==null?r:Tt({value:r,schema:t})}catch(r){throw Ss.isInstance(r)||gn.isInstance(r)?r:new Ss({text:e,cause:r})}}async function Qt({text:e,schema:t}){try{const r=ul(e);return t==null?{success:!0,value:r,rawValue:r}:await Yt({value:r,schema:t})}catch(r){return{success:!1,error:Ss.isInstance(r)?r:new Ss({text:e,cause:r}),rawValue:void 0}}}function $f(e){try{return ul(e),!0}catch{return!1}}function Rf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Qt({text:r,schema:t}))}}))}async function Pr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Yt({value:t[e],schema:r});if(!n.success)throw new pd({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var F9=()=>globalThis.fetch,Dt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Nf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Pf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Nf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),Nf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=F9()})=>{try{const i=await a(e,{method:"POST",headers:tn(t,`ai-sdk/provider-utils/${wf}`,Po()),body:r.content,signal:s}),l=Jn(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw wn(u)||st.isInstance(u)?u:new st({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(wn(c)||st.isInstance(c))?c:new st({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw vf({error:i,url:e,requestBodyValues:r.values})}};function EE(e){return e}function Mf(e){return{...e,type:"dynamic"}}function ir({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Ut(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var rn=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Jn(n);if(a.trim()==="")return{responseHeaders:i,value:new st({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await z9({text:a,schema:e});return{responseHeaders:i,value:new st({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new st({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Zs=e=>async({response:t})=>{const r=Jn(t);if(t.body==null)throw new tv({});return{responseHeaders:r,value:Rf({stream:t.body,schema:e})}},Xt=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Qt({text:o,schema:e}),a=Jn(t);if(!s.success)throw new st({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},V9=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Jn(e);if(!e.body)throw new st({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new st({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function Of(e){return e?.replace(/\/$/,"")}function Z9(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*B9({execute:e,input:t,options:r}){const n=e(t,r);if(Z9(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 gl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var yl,Af;function H9(){if(Af)return yl;Af=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,m)=>{for(var p in m)e(u,p,{get:m[p],enumerable:!0})},s=(u,m,p,f)=>{if(m&&typeof m=="object"||typeof m=="function")for(let g of r(m))!n.call(u,g)&&g!==p&&e(u,g,{get:()=>m[g],enumerable:!(f=t(m,g))||f.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),yl=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return yl}var _l,qf;function J9(){if(qf)return _l;qf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(m,p)=>{for(var f in p)e(m,f,{get:p[f],enumerable:!0})},s=(m,p,f,g)=>{if(p&&typeof p=="object"||typeof p=="function")for(let v of r(p))!n.call(m,v)&&v!==f&&e(m,v,{get:()=>p[v],enumerable:!(g=t(p,v))||g.enumerable});return m},a=m=>s(e({},"__esModule",{value:!0}),m),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),_l=a(i);var l=H9();async function c(){return""}function u(){return""}return _l}var Lf=J9(),G9="vercel.ai.gateway.error",vl=Symbol.for(G9),jf,Df,qt=class G_ extends(Df=Error,jf=vl,Df){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[jf]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return G_.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&vl in t&&t[vl]===!0}},Uf="GatewayAuthenticationError",W9=`vercel.ai.gateway.error.${Uf}`,zf=Symbol.for(W9),Ff,Vf,wl=class W_ extends(Vf=qt,Ff=zf,Vf){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Ff]=!0,this.name=Uf,this.type="authentication_error"}static isInstance(t){return qt.hasMarker(t)&&zf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
39
39
 
40
40
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
41
41
 
@@ -50,41 +50,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 T1({message:i,statusCode:o,cause:s})}},Ad="GatewayInvalidRequestError",Xw=`vercel.ai.gateway.error.${Ad}`,qd=Symbol.for(Xw),Ld,jd,eb=class extends(jd=ht,Ld=qd,jd){constructor({message:e="Invalid request",statusCode:t=400,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Ld]=!0,this.name=Ad,this.type="invalid_request_error"}static isInstance(e){return ht.hasMarker(e)&&qd in e}},Ud="GatewayRateLimitError",tb=`vercel.ai.gateway.error.${Ud}`,Dd=Symbol.for(tb),zd,Zd,rb=class extends(Zd=ht,zd=Dd,Zd){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[zd]=!0,this.name=Ud,this.type="rate_limit_exceeded"}static isInstance(e){return ht.hasMarker(e)&&Dd in e}},Fd="GatewayModelNotFoundError",nb=`vercel.ai.gateway.error.${Fd}`,Vd=Symbol.for(nb),ob=Hr(()=>Er($({modelId:h()}))),Bd,Hd,Jd=class extends(Hd=ht,Bd=Vd,Hd){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Bd]=!0,this.name=Fd,this.type="model_not_found",this.modelId=r}static isInstance(e){return ht.hasMarker(e)&&Vd in e}},Gd="GatewayInternalServerError",sb=`vercel.ai.gateway.error.${Gd}`,Wd=Symbol.for(sb),Kd,Yd,Qd=class extends(Yd=ht,Kd=Wd,Yd){constructor({message:e="Internal server error",statusCode:t=500,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Kd]=!0,this.name=Gd,this.type="internal_server_error"}static isInstance(e){return ht.hasMarker(e)&&Wd in e}},Xd="GatewayResponseError",ab=`vercel.ai.gateway.error.${Xd}`,ep=Symbol.for(ab),tp,rp,ib=class extends(rp=ht,tp=ep,rp){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[tp]=!0,this.name=Xd,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return ht.hasMarker(e)&&ep in e}};async function np({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){const s=await $t({value:e,schema:lb});if(!s.success)return new ib({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 Va.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n});case"invalid_request_error":return new eb({message:l,statusCode:t,cause:n});case"rate_limit_exceeded":return new rb({message:l,statusCode:t,cause:n});case"model_not_found":{const c=await $t({value:i.error.param,schema:ob});return new Jd({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new Qd({message:l,statusCode:t,cause:n});default:return new Qd({message:l,statusCode:t,cause:n})}}var lb=Hr(()=>Er($({error:$({message:h(),type:h().nullish(),param:ke().nullish(),code:re([h(),A()]).nullish()})})));function cr(e,t){var r;return ht.isInstance(e)?e:et.isInstance(e)?np({response:cb(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):np({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function cb(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 op="ai-gateway-auth-method";async function Wr(e){const t=await $t({value:e[op],schema:ub});return t.success?t.value:void 0}var ub=Hr(()=>Er(re([q("api-key"),q("oidc")]))),sp=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await pd({url:`${this.config.baseURL}/config`,headers:await jt(this.config.headers()),successfulResponseHandler:Gr(db),failedResponseHandler:$r({errorSchema:tt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await cr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await pd({url:`${e.origin}/v1/credits`,headers:await jt(this.config.headers()),successfulResponseHandler:Gr(pb),failedResponseHandler:$r({errorSchema:tt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await cr(e)}}},db=Hr(()=>Er($({models:N($({id:h(),name:h(),description:h().nullish(),pricing:$({input:h(),output:h(),input_cache_read:h().nullish(),input_cache_write:h().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:$({specificationVersion:q("v2"),provider:h(),modelId:h()}),modelType:be(["language","embedding","image"]).nullish()}))}))),pb=Hr(()=>Er($({balance:h(),total_used:h()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),fb=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 Jr({url:this.getUrl(),headers:Br(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await jt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Gr(tt()),failedResponseHandler:$r({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 cr(s,await Wr(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 Jr({url:this.getUrl(),headers:Br(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await jt(this.config.o11yHeaders)),body:t,successfulResponseHandler:_d(tt()),failedResponseHandler:$r({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 cr(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)}}},hb=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 Jr({url:this.getUrl(),headers:Br(s,t??{},this.getModelConfigHeaders(),await jt(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Gr(mb),failedResponseHandler:$r({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 cr(i,await Wr(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},mb=Hr(()=>Er($({embeddings:N(N(A())),usage:$({tokens:A()}).nullish(),providerMetadata:me(h(),me(h(),ke())).optional()}))),gb=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:_,rawValue:f}=await Jr({url:this.getUrl(),headers:Br(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:Gr(yb),failedResponseHandler:$r({errorSchema:tt(),errorToMessage:d=>d}),...a&&{abortSignal:a},fetch:this.config.fetch});return{images:_.images,warnings:(l=_.warnings)!=null?l:[],providerMetadata:_.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw cr(u,await Wr(c))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},_b=$({images:N(ke()).optional()}).catchall(ke()),yb=$({images:N(h()),warnings:N($({type:q("other"),message:h()})).optional(),providerMetadata:me(h(),_b).optional()});async function vb(){var e;return(e=Id.getContext().headers)==null?void 0:e["x-vercel-id"]}var wb="2.0.18",bb="0.0.1";function Sb(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=Cd(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const p=await Cb(e);if(p)return lr({Authorization:`Bearer ${p.token}`,"ai-gateway-protocol-version":bb,[op]:p.authMethod,...e.headers},`ai-sdk/gateway/${wb}`);throw Va.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const p=Eo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=Eo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=Eo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const w=await vb();return{...p&&{"ai-o11y-deployment-id":p},...v&&{"ai-o11y-environment":v},...m&&{"ai-o11y-region":m},...w&&{"ai-o11y-request-id":w}}}},u=p=>new fb(p,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),_=async()=>{var p,v,m;const w=(m=(v=(p=e._internal)==null?void 0:p.currentDate)==null?void 0:v.call(p).getTime())!=null?m:Date.now();return(!n||w-i>s)&&(i=w,n=new sp({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(g=>(o=g,g)).catch(async g=>{throw await cr(g,await Wr(await l()))})),o?Promise.resolve(o):n},f=async()=>new sp({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async p=>{throw await cr(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=_,d.getCredits=f,d.imageModel=p=>new gb(p,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),d.languageModel=u,d.textEmbeddingModel=p=>new hb(p,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),d}var kb=Sb();async function Cb(e){const t=Eo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Id.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var $b=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Tr="1.9.0",ap=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Eb(e){var t=new Set([e]),r=new Set,n=e.match(ap);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(ap);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 Tb=Eb(Tr),Ib=Tr.split(".")[0],On=Symbol.for("opentelemetry.js.api."+Ib),Mn=$b;function Nn(e,t,r,n){var o;n===void 0&&(n=!1);var s=Mn[On]=(o=Mn[On])!==null&&o!==void 0?o:{version:Tr};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!==Tr){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Tr);return r.error(i.stack||i.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Tr+"."),!0}function Ir(e){var t,r,n=(t=Mn[On])===null||t===void 0?void 0:t.version;if(!(!n||!Tb(n)))return(r=Mn[On])===null||r===void 0?void 0:r[e]}function An(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Tr+".");var r=Mn[On];r&&delete r[e]}var xb=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},Rb=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))},Pb=(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 qn("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qn("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qn("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qn("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qn("verbose",this._namespace,t)},e})();function qn(e,t,r){var n=Ir("diag");if(n)return r.unshift(t),n[e].apply(n,Rb([],xb(r),!1))}var mt;(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"})(mt||(mt={}));function Ob(e,t){e<mt.NONE?e=mt.NONE:e>mt.ALL&&(e=mt.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",mt.ERROR),warn:r("warn",mt.WARN),info:r("info",mt.INFO),debug:r("debug",mt.DEBUG),verbose:r("verbose",mt.VERBOSE)}}var Mb=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},Nb=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))},Ab="diag",Ut=(function(){function e(){function t(o){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Ir("diag");if(a)return a[o].apply(a,Nb([],Mb(s),!1))}}var r=this,n=function(o,s){var i,a,l;if(s===void 0&&(s={logLevel:mt.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=Ir("diag"),_=Ob((a=s.logLevel)!==null&&a!==void 0?a:mt.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),_.warn("Current logger will overwrite one already registered from "+f)}return Nn("diag",_,r,!0)};r.setLogger=n,r.disable=function(){An(Ab,r)},r.createComponentLogger=function(o){return new Pb(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})(),qb=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},Lb=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.")},jb=(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=qb(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=Lb(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})();Ut.instance();function Ub(e){return e===void 0&&(e={}),new jb(new Map(Object.entries(e)))}function ip(e){return Symbol.for(e)}var Db=(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})(),zb=new Db,xr=(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)}})(),Zb=(function(){function e(){}return e.prototype.createGauge=function(t,r){return Qb},e.prototype.createHistogram=function(t,r){return Xb},e.prototype.createCounter=function(t,r){return Yb},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})(),Ro=(function(){function e(){}return e})(),Fb=(function(e){xr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Ro),Vb=(function(e){xr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Ro),Bb=(function(e){xr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Ro),Hb=(function(e){xr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Ro),Ba=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),Jb=(function(e){xr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ba),Gb=(function(e){xr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ba),Wb=(function(e){xr(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Ba),Kb=new Zb,Yb=new Fb,Qb=new Bb,Xb=new Hb,e3=new Vb,t3=new Jb,r3=new Gb,n3=new Wb,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=[],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},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 zb},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=[],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},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))},Ha="context",d3=new l3,Po=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Nn(Ha,t,Ut.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,u3([t,r,n],c3(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return Ir(Ha)||d3},e.prototype.disable=function(){this._getContextManager().disable(),An(Ha,Ut.instance())},e})(),Ja;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ja||(Ja={}));var lp="0000000000000000",cp="00000000000000000000000000000000",p3={traceId:cp,spanId:lp,traceFlags:Ja.NONE},Ln=(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})(),Ga=ip("OpenTelemetry Context Key SPAN");function Wa(e){return e.getValue(Ga)||void 0}function f3(){return Wa(Po.getInstance().active())}function Ka(e,t){return e.setValue(Ga,t)}function h3(e){return e.deleteValue(Ga)}function m3(e,t){return Ka(e,new Ln(t))}function up(e){var t;return(t=Wa(e))===null||t===void 0?void 0:t.spanContext()}var g3=/^([0-9a-f]{32})$/i,_3=/^[0-9a-f]{16}$/i;function y3(e){return g3.test(e)&&e!==cp}function v3(e){return _3.test(e)&&e!==lp}function dp(e){return y3(e.traceId)&&v3(e.spanId)}function w3(e){return new Ln(e)}var Ya=Po.getInstance(),pp=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Ya.active());var o=!!r?.root;if(o)return new Ln;var s=n&&up(n);return b3(s)&&dp(s)?new Ln(s):new Ln},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??Ya.active(),c=this.startSpan(t,s,l),u=Ka(l,c);return Ya.with(u,a,void 0,c)}},e})();function b3(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var S3=new pp,k3=(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):S3},e})(),C3=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new pp},e})(),$3=new C3,fp=(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 k3(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:$3},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})(),Oo;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Oo||(Oo={})),Po.getInstance(),Ut.instance();var E3=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return Kb},e})(),T3=new E3,Qa="metrics",I3=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Nn(Qa,t,Ut.instance())},e.prototype.getMeterProvider=function(){return Ir(Qa)||T3},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){An(Qa,Ut.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})(),Xa=ip("OpenTelemetry Baggage Key");function hp(e){return e.getValue(Xa)||void 0}function R3(){return hp(Po.getInstance().active())}function P3(e,t){return e.setValue(Xa,t)}function O3(e){return e.deleteValue(Xa)}var ei="propagation",M3=new x3,N3=(function(){function e(){this.createBaggage=Ub,this.getBaggage=hp,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 Nn(ei,t,Ut.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(){An(ei,Ut.instance())},e.prototype._getGlobalPropagator=function(){return Ir(ei)||M3},e})();N3.getInstance();var ti="trace",A3=(function(){function e(){this._proxyTracerProvider=new fp,this.wrapSpanContext=w3,this.isSpanContextValid=dp,this.deleteSpan=h3,this.getSpan=Wa,this.getActiveSpan=f3,this.getSpanContext=up,this.setSpan=Ka,this.setSpanContext=m3}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Nn(ti,this._proxyTracerProvider,Ut.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return Ir(ti)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){An(ti,Ut.instance()),this._proxyTracerProvider=new fp},e})(),q3=A3.getInstance(),L3=Object.defineProperty,j3=(e,t)=>{for(var r in t)L3(e,r,{get:t[r],enumerable:!0})},mp="AI_NoOutputSpecifiedError",gp=`vercel.ai.error.${mp}`,U3=Symbol.for(gp),_p,yp=class extends he{constructor({message:e="No output specified."}={}){super({name:mp,message:e}),this[_p]=!0}static isInstance(e){return he.hasMarker(e,gp)}};_p=U3;function D3(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 z3="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",vp=!1,wp=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}vp||(vp=!0,console.info(z3));for(const r of e)console.warn(D3(r))}},bp="AI_InvalidArgumentError",Sp=`vercel.ai.error.${bp}`,Z3=Symbol.for(Sp),kp,Dt=class extends he{constructor({parameter:t,value:r,message:n}){super({name:bp,message:`Invalid argument for parameter ${t}: ${n}`}),this[kp]=!0,this.parameter=t,this.value=r}static isInstance(t){return he.hasMarker(t,Sp)}};kp=Z3;var Cp="AI_InvalidToolInputError",$p=`vercel.ai.error.${Cp}`,F3=Symbol.for($p),Ep,Tp=class extends he{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${Zr(r)}`}){super({name:Cp,message:n,cause:r}),this[Ep]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return he.hasMarker(e,$p)}};Ep=F3;var Ip="AI_NoObjectGeneratedError",xp=`vercel.ai.error.${Ip}`,V3=Symbol.for(xp),Rp,Pp=class extends he{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Ip,message:e,cause:t}),this[Rp]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return he.hasMarker(e,xp)}};Rp=V3;var Op="AI_NoOutputGeneratedError",Mp=`vercel.ai.error.${Op}`,B3=Symbol.for(Mp),Np,H3=class extends he{constructor({message:e="No output generated.",cause:t}={}){super({name:Op,message:e,cause:t}),this[Np]=!0}static isInstance(e){return he.hasMarker(e,Mp)}};Np=B3;var Ap="AI_NoSuchToolError",qp=`vercel.ai.error.${Ap}`,J3=Symbol.for(qp),Lp,ri=class extends he{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Ap,message:r}),this[Lp]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return he.hasMarker(e,qp)}};Lp=J3;var jp="AI_ToolCallRepairError",Up=`vercel.ai.error.${jp}`,G3=Symbol.for(Up),Dp,W3=class extends he{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${Zr(e)}`}){super({name:jp,message:r,cause:e}),this[Dp]=!0,this.originalError=t}static isInstance(e){return he.hasMarker(e,Up)}};Dp=G3;var K3=class extends he{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},zp="AI_InvalidMessageRoleError",Zp=`vercel.ai.error.${zp}`,Y3=Symbol.for(Zp),Fp,Q3=class extends he{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:zp,message:t}),this[Fp]=!0,this.role=e}static isInstance(e){return he.hasMarker(e,Zp)}};Fp=Y3;var Vp="AI_DownloadError",Bp=`vercel.ai.error.${Vp}`,X3=Symbol.for(Bp),Hp,ni=class extends he{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:Vp,message:o,cause:n}),this[Hp]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return he.hasMarker(e,Bp)}};Hp=X3;var Jp="AI_RetryError",Gp=`vercel.ai.error.${Jp}`,e9=Symbol.for(Gp),Wp,Kp=class extends he{constructor({message:e,reason:t,errors:r}){super({name:Jp,message:e}),this[Wp]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return he.hasMarker(e,Gp)}};Wp=e9;function Mo(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new K3({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return t9().languageModel(e)}function t9(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:kb}var r9=[{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]}],n9=e=>{const t=typeof e=="string"?Ua(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function o9(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?n9(e):e}function s9({data:e,signatures:t}){const r=o9(e),n=typeof r=="string"?Ua(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 Yp="5.0.106",a9=async({url:e})=>{var t;const r=e.toString();try{const n=await fetch(r,{headers:lr({},`ai-sdk/${Yp}`,Rn())});if(!n.ok)throw new ni({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 ni.isInstance(n)?n:new ni({url:r,cause:n})}},i9=(e=a9)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function l9(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 Qp=re([h(),Co(Uint8Array),Co(ArrayBuffer),sd(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function Xp(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}=l9(e.toString());if(t==null||r==null)throw new he({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function c9(e){return typeof e=="string"?e:e instanceof ArrayBuffer?xo(new Uint8Array(e)):xo(e)}async function e0({prompt:e,supportedUrls:t,download:r=i9()}){const n=await d9(e.messages,r,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>u9({message:o,downloadedAssets:n}))]}function u9({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=>p9(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}=Xp(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 Q3({role:n})}}}async function d9(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&&zv({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 p9(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}=Xp(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=s9({data:l,signatures:r9}))!=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 oi({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 Dt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Dt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Dt({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Dt({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Dt({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Dt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Dt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new Dt({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 f9(e){return e!=null&&Object.keys(e).length>0}function t0({tools:e,toolChoice:t,activeTools:r}){return f9(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:Io(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 jn=od(()=>re([Ta(),h(),A(),ce(),me(h(),jn),N(jn)])),zt=me(h(),me(h(),jn)),r0=$({type:q("text"),text:h(),providerOptions:zt.optional()}),h9=$({type:q("image"),image:re([Qp,Co(URL)]),mediaType:h().optional(),providerOptions:zt.optional()}),n0=$({type:q("file"),data:re([Qp,Co(URL)]),filename:h().optional(),mediaType:h(),providerOptions:zt.optional()}),m9=$({type:q("reasoning"),text:h(),providerOptions:zt.optional()}),g9=$({type:q("tool-call"),toolCallId:h(),toolName:h(),input:ke(),providerOptions:zt.optional(),providerExecuted:ce().optional()}),_9=Ze("type",[$({type:q("text"),value:h()}),$({type:q("json"),value:jn}),$({type:q("error-text"),value:h()}),$({type:q("error-json"),value:jn}),$({type:q("content"),value:N(re([$({type:q("text"),text:h()}),$({type:q("media"),data:h(),mediaType:h()})]))})]),o0=$({type:q("tool-result"),toolCallId:h(),toolName:h(),output:_9,providerOptions:zt.optional()}),y9=$({role:q("system"),content:h(),providerOptions:zt.optional()}),v9=$({role:q("user"),content:re([h(),N(re([r0,h9,n0]))]),providerOptions:zt.optional()}),w9=$({role:q("assistant"),content:re([h(),N(re([r0,n0,m9,g9,o0]))]),providerOptions:zt.optional()}),b9=$({role:q("tool"),content:N(o0),providerOptions:zt.optional()}),S9=re([y9,v9,w9,b9]);async function s0(e){if(e.prompt==null&&e.messages==null)throw new Fr({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Fr({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Fr({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 Fr({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Fr({prompt:e,message:"messages must not be empty"});const r=await $t({value:t,schema:N(S9)});if(!r.success)throw new Fr({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 a0(e){return Va.isInstance(e)||Jd.isInstance(e)?new he({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 i0({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 k9={startSpan(){return No},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(No);if(typeof r=="function")return r(No);if(typeof n=="function")return n(No)}},No={spanContext(){return C9},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}},C9={traceId:"",spanId:"",traceFlags:0};function l0({isEnabled:e=!1,tracer:t}={}){return e?t||q3.getTracer("ai"):k9}function Yr({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{si(s,i)}finally{s.end()}throw i}})}function si(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Oo.ERROR,message:t.message})):e.setStatus({code:Oo.ERROR})}function vt({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 c0(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?c9(r.data):r.data}:r)})))}function u0(e,t){return{inputTokens:Un(e.inputTokens,t.inputTokens),outputTokens:Un(e.outputTokens,t.outputTokens),totalTokens:Un(e.totalTokens,t.totalTokens),reasoningTokens:Un(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Un(e.cachedInputTokens,t.cachedInputTokens)}}function Un(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ai(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function $9({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 E9=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>d0(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function d0(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(i){if(kr(i)||t===0)throw i;const a=Oa(i),l=[...s,i],c=l.length;if(c>t)throw new Kp({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&et.isInstance(i)&&i.isRetryable===!0&&c<=t)return await Lv($9({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),d0(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new Kp({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function p0({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Dt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Dt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:E9({maxRetries:r,abortSignal:t})}}function f0(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var h0=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=xo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Ua(this.base64Data)),this.uint8ArrayData}},T9=class extends h0{constructor(e){super(e),this.type="file"}};async function m0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){try{if(t==null)throw new ri({toolName:e.toolName});try{return await g0({toolCall:e,tools:t})}catch(s){if(r==null||!(ri.isInstance(s)||Tp.isInstance(s)))throw s;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:({toolName:a})=>{const{inputSchema:l}=t[a];return Io(l).jsonSchema},system:n,messages:o,error:s})}catch(a){throw new W3({cause:a,originalError:s})}if(i==null)throw s;return await g0({toolCall:i,tools:t})}}catch(s){const i=await Cr({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 g0({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null)throw new ri({toolName:e.toolName,availableTools:Object.keys(t)});const o=Io(n.inputSchema),s=e.input.trim()===""?await $t({value:{},schema:o}):await Cr({text:e.input,schema:o});if(s.success===!1)throw new Tp({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 _0=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 ii(e){return({steps:t})=>t.length===e}async function y0({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}function li({output:e,tool:t,errorMode:r}){return r==="text"?{type:"error-text",value:Zr(e)}:r==="json"?{type:"error-json",value:v0(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:v0(e)}}function v0(e){return e===void 0?null:e}function ci({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:li({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:li({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:li({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 I9=In({prefix:"aitxt",size:24});async function w0({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,headers:l,stopWhen:c=ii(1),experimental_output:u,experimental_telemetry:_,providerOptions:f,experimental_activeTools:d,activeTools:p=d,experimental_prepareStep:v,prepareStep:m=v,experimental_repairToolCall:w,experimental_download:g,experimental_context:y,_internal:{generateId:b=I9,currentDate:S=()=>new Date}={},onStepFinish:k,...C}){const I=Mo(e),R=ai(c),{maxRetries:L,retry:O}=p0({maxRetries:i,abortSignal:a}),U=oi(C),D=lr(l??{},`ai/${Yp}`),F=i0({model:I,telemetry:_,headers:D,settings:{...U,maxRetries:L}}),ee=await s0({system:n,prompt:o,messages:s}),ie=l0(_);try{return await Yr({name:"ai.generateText",attributes:vt({telemetry:_,attributes:{...Kr({operationId:"ai.generateText",telemetry:_}),...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 X,de,V,P,Z,j,T;const x=oi(C);let E,B=[],G=[];const pe=[],ae=[];do{const H=[...ee.messages,...pe],W=await m?.({model:I,steps:ae,stepNumber:ae.length,messages:H}),K=Mo((X=W?.model)!=null?X:I),oe=await e0({prompt:{system:(de=W?.system)!=null?de:ee.system,messages:(V=W?.messages)!=null?V:H},supportedUrls:await K.supportedUrls,download:g}),{toolChoice:le,tools:Me}=t0({tools:t,toolChoice:(P=W?.toolChoice)!=null?P:r,activeTools:(Z=W?.activeTools)!=null?Z:p});E=await O(()=>{var we;return Yr({name:"ai.generateText.doGenerate",attributes:vt({telemetry:_,attributes:{...Kr({operationId:"ai.generateText.doGenerate",telemetry:_}),...F,"ai.model.provider":K.provider,"ai.model.id":K.modelId,"ai.prompt.messages":{input:()=>c0(oe)},"ai.prompt.tools":{input:()=>Me?.map(dt=>JSON.stringify(dt))},"ai.prompt.toolChoice":{input:()=>le!=null?JSON.stringify(le):void 0},"gen_ai.system":K.provider,"gen_ai.request.model":K.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":(we=C.temperature)!=null?we:void 0,"gen_ai.request.top_k":C.topK,"gen_ai.request.top_p":C.topP}}),tracer:ie,fn:async dt=>{var rr,pt,Ye,Ct,vr,wr,_n,fa;const Be=await K.doGenerate({...x,tools:Me,toolChoice:le,responseFormat:u?.responseFormat,prompt:oe,providerOptions:f,abortSignal:a,headers:D}),nr={id:(pt=(rr=Be.response)==null?void 0:rr.id)!=null?pt:b(),timestamp:(Ct=(Ye=Be.response)==null?void 0:Ye.timestamp)!=null?Ct:S(),modelId:(wr=(vr=Be.response)==null?void 0:vr.modelId)!=null?wr:K.modelId,headers:(_n=Be.response)==null?void 0:_n.headers,body:(fa=Be.response)==null?void 0:fa.body};return dt.setAttributes(vt({telemetry:_,attributes:{"ai.response.finishReason":Be.finishReason,"ai.response.text":{output:()=>f0(Be.content)},"ai.response.toolCalls":{output:()=>{const or=b0(Be.content);return or==null?void 0:JSON.stringify(or)}},"ai.response.id":nr.id,"ai.response.model":nr.modelId,"ai.response.timestamp":nr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Be.providerMetadata),"ai.usage.promptTokens":Be.usage.inputTokens,"ai.usage.completionTokens":Be.usage.outputTokens,"gen_ai.response.finish_reasons":[Be.finishReason],"gen_ai.response.id":nr.id,"gen_ai.response.model":nr.modelId,"gen_ai.usage.input_tokens":Be.usage.inputTokens,"gen_ai.usage.output_tokens":Be.usage.outputTokens}})),{...Be,response:nr}}})});const Ae=await Promise.all(E.content.filter(we=>we.type==="tool-call").map(we=>m0({toolCall:we,tools:t,repairToolCall:w,system:n,messages:H})));for(const we of Ae){if(we.invalid)continue;const dt=t[we.toolName];dt?.onInputAvailable!=null&&await dt.onInputAvailable({input:we.input,toolCallId:we.toolCallId,messages:H,abortSignal:a,experimental_context:y})}const Q=Ae.filter(we=>we.invalid&&we.dynamic);G=[];for(const we of Q)G.push({type:"tool-error",toolCallId:we.toolCallId,toolName:we.toolName,input:we.input,error:Oa(we.error),dynamic:!0});B=Ae.filter(we=>!we.providerExecuted),t!=null&&G.push(...await x9({toolCalls:B.filter(we=>!we.invalid),tools:t,tracer:ie,telemetry:_,messages:H,abortSignal:a,experimental_context:y}));const ge=P9({content:E.content,toolCalls:Ae,toolOutputs:G});pe.push(...ci({content:ge,tools:t}));const at=new _0({content:ge,finishReason:E.finishReason,usage:E.usage,warnings:E.warnings,providerMetadata:E.providerMetadata,request:(j=E.request)!=null?j:{},response:{...E.response,messages:structuredClone(pe)}});wp((T=E.warnings)!=null?T:[]),ae.push(at),await k?.(at)}while(B.length>0&&G.length===B.length&&!await y0({stopConditions:R,steps:ae}));se.setAttributes(vt({telemetry:_,attributes:{"ai.response.finishReason":E.finishReason,"ai.response.text":{output:()=>f0(E.content)},"ai.response.toolCalls":{output:()=>{const H=b0(E.content);return H==null?void 0:JSON.stringify(H)}},"ai.response.providerMetadata":JSON.stringify(E.providerMetadata),"ai.usage.promptTokens":E.usage.inputTokens,"ai.usage.completionTokens":E.usage.outputTokens}}));const M=ae[ae.length-1];let z;return M.finishReason==="stop"&&(z=await u?.parseOutput({text:M.text},{response:M.response,usage:M.usage,finishReason:M.finishReason})),new R9({steps:ae,resolvedOutput:z})}})}catch(se){throw a0(se)}}async function x9({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 _=t[c];if(_?.execute!=null)return Yr({name:"ai.toolCall",attributes:vt({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 f=>{try{const d=$d({execute:_.execute.bind(_),input:u,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:i}});let p;for await(const v of d)v.type==="final"&&(p=v.output);try{f.setAttributes(vt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(p)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:p,dynamic:_.type==="dynamic"}}catch(d){return si(f,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:_.type==="dynamic"}}}})}))).filter(l=>l!=null)}var R9=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)=>u0(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 yp;return this.resolvedOutput}};function b0(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 P9({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 h0(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 Ao(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 O9({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Ao(r,{"content-type":"text/plain; charset=utf-8"})})}function S0({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 M9({response:e,status:t,statusText:r,headers:n,textStream:o}){S0({response:e,status:t,statusText:r,headers:Object.fromEntries(Ao(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var k0=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 W_({message:i,statusCode:o,cause:s,generationId:a})}},Zf="GatewayInvalidRequestError",K9=`vercel.ai.gateway.error.${Zf}`,Bf=Symbol.for(K9),Hf,Jf,Y9=class extends(Jf=qt,Hf=Bf,Jf){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Hf]=!0,this.name=Zf,this.type="invalid_request_error"}static isInstance(e){return qt.hasMarker(e)&&Bf in e}},Gf="GatewayRateLimitError",Q9=`vercel.ai.gateway.error.${Gf}`,Wf=Symbol.for(Q9),Kf,Yf,X9=class extends(Yf=qt,Kf=Wf,Yf){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Kf]=!0,this.name=Gf,this.type="rate_limit_exceeded"}static isInstance(e){return qt.hasMarker(e)&&Wf in e}},Qf="GatewayModelNotFoundError",e4=`vercel.ai.gateway.error.${Qf}`,Xf=Symbol.for(e4),t4=be(()=>we(T({modelId:d()}))),eh,th,r4=class extends(th=qt,eh=Xf,th){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[eh]=!0,this.name=Qf,this.type="model_not_found",this.modelId=r}static isInstance(e){return qt.hasMarker(e)&&Xf in e}},rh="GatewayInternalServerError",n4=`vercel.ai.gateway.error.${rh}`,nh=Symbol.for(n4),oh,sh,ah=class extends(sh=qt,oh=nh,sh){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[oh]=!0,this.name=rh,this.type="internal_server_error"}static isInstance(e){return qt.hasMarker(e)&&nh in e}},ih="GatewayResponseError",o4=`vercel.ai.gateway.error.${ih}`,lh=Symbol.for(o4),ch,uh,s4=class extends(uh=qt,ch=lh,uh){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[ch]=!0,this.name=ih,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return qt.hasMarker(e)&&lh in e}};async function dh({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await Yt({value:e,schema:a4});if(!a.success){const m=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new s4({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:m})}const i=a.value,l=i.error.type,c=i.error.message,u=(s=i.generationId)!=null?s:void 0;switch(l){case"authentication_error":return wl.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new Y9({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new X9({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const m=await Yt({value:i.error.param,schema:t4});return new r4({message:c,statusCode:t,modelId:m.success?m.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new ah({message:c,statusCode:t,cause:n,generationId:u});default:return new ah({message:c,statusCode:t,cause:n,generationId:u})}}var a4=be(()=>we(T({error:T({message:d(),type:d().nullish(),param:$e().nullish(),code:oe([d(),j()]).nullish()}),generationId:d().nullish()}))),ph="GatewayTimeoutError",i4=`vercel.ai.gateway.error.${ph}`,fh=Symbol.for(i4),hh,mh,gh=class K_ extends(mh=qt,hh=fh,mh){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[hh]=!0,this.name=ph,this.type="timeout_error"}static isInstance(t){return qt.hasMarker(t)&&fh in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
54
+
55
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new K_({message:s,statusCode:r,cause:n,generationId:o})}};function yh(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function Nr(e,t){var r;return qt.isInstance(e)?e:yh(e)?gh.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):st.isInstance(e)?e.cause&&yh(e.cause)?gh.createTimeoutError({originalMessage:e.message,cause:e}):await dh({response:l4(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await dh({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function l4(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 _h="ai-gateway-auth-method";async function Cn(e){const t=await Yt({value:e[_h],schema:c4});return t.success?t.value:void 0}var c4=be(()=>we(oe([$("api-key"),$("oidc")]))),vh=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await bf({url:`${this.config.baseURL}/config`,headers:await Ut(this.config.headers()),successfulResponseHandler:Xt(u4),failedResponseHandler:rn({errorSchema:vt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Nr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await bf({url:`${e.origin}/v1/credits`,headers:await Ut(this.config.headers()),successfulResponseHandler:Xt(d4),failedResponseHandler:rn({errorSchema:vt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await Nr(e)}}},u4=be(()=>we(T({models:q(T({id:d(),name:d(),description:d().nullish(),pricing:T({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:T({specificationVersion:$("v3"),provider:d(),modelId:d()}),modelType:_e(["embedding","image","language","video"]).nullish()}))}))),d4=be(()=>we(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),p4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Ut(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Dt({url:this.getUrl(),headers:Pt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Ut(this.config.o11yHeaders)),body:t,successfulResponseHandler:Xt(vt()),failedResponseHandler:rn({errorSchema:vt(),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 Nr(s,await Cn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Ut(this.config.headers());try{const{value:s,responseHeaders:a}=await Dt({url:this.getUrl(),headers:Pt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Ut(this.config.o11yHeaders)),body:t,successfulResponseHandler:Zs(vt()),failedResponseHandler:rn({errorSchema:vt(),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 Nr(s,await Cn(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},f4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Ut(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Dt({url:this.getUrl(),headers:Pt(s,t??{},this.getModelConfigHeaders(),await Ut(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:Xt(h4),failedResponseHandler:rn({errorSchema:vt(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l},warnings:[]}}catch(a){throw await Nr(a,await Cn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},h4=be(()=>we(T({embeddings:q(q(j())),usage:T({tokens:j()}).nullish(),providerMetadata:ge(d(),ge(d(),$e())).optional()}))),m4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:s,mask:a,providerOptions:i,headers:l,abortSignal:c}){var u,m,p,f;const g=await Ut(this.config.headers());try{const{responseHeaders:v,value:y,rawValue:w}=await Dt({url:this.getUrl(),headers:Pt(g,l??{},this.getModelConfigHeaders(),await Ut(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(_=>wh(_))},...a&&{mask:wh(a)}},successfulResponseHandler:Xt(v4),failedResponseHandler:rn({errorSchema:vt(),errorToMessage:_=>_}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:y.images,warnings:(u=y.warnings)!=null?u:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:v},...y.usage!=null&&{usage:{inputTokens:(m=y.usage.inputTokens)!=null?m:void 0,outputTokens:(p=y.usage.outputTokens)!=null?p:void 0,totalTokens:(f=y.usage.totalTokens)!=null?f:void 0}}}}catch(v){throw await Nr(v,await Cn(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function wh(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Wn(e.data)}:e}var g4=T({images:q($e()).optional()}).catchall($e()),y4=De("type",[T({type:$("unsupported"),feature:d(),details:d().optional()}),T({type:$("compatibility"),feature:d(),details:d().optional()}),T({type:$("other"),message:d()})]),_4=T({inputTokens:j().nullish(),outputTokens:j().nullish(),totalTokens:j().nullish()}),v4=T({images:q(d()),warnings:q(y4).optional(),providerMetadata:ge(d(),g4).optional(),usage:_4.optional()}),w4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:s,seed:a,image:i,providerOptions:l,headers:c,abortSignal:u}){var m;const p=await Ut(this.config.headers());try{const{responseHeaders:f,value:g}=await Dt({url:this.getUrl(),headers:Pt(p,c??{},this.getModelConfigHeaders(),await Ut(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...a&&{seed:a},...l&&{providerOptions:l},...i&&{image:b4(i)}},successfulResponseHandler:async({response:v,url:y,requestBodyValues:w})=>{if(v.body==null)throw new st({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:v.status});const h=Rf({stream:v.body,schema:S4}).getReader(),{done:S,value:k}=await h.read();if(h.releaseLock(),S||!k)throw new st({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:v.status});if(!k.success)throw new st({message:"Failed to parse video SSE event",cause:k.error,url:y,requestBodyValues:w,statusCode:v.status});const C=k.value;if(C.type==="error")throw new st({message:C.message,statusCode:C.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([...v.headers]),responseBody:JSON.stringify(C),data:{error:{message:C.message,type:C.errorType,param:C.param}}});return{value:{videos:C.videos,warnings:C.warnings,providerMetadata:C.providerMetadata},responseHeaders:Object.fromEntries([...v.headers])}},failedResponseHandler:rn({errorSchema:vt(),errorToMessage:v=>v}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:g.videos,warnings:(m=g.warnings)!=null?m:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:f}}}catch(f){throw await Nr(f,await Cn(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function b4(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Wn(e.data)}:e}var k4=T({videos:q($e()).optional()}).catchall($e()),C4=oe([T({type:$("url"),url:d(),mediaType:d()}),T({type:$("base64"),data:d(),mediaType:d()})]),T4=De("type",[T({type:$("unsupported"),feature:d(),details:d().optional()}),T({type:$("compatibility"),feature:d(),details:d().optional()}),T({type:$("other"),message:d()})]),S4=De("type",[T({type:$("result"),videos:q(C4),warnings:q(T4).optional(),providerMetadata:ge(d(),k4).optional()}),T({type:$("error"),message:d(),errorType:d(),statusCode:j(),param:$e().nullable()})]),I4=be(()=>we(or({objective:We().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:Xr(We()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Vs(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:br().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:or({include_domains:Xr(We()).optional().describe("List of domains to include in search results."),exclude_domains:Xr(We()).optional().describe("List of domains to exclude from search results."),after_date:We().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:or({max_chars_per_result:br().optional().describe("Maximum characters per result."),max_chars_total:br().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:or({max_age_seconds:br().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),x4=be(()=>we(al([or({searchId:We(),results:Xr(or({url:We(),title:We(),excerpt:We(),publishDate:We().nullable().optional(),relevanceScore:br().optional()}))}),or({error:Vs(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:br().optional(),message:We()})]))),E4=ir({id:"gateway.parallel_search",inputSchema:I4,outputSchema:x4}),$4=(e={})=>E4(e),R4=be(()=>we(or({query:al([We(),Xr(We())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:br().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:br().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:br().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:We().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Xr(We()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Xr(We()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:We().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:We().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:We().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:We().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Vs(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),P4=be(()=>we(al([or({results:Xr(or({title:We(),url:We(),snippet:We(),date:We().optional(),lastUpdated:We().optional()})),id:We()}),or({error:Vs(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:br().optional(),message:We()})]))),N4=ir({id:"gateway.perplexity_search",inputSchema:R4,outputSchema:P4}),M4=(e={})=>N4(e),O4={parallelSearch:$4,perplexitySearch:M4};async function A4(){var e;return(e=Lf.getContext().headers)==null?void 0:e["x-vercel-id"]}var q4="3.0.55",L4="0.0.1";function j4(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=Of(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const v=await U4(e);return tn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":L4,[_h]:v.authMethod,...e.headers},`ai-sdk/gateway/${q4}`)}catch(v){throw wl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},c=()=>{const v=Yn({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Yn({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=Yn({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),_=Yn({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const h=await A4();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...w&&{"ai-o11y-region":w},...h&&{"ai-o11y-request-id":h},..._&&{"ai-o11y-project-id":_}}}},u=v=>new p4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),m=async()=>{var v,y,w;const _=(w=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?w:Date.now();return(!n||_-a>s)&&(a=_,n=new vh({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(h=>(o=h,h)).catch(async h=>{throw await Nr(h,await Cn(await l()))})),o?Promise.resolve(o):n},p=async()=>new vh({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await Nr(v,await Cn(await l()))}),f=function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(v)};f.specificationVersion="v3",f.getAvailableModels=m,f.getCredits=p,f.imageModel=v=>new m4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const g=v=>new f4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=g,f.textEmbeddingModel=g,f.videoModel=v=>new w4(v,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.chat=f.languageModel,f.embedding=f.embeddingModel,f.image=f.imageModel,f.video=f.videoModel,f.tools=O4,f}var D4=j4();async function U4(e){const t=Yn({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Lf.getVercelOidcToken(),authMethod:"oidc"}}var z4=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Tn="1.9.0",bh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function F4(e){var t=new Set([e]),r=new Set,n=e.match(bh);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(bh);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 V4=F4(Tn),Z4=Tn.split(".")[0],No=Symbol.for("opentelemetry.js.api."+Z4),Mo=z4;function Oo(e,t,r,n){var o;n===void 0&&(n=!1);var s=Mo[No]=(o=Mo[No])!==null&&o!==void 0?o:{version:Tn};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!==Tn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+Tn);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+Tn+"."),!0}function Sn(e){var t,r,n=(t=Mo[No])===null||t===void 0?void 0:t.version;if(!(!n||!V4(n)))return(r=Mo[No])===null||r===void 0?void 0:r[e]}function Ao(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+Tn+".");var r=Mo[No];r&&delete r[e]}var B4=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},H4=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))},J4=(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 qo("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qo("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qo("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qo("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return qo("verbose",this._namespace,t)},e})();function qo(e,t,r){var n=Sn("diag");if(n)return r.unshift(t),n[e].apply(n,H4([],B4(r),!1))}var Ht;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(Ht||(Ht={}));function G4(e,t){e<Ht.NONE?e=Ht.NONE:e>Ht.ALL&&(e=Ht.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",Ht.ERROR),warn:r("warn",Ht.WARN),info:r("info",Ht.INFO),debug:r("debug",Ht.DEBUG),verbose:r("verbose",Ht.VERBOSE)}}var W4=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},K4=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))},Y4="diag",kr=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=Sn("diag");if(i)return i[o].apply(i,K4([],W4(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:Ht.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=Sn("diag"),m=G4((i=s.logLevel)!==null&&i!==void 0?i:Ht.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),m.warn("Current logger will overwrite one already registered from "+p)}return Oo("diag",m,r,!0)};r.setLogger=n,r.disable=function(){Ao(Y4,r)},r.createComponentLogger=function(o){return new J4(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),Q4=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},X4=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.")},e6=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=Q4(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var a=X4(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})();kr.instance();function t6(e){return e===void 0&&(e={}),new e6(new Map(Object.entries(e)))}function kh(e){return Symbol.for(e)}var r6=(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})(),n6=new r6,In=(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)}})(),o6=(function(){function e(){}return e.prototype.createGauge=function(t,r){return h6},e.prototype.createHistogram=function(t,r){return m6},e.prototype.createCounter=function(t,r){return f6},e.prototype.createUpDownCounter=function(t,r){return g6},e.prototype.createObservableGauge=function(t,r){return _6},e.prototype.createObservableCounter=function(t,r){return y6},e.prototype.createObservableUpDownCounter=function(t,r){return v6},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Bs=(function(){function e(){}return e})(),s6=(function(e){In(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Bs),a6=(function(e){In(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Bs),i6=(function(e){In(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Bs),l6=(function(e){In(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Bs),bl=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),c6=(function(e){In(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(bl),u6=(function(e){In(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(bl),d6=(function(e){In(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(bl),p6=new o6,f6=new s6,h6=new i6,m6=new l6,g6=new a6,y6=new c6,_6=new u6,v6=new d6,w6={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},b6={set:function(e,t,r){e!=null&&(e[t]=r)}},k6=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},C6=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))},T6=(function(){function e(){}return e.prototype.active=function(){return n6},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,C6([n],k6(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),S6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},I6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},kl="context",x6=new T6,Hs=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Oo(kl,t,kr.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,I6([t,r,n],S6(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return Sn(kl)||x6},e.prototype.disable=function(){this._getContextManager().disable(),Ao(kl,kr.instance())},e})(),Cl;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Cl||(Cl={}));var Ch="0000000000000000",Th="00000000000000000000000000000000",E6={traceId:Th,spanId:Ch,traceFlags:Cl.NONE},Lo=(function(){function e(t){t===void 0&&(t=E6),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})(),Tl=kh("OpenTelemetry Context Key SPAN");function Sl(e){return e.getValue(Tl)||void 0}function $6(){return Sl(Hs.getInstance().active())}function Il(e,t){return e.setValue(Tl,t)}function R6(e){return e.deleteValue(Tl)}function P6(e,t){return Il(e,new Lo(t))}function Sh(e){var t;return(t=Sl(e))===null||t===void 0?void 0:t.spanContext()}var N6=/^([0-9a-f]{32})$/i,M6=/^[0-9a-f]{16}$/i;function O6(e){return N6.test(e)&&e!==Th}function A6(e){return M6.test(e)&&e!==Ch}function Ih(e){return O6(e.traceId)&&A6(e.spanId)}function q6(e){return new Lo(e)}var xl=Hs.getInstance(),xh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=xl.active());var o=!!r?.root;if(o)return new Lo;var s=n&&Sh(n);return L6(s)&&Ih(s)?new Lo(s):new Lo},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??xl.active(),c=this.startSpan(t,s,l),u=Il(l,c);return xl.with(u,i,void 0,c)}},e})();function L6(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var j6=new xh,D6=(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):j6},e})(),U6=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new xh},e})(),z6=new U6,Eh=(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 D6(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:z6},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})(),Js;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Js||(Js={}));var $h=Hs.getInstance();kr.instance();var F6=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return p6},e})(),V6=new F6,El="metrics",Z6=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Oo(El,t,kr.instance())},e.prototype.getMeterProvider=function(){return Sn(El)||V6},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Ao(El,kr.instance())},e})();Z6.getInstance();var B6=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),$l=kh("OpenTelemetry Baggage Key");function Rh(e){return e.getValue($l)||void 0}function H6(){return Rh(Hs.getInstance().active())}function J6(e,t){return e.setValue($l,t)}function G6(e){return e.deleteValue($l)}var Rl="propagation",W6=new B6,K6=(function(){function e(){this.createBaggage=t6,this.getBaggage=Rh,this.getActiveBaggage=H6,this.setBaggage=J6,this.deleteBaggage=G6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Oo(Rl,t,kr.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=b6),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=w6),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Ao(Rl,kr.instance())},e.prototype._getGlobalPropagator=function(){return Sn(Rl)||W6},e})();K6.getInstance();var Pl="trace",Y6=(function(){function e(){this._proxyTracerProvider=new Eh,this.wrapSpanContext=q6,this.isSpanContextValid=Ih,this.deleteSpan=R6,this.getSpan=Sl,this.getActiveSpan=$6,this.getSpanContext=Sh,this.setSpan=Il,this.setSpanContext=P6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=Oo(Pl,this._proxyTracerProvider,kr.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return Sn(Pl)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Ao(Pl,kr.instance()),this._proxyTracerProvider=new Eh},e})(),Q6=Y6.getInstance(),X6=Object.defineProperty,ek=(e,t)=>{for(var r in t)X6(e,r,{get:t[r],enumerable:!0})},Ph="AI_InvalidArgumentError",Nh=`vercel.ai.error.${Ph}`,tk=Symbol.for(Nh),Mh,Cr=class extends me{constructor({parameter:t,value:r,message:n}){super({name:Ph,message:`Invalid argument for parameter ${t}: ${n}`}),this[Mh]=!0,this.parameter=t,this.value=r}static isInstance(t){return me.hasMarker(t,Nh)}};Mh=tk;var Oh="AI_InvalidToolApprovalError",Ah=`vercel.ai.error.${Oh}`,rk=Symbol.for(Ah),qh,nk=class extends me{constructor({approvalId:e}){super({name:Oh,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[qh]=!0,this.approvalId=e}static isInstance(e){return me.hasMarker(e,Ah)}};qh=rk;var Lh="AI_InvalidToolInputError",jh=`vercel.ai.error.${Lh}`,ok=Symbol.for(jh),Dh,Nl=class extends me{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${hn(r)}`}){super({name:Lh,message:n,cause:r}),this[Dh]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return me.hasMarker(e,jh)}};Dh=ok;var Uh="AI_ToolCallNotFoundForApprovalError",zh=`vercel.ai.error.${Uh}`,sk=Symbol.for(zh),Fh,Ml=class extends me{constructor({toolCallId:e,approvalId:t}){super({name:Uh,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Fh]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return me.hasMarker(e,zh)}};Fh=sk;var Vh="AI_MissingToolResultsError",Zh=`vercel.ai.error.${Vh}`,ak=Symbol.for(Zh),Bh,Hh=class extends me{constructor({toolCallIds:e}){super({name:Vh,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Bh]=!0,this.toolCallIds=e}static isInstance(e){return me.hasMarker(e,Zh)}};Bh=ak;var Jh="AI_NoObjectGeneratedError",Gh=`vercel.ai.error.${Jh}`,ik=Symbol.for(Gh),Wh,nn=class extends me{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Jh,message:e,cause:t}),this[Wh]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return me.hasMarker(e,Gh)}};Wh=ik;var Kh="AI_NoOutputGeneratedError",Yh=`vercel.ai.error.${Kh}`,lk=Symbol.for(Yh),Qh,Xh=class extends me{constructor({message:e="No output generated.",cause:t}={}){super({name:Kh,message:e,cause:t}),this[Qh]=!0}static isInstance(e){return me.hasMarker(e,Yh)}};Qh=lk;var e0="AI_NoSuchToolError",t0=`vercel.ai.error.${e0}`,ck=Symbol.for(t0),r0,Ol=class extends me{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:e0,message:r}),this[r0]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return me.hasMarker(e,t0)}};r0=ck;var n0="AI_ToolCallRepairError",o0=`vercel.ai.error.${n0}`,uk=Symbol.for(o0),s0,dk=class extends me{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${hn(e)}`}){super({name:n0,message:r,cause:e}),this[s0]=!0,this.originalError=t}static isInstance(e){return me.hasMarker(e,o0)}};s0=uk;var pk=class extends me{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},a0="AI_UIMessageStreamError",i0=`vercel.ai.error.${a0}`,fk=Symbol.for(i0),l0,Xn=class extends me{constructor({chunkType:e,chunkId:t,message:r}){super({name:a0,message:r}),this[l0]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return me.hasMarker(e,i0)}};l0=fk;var c0="AI_InvalidMessageRoleError",u0=`vercel.ai.error.${c0}`,hk=Symbol.for(u0),d0,mk=class extends me{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:c0,message:t}),this[d0]=!0,this.role=e}static isInstance(e){return me.hasMarker(e,u0)}};d0=hk;var p0="AI_RetryError",f0=`vercel.ai.error.${p0}`,gk=Symbol.for(f0),h0,m0=class extends me{constructor({message:e,reason:t,errors:r}){super({name:p0,message:e}),this[h0]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return me.hasMarker(e,f0)}};h0=gk;function yk({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var _k="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",g0=!1,Al=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}g0||(g0=!0,console.info(_k));for(const r of e.warnings)console.warn(yk({warning:r,provider:e.provider,model:e.model}))}};function vk({provider:e,modelId:t}){Al({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function wk(e){return e.specificationVersion==="v3"?e:(vk({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:y0(o.finishReason),usage:_0(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:bk(o.stream)}};default:return t[r]}}}))}function bk(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:y0(t.finishReason),usage:_0(t.usage)});break;default:r.enqueue(t);break}}}))}function y0(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function _0(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function Gs(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new pk({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return wk(e)}return kk().languageModel(e)}function kk(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:D4}function ql(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function v0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function Ck(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var Tk=[{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]}],Sk=e=>{const t=typeof e=="string"?Gn(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function Ik(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Sk(e):e}function xk({data:e,signatures:t}){const r=Ik(e),n=typeof r=="string"?Gn(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 w0="6.0.99",Ek=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();try{const s=await fetch(o,{headers:tn({},`ai-sdk/${w0}`,Po()),signal:r});if(!s.ok)throw new en({url:o,statusCode:s.status,statusText:s.statusText});return{data:await yf({response:s,url:o,maxBytes:t??ll}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw en.isInstance(s)?s:new en({url:o,cause:s})}},$k=(e=Ek)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function Rk(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 b0=oe([d(),Ls(Uint8Array),Ls(ArrayBuffer),Up(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function k0(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}=Rk(e.toString());if(t==null||r==null)throw new me({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function Pk(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Wn(new Uint8Array(e)):Wn(e)}function jo(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function C0({prompt:e,supportedUrls:t,download:r=$k()}){const n=await Mk(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const m=o.get(u.approvalId);m&&s.add(m)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:jo(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>Nk({message:c,downloadedAssets:n}))],i=[];for(const c of a){if(c.role!=="tool"){i.push(c);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...c.content):i.push(c)}const l=new Set;for(const c of i)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of s)l.delete(u);if(l.size>0)throw new Hh({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Hh({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function Nk({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=>Ok(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=k0(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:T0(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:T0(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new mk({role:n})}}}async function Mk(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&&Z3({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 Ok(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}=k0(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=xk({data:l,signatures:Tk}))!=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 T0(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}async function Do({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:hn(r)}:o==="json"?{type:"error-json",value:S0(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:S0(r)}}function S0(e){return e===void 0?null:e}function Ll({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 Cr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new Cr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new Cr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Cr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new Cr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new Cr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Cr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new Cr({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 Ak(e){return e!=null&&Object.keys(e).length>0}async function I0({tools:e,toolChoice:t,activeTools:r}){if(!Ak(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e),o=[];for(const[s,a]of n){const i=a.type;switch(i){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await kn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=i;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var Uo=Yi(()=>oe([qs(),d(),j(),fe(),ge(d(),Uo.optional()),q(Uo)])),lt=ge(d(),ge(d(),Uo.optional())),x0=T({type:$("text"),text:d(),providerOptions:lt.optional()}),qk=T({type:$("image"),image:oe([b0,Ls(URL)]),mediaType:d().optional(),providerOptions:lt.optional()}),E0=T({type:$("file"),data:oe([b0,Ls(URL)]),filename:d().optional(),mediaType:d(),providerOptions:lt.optional()}),Lk=T({type:$("reasoning"),text:d(),providerOptions:lt.optional()}),jk=T({type:$("tool-call"),toolCallId:d(),toolName:d(),input:$e(),providerOptions:lt.optional(),providerExecuted:fe().optional()}),Dk=De("type",[T({type:$("text"),value:d(),providerOptions:lt.optional()}),T({type:$("json"),value:Uo,providerOptions:lt.optional()}),T({type:$("execution-denied"),reason:d().optional(),providerOptions:lt.optional()}),T({type:$("error-text"),value:d(),providerOptions:lt.optional()}),T({type:$("error-json"),value:Uo,providerOptions:lt.optional()}),T({type:$("content"),value:q(oe([T({type:$("text"),text:d(),providerOptions:lt.optional()}),T({type:$("media"),data:d(),mediaType:d()}),T({type:$("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:lt.optional()}),T({type:$("file-url"),url:d(),providerOptions:lt.optional()}),T({type:$("file-id"),fileId:oe([d(),ge(d(),d())]),providerOptions:lt.optional()}),T({type:$("image-data"),data:d(),mediaType:d(),providerOptions:lt.optional()}),T({type:$("image-url"),url:d(),providerOptions:lt.optional()}),T({type:$("image-file-id"),fileId:oe([d(),ge(d(),d())]),providerOptions:lt.optional()}),T({type:$("custom"),providerOptions:lt.optional()})]))})]),$0=T({type:$("tool-result"),toolCallId:d(),toolName:d(),output:Dk,providerOptions:lt.optional()}),Uk=T({type:$("tool-approval-request"),approvalId:d(),toolCallId:d()}),zk=T({type:$("tool-approval-response"),approvalId:d(),approved:fe(),reason:d().optional()}),Fk=T({role:$("system"),content:d(),providerOptions:lt.optional()}),Vk=T({role:$("user"),content:oe([d(),q(oe([x0,qk,E0]))]),providerOptions:lt.optional()}),Zk=T({role:$("assistant"),content:oe([d(),q(oe([x0,E0,Lk,jk,$0,Uk]))]),providerOptions:lt.optional()}),Bk=T({role:$("tool"),content:q(oe([$0,zk])),providerOptions:lt.optional()}),Hk=oe([Fk,Vk,Zk,Bk]);async function R0(e){if(e.prompt==null&&e.messages==null)throw new mn({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new mn({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!jo(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new mn({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new mn({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new mn({prompt:e,message:"messages must not be empty"});const r=await Yt({value:t,schema:q(Hk)});if(!r.success)throw new mn({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function P0(e){if(!wl.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new me({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
56
+
57
+ To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
58
+
59
+ Alternatively, you can use a provider module instead of the AI Gateway.
60
+
61
+ Learn more: \x1B[34m${r}\x1B[0m
62
+
63
+ `),{name:"GatewayAuthenticationError"})}function zo({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 N0({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>{if(a==="timeout"){const l=ql(i);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=i;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(n??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var Jk={startSpan(){return Ws},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Ws);if(typeof r=="function")return r(Ws);if(typeof n=="function")return n(Ws)}},Ws={spanContext(){return Gk},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}},Gk={traceId:"",spanId:"",traceFlags:0};function M0({isEnabled:e=!1,tracer:t}={}){return e?t||Q6.getTracer("ai"):Jk}async function Fo({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=$h.active();try{const i=await $h.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{O0(s,i)}finally{s.end()}throw i}})}function O0(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Js.ERROR,message:t.message})):e.setStatus({code:Js.ERROR})}async function Tr({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function A0(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?Pk(r.data):r.data}:r)})))}function q0(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:lr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function jl(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function L0(e,t){var r,n,o,s,a,i,l,c,u,m;return{inputTokens:lr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:lr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:lr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:lr((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:lr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:lr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:lr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:lr(e.totalTokens,t.totalTokens),reasoningTokens:lr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:lr(e.cachedInputTokens,t.cachedInputTokens)}}function lr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Ks(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]=Ks(s,o):r[n]=o}return r}function Wk({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 Kk=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>j0(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function j0(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(wn(a)||t===0)throw a;const i=cl(a),l=[...s,a],c=l.length;if(c>t)throw new m0({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&st.isInstance(a)&&a.isRetryable===!0&&c<=t)return await M3(Wk({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),j0(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new m0({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function D0({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new Cr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new Cr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:Kk({maxRetries:r,abortSignal:t})}}function U0({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],i=t.content.filter(l=>l.type==="tool-approval-response");for(const l of i){const c=n[l.approvalId];if(c==null)throw new nk({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new Ml({toolCallId:c.toolCallId,approvalId:c.approvalId});const m={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(m):a.push(m)}return{approvedToolApprovals:s,deniedToolApprovals:a}}function Ys(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Dl({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:m}){const{toolName:p,toolCallId:f,input:g}=e,v=t?.[p];if(v?.execute==null)return;const y={stepNumber:i,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:a};return Fo({name:"ai.toolCall",attributes:Tr({telemetry:n,attributes:{...zo({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":f,"ai.toolCall.args":{output:()=>JSON.stringify(g)}}}),tracer:r,fn:async w=>{let _;try{await u?.(y)}catch{}const h=Ys();try{const k=B9({execute:v.execute.bind(v),input:g,options:{toolCallId:f,messages:o,abortSignal:s,experimental_context:a}});for await(const C of k)C.type==="preliminary"?c?.({...e,type:"tool-result",output:C.output,preliminary:!0}):_=C.output}catch(k){const C=Ys()-h;try{await m?.({...y,success:!1,error:k,durationMs:C})}catch{}return O0(w,k),{type:"tool-error",toolCallId:f,toolName:p,input:g,error:k,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const S=Ys()-h;try{await m?.({...y,success:!0,output:_,durationMs:S})}catch{}try{w.setAttributes(await Tr({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(_)}}}))}catch{}return{type:"tool-result",toolCallId:f,toolName:p,input:g,output:_,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function z0(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
64
+ `)}function F0(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var V0=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=Wn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Gn(this.base64Data)),this.uint8ArrayData}},Yk=class extends V0{constructor(e){super(e),this.type="file"}};async function Z0({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var Qk={};ek(Qk,{array:()=>t5,choice:()=>r5,json:()=>n5,object:()=>e5,text:()=>Qs});function Xk(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(n,l+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function Vo(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Qt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Qt({text:Xk(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Qs=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),e5=({schema:e,name:t,description:r})=>{const n=kn(e);return{name:"object",responseFormat:Ut(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await Qt({text:o});if(!a.success)throw new nn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=await Yt({value:a.value,schema:n});if(!i.success)throw new nn({message:"No object generated: response did not match schema.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return i.value},async parsePartialOutput({text:o}){const s=await Vo(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},t5=({element:e,name:t,description:r})=>{const n=kn(e);return{name:"array",responseFormat:Ut(n.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const a=await Qt({text:o});if(!a.success)throw new nn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))throw new nn({message:"No object generated: response did not match schema.",cause:new gn({value:i,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of i.elements){const c=await Yt({value:l,schema:n});if(!c.success)throw new nn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return i.elements},async parsePartialOutput({text:o}){const s=await Vo(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const i=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of i){const u=await Yt({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},r5=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const s=await Qt({text:n});if(!s.success)throw new nn({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new nn({message:"No object generated: response did not match schema.",cause:new gn({value:a,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:n}){const o=await Vo(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(i=>i.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),n5=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await Qt({text:r});if(!o.success)throw new nn({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await Vo(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function B0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await H0(e);throw new Ol({toolName:e.toolName})}try{return await J0({toolCall:e,tools:t})}catch(a){if(r==null||!(Ol.isInstance(a)||Nl.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await kn(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new dk({cause:l,originalError:a})}if(i==null)throw a;return await J0({toolCall:i,tools:t})}}catch(a){const i=await Qt({text:e.input}),l=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function H0(e){const t=e.input.trim()===""?{success:!0,value:{}}:await Qt({text:e.input});if(t.success===!1)throw new Nl({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function J0({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await H0(e);throw new Ol({toolName:e.toolName,availableTools:Object.keys(t)})}const o=kn(n.inputSchema),s=e.input.trim()===""?await Yt({value:{},schema:o}):await Qt({text:e.input,schema:o});if(s.success===!1)throw new Nl({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}var G0=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:a,rawFinishReason:i,usage:l,warnings:c,request:u,response:m,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=s,this.finishReason=a,this.rawFinishReason=i,this.usage=l,this.warnings=c,this.request=u,this.response=m,this.providerMetadata=p}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function Ul(e){return({steps:t})=>t.length===e}async function W0({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function zl({content:e,tools:t}){const r=[],n=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":n.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":n.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await Do({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await Do({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await Do({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function K0(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var o5=Ro({prefix:"aitxt",size:24});async function Y0({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Ul(1),experimental_output:m,output:p=m,experimental_telemetry:f,providerOptions:g,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:w,prepareStep:_=w,experimental_repairToolCall:h,experimental_download:S,experimental_context:k,experimental_include:C,_internal:{generateId:b=o5}={},experimental_onStart:E,experimental_onStepStart:I,experimental_onToolCallStart:L,experimental_onToolCallFinish:M,onStepFinish:A,onFinish:O,...U}){const G=Gs(e),H=jo(u),le=ql(l),ee=v0(l),he=ee!=null?new AbortController:void 0,Z=K0(i,le!=null?AbortSignal.timeout(le):void 0,he?.signal),{maxRetries:R,retry:B}=D0({maxRetries:a,abortSignal:Z}),F=Ll(U),x=tn(c??{},`ai/${w0}`),N=N0({model:G,telemetry:f,headers:x,settings:{...F,maxRetries:R}}),D={provider:G.provider,modelId:G.modelId},W=await R0({system:n,prompt:o,messages:s});try{await E?.({model:D,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:F.maxOutputTokens,temperature:F.temperature,topP:F.topP,topK:F.topK,presencePenalty:F.presencePenalty,frequencyPenalty:F.frequencyPenalty,stopSequences:F.stopSequences,seed:F.seed,maxRetries:R,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:i,include:C,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k})}catch{}const re=M0(f);try{return await Fo({name:"ai.generateText",attributes:Tr({telemetry:f,attributes:{...zo({operationId:"ai.generateText",telemetry:f}),...N,"ai.model.provider":G.provider,"ai.model.id":G.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:re,fn:async se=>{var Te,z,V,K,Q,ie,ve,Qe,P,X,Re,qe,Vt;const ft=W.messages,Ke=[],{approvedToolApprovals:zr,deniedToolApprovals:Xe}=U0({messages:ft}),Wt=zr.filter(ot=>!ot.toolCall.providerExecuted);if(Xe.length>0||Wt.length>0){const ot=await Q0({toolCalls:Wt.map(Ce=>Ce.toolCall),tools:t,tracer:re,telemetry:f,messages:ft,abortSignal:Z,experimental_context:k,stepNumber:0,model:D,onToolCallStart:L,onToolCallFinish:M}),kt=[];for(const Ce of ot){const Nt=await Do({toolCallId:Ce.toolCallId,input:Ce.input,tool:t?.[Ce.toolName],output:Ce.type==="tool-result"?Ce.output:Ce.error,errorMode:Ce.type==="tool-error"?"json":"none"});kt.push({type:"tool-result",toolCallId:Ce.toolCallId,toolName:Ce.toolName,output:Nt})}for(const Ce of Xe)kt.push({type:"tool-result",toolCallId:Ce.toolCall.toolCallId,toolName:Ce.toolCall.toolName,output:{type:"execution-denied",reason:Ce.approvalResponse.reason,...Ce.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ce.approvalResponse.approvalId}}}}});Ke.push({role:"tool",content:kt})}const Fr=[...zr,...Xe].filter(ot=>ot.toolCall.providerExecuted);Fr.length>0&&Ke.push({role:"tool",content:Fr.map(ot=>({type:"tool-approval-response",approvalId:ot.approvalResponse.approvalId,approved:ot.approvalResponse.approved,reason:ot.approvalResponse.reason,providerExecuted:!0}))});const et=Ll(U);let Se,nt=[],Ie=[];const Je=[],gr=new Map;do{const ot=ee!=null?setTimeout(()=>he.abort(),ee):void 0;try{const kt=[...ft,...Ke],Ce=await _?.({model:G,steps:Je,stepNumber:Je.length,messages:kt,experimental_context:k}),Nt=Gs((Te=Ce?.model)!=null?Te:G),dt={provider:Nt.provider,modelId:Nt.modelId},Ct=await C0({prompt:{system:(z=Ce?.system)!=null?z:W.system,messages:(V=Ce?.messages)!=null?V:kt},supportedUrls:await Nt.supportedUrls,download:S});k=(K=Ce?.experimental_context)!=null?K:k;const ct=(Q=Ce?.activeTools)!=null?Q:y,{toolChoice:Vr,tools:go}=await I0({tools:t,toolChoice:(ie=Ce?.toolChoice)!=null?ie:r,activeTools:ct}),Ri=(ve=Ce?.messages)!=null?ve:kt,Pi=(Qe=Ce?.system)!=null?Qe:W.system,ms=Ks(g,Ce?.providerOptions);try{await I?.({stepNumber:Je.length,model:dt,system:Pi,messages:Ri,tools:t,toolChoice:Vr,activeTools:ct,steps:[...Je],providerOptions:ms,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:C,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k})}catch{}Se=await B(()=>{var Pe;return Fo({name:"ai.generateText.doGenerate",attributes:Tr({telemetry:f,attributes:{...zo({operationId:"ai.generateText.doGenerate",telemetry:f}),...N,"ai.model.provider":Nt.provider,"ai.model.id":Nt.modelId,"ai.prompt.messages":{input:()=>A0(Ct)},"ai.prompt.tools":{input:()=>go?.map(Mt=>JSON.stringify(Mt))},"ai.prompt.toolChoice":{input:()=>Vr!=null?JSON.stringify(Vr):void 0},"gen_ai.system":Nt.provider,"gen_ai.request.model":Nt.modelId,"gen_ai.request.frequency_penalty":U.frequencyPenalty,"gen_ai.request.max_tokens":U.maxOutputTokens,"gen_ai.request.presence_penalty":U.presencePenalty,"gen_ai.request.stop_sequences":U.stopSequences,"gen_ai.request.temperature":(Pe=U.temperature)!=null?Pe:void 0,"gen_ai.request.top_k":U.topK,"gen_ai.request.top_p":U.topP}}),tracer:re,fn:async Mt=>{var fn,Zr,Mi,Oi,vs,Ai,ws,yo;const ut=await Nt.doGenerate({...et,tools:go,toolChoice:Vr,responseFormat:await p?.responseFormat,prompt:Ct,providerOptions:ms,abortSignal:Z,headers:x}),Br={id:(Zr=(fn=ut.response)==null?void 0:fn.id)!=null?Zr:b(),timestamp:(Oi=(Mi=ut.response)==null?void 0:Mi.timestamp)!=null?Oi:new Date,modelId:(Ai=(vs=ut.response)==null?void 0:vs.modelId)!=null?Ai:Nt.modelId,headers:(ws=ut.response)==null?void 0:ws.headers,body:(yo=ut.response)==null?void 0:yo.body};return Mt.setAttributes(await Tr({telemetry:f,attributes:{"ai.response.finishReason":ut.finishReason.unified,"ai.response.text":{output:()=>F0(ut.content)},"ai.response.reasoning":{output:()=>z0(ut.content)},"ai.response.toolCalls":{output:()=>{const qi=X0(ut.content);return qi==null?void 0:JSON.stringify(qi)}},"ai.response.id":Br.id,"ai.response.model":Br.modelId,"ai.response.timestamp":Br.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ut.providerMetadata),"ai.usage.promptTokens":ut.usage.inputTokens.total,"ai.usage.completionTokens":ut.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ut.finishReason.unified],"gen_ai.response.id":Br.id,"gen_ai.response.model":Br.modelId,"gen_ai.usage.input_tokens":ut.usage.inputTokens.total,"gen_ai.usage.output_tokens":ut.usage.outputTokens.total}})),{...ut,response:Br}}})});const nr=await Promise.all(Se.content.filter(Pe=>Pe.type==="tool-call").map(Pe=>B0({toolCall:Pe,tools:t,repairToolCall:h,system:n,messages:kt}))),gs={};for(const Pe of nr){if(Pe.invalid)continue;const Mt=t?.[Pe.toolName];Mt!=null&&(Mt?.onInputAvailable!=null&&await Mt.onInputAvailable({input:Pe.input,toolCallId:Pe.toolCallId,messages:kt,abortSignal:Z,experimental_context:k}),await Z0({tool:Mt,toolCall:Pe,messages:kt,experimental_context:k})&&(gs[Pe.toolCallId]={type:"tool-approval-request",approvalId:b(),toolCall:Pe}))}const Ni=nr.filter(Pe=>Pe.invalid&&Pe.dynamic);Ie=[];for(const Pe of Ni)Ie.push({type:"tool-error",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:Pe.input,error:cl(Pe.error),dynamic:!0});nt=nr.filter(Pe=>!Pe.providerExecuted),t!=null&&Ie.push(...await Q0({toolCalls:nt.filter(Pe=>!Pe.invalid&&gs[Pe.toolCallId]==null),tools:t,tracer:re,telemetry:f,messages:kt,abortSignal:Z,experimental_context:k,stepNumber:Je.length,model:dt,onToolCallStart:L,onToolCallFinish:M}));for(const Pe of nr){if(!Pe.providerExecuted)continue;const Mt=t?.[Pe.toolName];Mt?.type==="provider"&&Mt.supportsDeferredResults&&(Se.content.some(Zr=>Zr.type==="tool-result"&&Zr.toolCallId===Pe.toolCallId)||gr.set(Pe.toolCallId,{toolName:Pe.toolName}))}for(const Pe of Se.content)Pe.type==="tool-result"&&gr.delete(Pe.toolCallId);const ys=a5({content:Se.content,toolCalls:nr,toolOutputs:Ie,toolApprovalRequests:Object.values(gs),tools:t});Ke.push(...await zl({content:ys,tools:t}));const pn=(P=C?.requestBody)==null||P?(X=Se.request)!=null?X:{}:{...Se.request,body:void 0},gt={...Se.response,messages:structuredClone(Ke),body:(Re=C?.responseBody)==null||Re?(qe=Se.response)==null?void 0:qe.body:void 0},Ir=Je.length,_s=new G0({stepNumber:Ir,model:dt,functionId:f?.functionId,metadata:f?.metadata,experimental_context:k,content:ys,finishReason:Se.finishReason.unified,rawFinishReason:Se.finishReason.raw,usage:q0(Se.usage),warnings:Se.warnings,providerMetadata:Se.providerMetadata,request:pn,response:gt});Al({warnings:(Vt=Se.warnings)!=null?Vt:[],provider:dt.provider,model:dt.modelId}),Je.push(_s),await A?.(_s)}finally{ot!=null&&clearTimeout(ot)}}while((nt.length>0&&Ie.length===nt.length||gr.size>0)&&!await W0({stopConditions:H,steps:Je}));se.setAttributes(await Tr({telemetry:f,attributes:{"ai.response.finishReason":Se.finishReason.unified,"ai.response.text":{output:()=>F0(Se.content)},"ai.response.reasoning":{output:()=>z0(Se.content)},"ai.response.toolCalls":{output:()=>{const ot=X0(Se.content);return ot==null?void 0:JSON.stringify(ot)}},"ai.response.providerMetadata":JSON.stringify(Se.providerMetadata),"ai.usage.promptTokens":Se.usage.inputTokens.total,"ai.usage.completionTokens":Se.usage.outputTokens.total}}));const Y=Je[Je.length-1],Be=Je.reduce((ot,kt)=>L0(ot,kt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await O?.({stepNumber:Y.stepNumber,model:Y.model,functionId:Y.functionId,metadata:Y.metadata,experimental_context:Y.experimental_context,finishReason:Y.finishReason,rawFinishReason:Y.rawFinishReason,usage:Y.usage,content:Y.content,text:Y.text,reasoningText:Y.reasoningText,reasoning:Y.reasoning,files:Y.files,sources:Y.sources,toolCalls:Y.toolCalls,staticToolCalls:Y.staticToolCalls,dynamicToolCalls:Y.dynamicToolCalls,toolResults:Y.toolResults,staticToolResults:Y.staticToolResults,dynamicToolResults:Y.dynamicToolResults,request:Y.request,response:Y.response,warnings:Y.warnings,providerMetadata:Y.providerMetadata,steps:Je,totalUsage:Be});let yr;return Y.finishReason==="stop"&&(yr=await(p??Qs()).parseCompleteOutput({text:Y.text},{response:Y.response,usage:Y.usage,finishReason:Y.finishReason})),new s5({steps:Je,totalUsage:Be,output:yr})}})}catch(se){throw P0(se)}}async function Q0({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>Dl({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var s5=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Xh;return this._output}};function X0(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 a5({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new V0(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(i=>i.toolCallId===a.toolCallId));break}case"tool-result":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,error:a.result,providerExecuted:!0,dynamic:i.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,output:a.result,providerExecuted:!0,dynamic:i.dynamic});break}case"tool-approval-request":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null)throw new Ml({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function Xs(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 i5({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Xs(r,{"content-type":"text/plain; charset=utf-8"})})}function em({response:e,status:t,statusText:r,headers:n,stream:o}){const s=t??200;r!==void 0?e.writeHead(s,r,n):e.writeHead(s,n);const a=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await a.read();if(l)break;e.write(c)||await new Promise(m=>{e.once("drain",m)})}}catch(l){throw l}finally{e.end()}})()}function l5({response:e,status:t,statusText:r,headers:n,textStream:o}){em({response:e,status:t,statusText:r,headers:Object.fromEntries(Xs(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var tm=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
54
65
 
55
66
  `)},flush(e){e.enqueue(`data: [DONE]
56
67
 
57
- `)}})}},C0={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function N9({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new k0);if(o){const[i,a]=s.tee();s=i,o({stream:a})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Ao(r,C0)})}function A9({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 q9(e){return e.type.startsWith("data-")}function $0(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]=$0(s,o):r[n]=o}return r}function L9(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 _=e.substring(n,l+1);!"false".startsWith(_)&&!"true".startsWith(_)&&!"null".startsWith(_)?(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 E0(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Cr({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Cr({text:L9(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function ui(e){return e.type.startsWith("tool-")}function T0(e){return e.type.split("-").slice(1).join("-")}function j9({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function U9({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 _,f,d,p;function v(b){const k=c.message.parts.filter(ui).find(C=>C.toolCallId===b);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function m(b){const k=c.message.parts.filter(C=>C.type==="dynamic-tool").find(C=>C.toolCallId===b);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function w(b){var S;const k=c.message.parts.find(R=>ui(R)&&R.toolCallId===b.toolCallId),C=b,I=k;k!=null?(k.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=(S=C.providerExecuted)!=null?S:k.providerExecuted,C.providerMetadata!=null&&k.state==="input-available"&&(k.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 g(b){var S,k;const C=c.message.parts.find(L=>L.type==="dynamic-tool"&&L.toolCallId===b.toolCallId),I=b,R=C;C!=null?(C.state=b.state,R.toolName=b.toolName,R.input=I.input,R.output=I.output,R.errorText=I.errorText,R.rawInput=(S=I.rawInput)!=null?S:R.rawInput,R.preliminary=I.preliminary,R.providerExecuted=(k=I.providerExecuted)!=null?k: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 y(b){if(b!=null){const S=c.message.metadata!=null?$0(c.message.metadata,b):b;t!=null&&await Na({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=(_=a.providerMetadata)!=null?_: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=(d=a.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[a.id];b.providerMetadata=(p=a.providerMetadata)!=null?p: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(ui);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 E0(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=m(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:T0(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=m(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:T0(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(q9(a)){r?.[a.type]!=null&&await Na({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(k=>b.type===k.type&&b.id===k.id):void 0;S!=null?S.data=b.data:c.message.parts.push(b),i?.(b),u()}}l.enqueue(a)})}}))}function D9({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,d){if(f.type==="start"){const p=f;p.messageId==null&&e!=null&&(p.messageId=e)}f.type==="abort"&&(i=!0),d.enqueue(f)}}));if(r==null)return a;const l=j9({lastMessage:s?structuredClone(s):void 0,messageId:e??""}),c=async f=>{await f({state:l,write:()=>{}})};let u=!1;const _=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 U9({stream:a,runUpdateMessageJob:c,onError:n}).pipeThrough(new TransformStream({transform(f,d){d.enqueue(f)},async cancel(){await _()},async flush(){await _()}}))}function z9({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let i=o.pipeThrough(new k0);if(s){const[a,l]=i.tee();i=a,s({stream:l})}S0({response:e,status:t,statusText:r,headers:Object.fromEntries(Ao(n,C0).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function qo(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 Z9({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 I0(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function F9(){let e=[],t=null,r=!1,n=I0();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=I0(),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 V9(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}function B9({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}}),_=new Set,f=new Map;let d=!1,p;function v(){d&&_.size===0&&(p!=null&&c.enqueue(p),c.close())}const m=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 T9({data:w.data,mediaType:w.mediaType})});break}case"finish":{p={type:"finish",finishReason:w.finishReason,usage:w.usage,providerMetadata:w.providerMetadata};break}case"tool-call":{try{const b=await m0({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:Oa(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 k=xn();_.add(k),Yr({name:"ai.toolCall",attributes:vt({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 R=$d({execute:S.execute.bind(S),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:i,experimental_context:l}});for await(const L of R)c.enqueue({...b,type:"tool-result",output:L.output,...L.type==="preliminary"&&{preliminary:!0}}),L.type==="final"&&(I=L.output)}catch(R){si(C,R),c.enqueue({...b,type:"tool-error",error:R}),_.delete(k),v();return}_.delete(k),v();try{C.setAttributes(vt({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(){d=!0,v()}});return new ReadableStream({async start(w){return Promise.all([t.pipeThrough(m).pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){}})),u.pipeTo(new WritableStream({write(g){w.enqueue(g)},close(){w.close()}}))])}})}var H9=In({prefix:"aitxt",size:24});function di({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,headers:l,stopWhen:c=ii(1),experimental_output:u,experimental_telemetry:_,prepareStep:f,providerOptions:d,experimental_activeTools:p,activeTools:v=p,experimental_repairToolCall:m,experimental_transform:w,experimental_download:g,includeRawChunks:y=!1,onChunk:b,onError:S=({error:F})=>{console.error(F)},onFinish:k,onAbort:C,onStepFinish:I,experimental_context:R,_internal:{now:L=V9,generateId:O=H9,currentDate:U=()=>new Date}={},...D}){return new G9({model:Mo(e),telemetry:_,headers:l,settings:D,maxRetries:i,abortSignal:a,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:ai(w),activeTools:v,repairToolCall:m,stopConditions:ai(c),output:u,providerOptions:d,prepareStep:f,includeRawChunks:y,onChunk:b,onError:S,onFinish:k,onAbort:C,onStepFinish:I,now:L,currentDate:U,generateId:O,experimental_context:R,download:g})}function J9(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 G9=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:_,activeTools:f,repairToolCall:d,stopConditions:p,output:v,providerOptions:m,prepareStep:w,includeRawChunks:g,now:y,currentDate:b,generateId:S,onChunk:k,onError:C,onFinish:I,onAbort:R,onStepFinish:L,experimental_context:O,download:U}){this._totalUsage=new $o,this._finishReason=new $o,this._steps=new $o,this.output=v,this.includeRawChunks=g,this.tools=c;let D,F=[];const ee=[];let ie,se,X={},de=[];const V=[];let P,Z={},j={};const T=new TransformStream({async transform(W,K){var oe,le,Me,Ae;K.enqueue(W);const{part:Q}=W;if((Q.type==="text-delta"||Q.type==="reasoning-delta"||Q.type==="source"||Q.type==="tool-call"||Q.type==="tool-result"||Q.type==="tool-input-start"||Q.type==="tool-input-delta"||Q.type==="raw")&&await k?.({chunk:Q}),Q.type==="error"&&await C({error:a0(Q.error)}),Q.type==="text-start"&&(Z[Q.id]={type:"text",text:"",providerMetadata:Q.providerMetadata},F.push(Z[Q.id])),Q.type==="text-delta"){const ge=Z[Q.id];if(ge==null){K.enqueue({part:{type:"error",error:`text part ${Q.id} not found`},partialOutput:void 0});return}ge.text+=Q.text,ge.providerMetadata=(oe=Q.providerMetadata)!=null?oe:ge.providerMetadata}if(Q.type==="text-end"){const ge=Z[Q.id];if(ge==null){K.enqueue({part:{type:"error",error:`text part ${Q.id} not found`},partialOutput:void 0});return}ge.providerMetadata=(le=Q.providerMetadata)!=null?le:ge.providerMetadata,delete Z[Q.id]}if(Q.type==="reasoning-start"&&(j[Q.id]={type:"reasoning",text:"",providerMetadata:Q.providerMetadata},F.push(j[Q.id])),Q.type==="reasoning-delta"){const ge=j[Q.id];if(ge==null){K.enqueue({part:{type:"error",error:`reasoning part ${Q.id} not found`},partialOutput:void 0});return}ge.text+=Q.text,ge.providerMetadata=(Me=Q.providerMetadata)!=null?Me:ge.providerMetadata}if(Q.type==="reasoning-end"){const ge=j[Q.id];if(ge==null){K.enqueue({part:{type:"error",error:`reasoning part ${Q.id} not found`},partialOutput:void 0});return}ge.providerMetadata=(Ae=Q.providerMetadata)!=null?Ae:ge.providerMetadata,delete j[Q.id]}if(Q.type==="file"&&F.push({type:"file",file:Q.file}),Q.type==="source"&&F.push(Q),Q.type==="tool-call"&&F.push(Q),Q.type==="tool-result"&&!Q.preliminary&&F.push(Q),Q.type==="tool-error"&&F.push(Q),Q.type==="start-step"&&(X=Q.request,de=Q.warnings),Q.type==="finish-step"){const ge=ci({content:F,tools:c}),at=new _0({content:F,finishReason:Q.finishReason,usage:Q.usage,warnings:de,request:X,response:{...Q.response,messages:[...ee,...ge]},providerMetadata:Q.providerMetadata});await L?.(at),wp(de),V.push(at),F=[],j={},Z={},ee.push(...ge),D.resolve()}Q.type==="finish"&&(se=Q.totalUsage,ie=Q.finishReason)},async flush(W){try{if(V.length===0){const Me=new H3({message:"No output generated. Check the stream for errors."});H._finishReason.reject(Me),H._totalUsage.reject(Me),H._steps.reject(Me);return}const K=ie??"unknown",oe=se??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};H._finishReason.resolve(K),H._totalUsage.resolve(oe),H._steps.resolve(V);const le=V[V.length-1];await I?.({finishReason:K,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}),P.setAttributes(vt({telemetry:t,attributes:{"ai.response.finishReason":K,"ai.response.text":{output:()=>le.text},"ai.response.toolCalls":{output:()=>{var Me;return(Me=le.toolCalls)!=null&&Me.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(K){W.error(K)}finally{P.end()}}}),x=F9();this.addStream=x.addStream,this.closeStream=x.close;const E=x.stream.getReader();let B=new ReadableStream({async start(W){W.enqueue({type:"start"})},async pull(W){function K(){R?.({steps:V}),W.enqueue({type:"abort"}),W.close()}try{const{done:oe,value:le}=await E.read();if(oe){W.close();return}if(s?.aborted){K();return}W.enqueue(le)}catch(oe){kr(oe)&&s?.aborted?K():W.error(oe)}},cancel(W){return x.stream.cancel(W)}});for(const W of _)B=B.pipeThrough(W({tools:c,stopStream(){x.terminate()}}));this.baseStream=B.pipeThrough(J9(v)).pipeThrough(T);const{maxRetries:G,retry:pe}=p0({maxRetries:o,abortSignal:s}),ae=l0(t),M=oi(n),z=i0({model:e,telemetry:t,headers:r,settings:{...M,maxRetries:G}}),H=this;Yr({name:"ai.streamText",attributes:vt({telemetry:t,attributes:{...Kr({operationId:"ai.streamText",telemetry:t}),...z,"ai.prompt":{input:()=>JSON.stringify({system:i,prompt:a,messages:l})}}}),tracer:ae,endWhenDone:!1,fn:async W=>{P=W;async function K({currentStep:oe,responseMessages:le,usage:Me}){var Ae,Q,ge,at,we;const dt=H.includeRawChunks;D=new $o;const rr=await s0({system:i,prompt:a,messages:l}),pt=[...rr.messages,...le],Ye=await w?.({model:e,steps:V,stepNumber:V.length,messages:pt}),Ct=Mo((Ae=Ye?.model)!=null?Ae:e),vr=await e0({prompt:{system:(Q=Ye?.system)!=null?Q:rr.system,messages:(ge=Ye?.messages)!=null?ge:pt},supportedUrls:await Ct.supportedUrls,download:U}),{toolChoice:wr,tools:_n}=t0({tools:c,toolChoice:(at=Ye?.toolChoice)!=null?at:u,activeTools:(we=Ye?.activeTools)!=null?we:f}),{result:{stream:fa,response:Be,request:nr},doStreamSpan:or,startTimestampMs:b1}=await pe(()=>Yr({name:"ai.streamText.doStream",attributes:vt({telemetry:t,attributes:{...Kr({operationId:"ai.streamText.doStream",telemetry:t}),...z,"ai.model.provider":Ct.provider,"ai.model.id":Ct.modelId,"ai.prompt.messages":{input:()=>c0(vr)},"ai.prompt.tools":{input:()=>_n?.map(fe=>JSON.stringify(fe))},"ai.prompt.toolChoice":{input:()=>wr!=null?JSON.stringify(wr):void 0},"gen_ai.system":Ct.provider,"gen_ai.request.model":Ct.modelId,"gen_ai.request.frequency_penalty":M.frequencyPenalty,"gen_ai.request.max_tokens":M.maxOutputTokens,"gen_ai.request.presence_penalty":M.presencePenalty,"gen_ai.request.stop_sequences":M.stopSequences,"gen_ai.request.temperature":M.temperature,"gen_ai.request.top_k":M.topK,"gen_ai.request.top_p":M.topP}}),tracer:ae,endWhenDone:!1,fn:async fe=>({startTimestampMs:y(),doStreamSpan:fe,result:await Ct.doStream({...M,tools:_n,toolChoice:wr,responseFormat:v?.responseFormat,prompt:vr,providerOptions:m,abortSignal:s,headers:r,includeRawChunks:dt})})})),P$=B9({tools:c,generatorStream:fa,tracer:ae,telemetry:t,system:i,messages:pt,repairToolCall:d,abortSignal:s,experimental_context:O}),O$=nr??{},ha=[],mc=[];let gc;const _c={};let yn="unknown",Lt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},yc,S1=!0,Bt={id:S(),timestamp:b(),modelId:e.modelId},k1="";H.addStream(P$.pipeThrough(new TransformStream({async transform(fe,Qe){var uo,po,ma,sr;if(fe.type==="stream-start"){gc=fe.warnings;return}if(S1){const it=y()-b1;S1=!1,or.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":it}),or.setAttributes({"ai.response.msToFirstChunk":it}),Qe.enqueue({type:"start-step",request:O$,warnings:gc??[]})}const C1=fe.type;switch(C1){case"text-start":case"text-end":{Qe.enqueue(fe);break}case"text-delta":{fe.delta.length>0&&(Qe.enqueue({type:"text-delta",id:fe.id,text:fe.delta,providerMetadata:fe.providerMetadata}),k1+=fe.delta);break}case"reasoning-start":case"reasoning-end":{Qe.enqueue(fe);break}case"reasoning-delta":{Qe.enqueue({type:"reasoning-delta",id:fe.id,text:fe.delta,providerMetadata:fe.providerMetadata});break}case"tool-call":{Qe.enqueue(fe),ha.push(fe);break}case"tool-result":{Qe.enqueue(fe),fe.preliminary||mc.push(fe);break}case"tool-error":{Qe.enqueue(fe),mc.push(fe);break}case"response-metadata":{Bt={id:(uo=fe.id)!=null?uo:Bt.id,timestamp:(po=fe.timestamp)!=null?po:Bt.timestamp,modelId:(ma=fe.modelId)!=null?ma:Bt.modelId};break}case"finish":{Lt=fe.usage,yn=fe.finishReason,yc=fe.providerMetadata;const it=y()-b1;or.addEvent("ai.stream.finish"),or.setAttributes({"ai.response.msToFinish":it,"ai.response.avgOutputTokensPerSecond":1e3*((sr=Lt.outputTokens)!=null?sr:0)/it});break}case"file":{Qe.enqueue(fe);break}case"source":{Qe.enqueue(fe);break}case"tool-input-start":{_c[fe.id]=fe.toolName;const it=c?.[fe.toolName];it?.onInputStart!=null&&await it.onInputStart({toolCallId:fe.id,messages:pt,abortSignal:s,experimental_context:O}),Qe.enqueue({...fe,dynamic:it?.type==="dynamic"});break}case"tool-input-end":{delete _c[fe.id],Qe.enqueue(fe);break}case"tool-input-delta":{const it=_c[fe.id],vc=c?.[it];vc?.onInputDelta!=null&&await vc.onInputDelta({inputTextDelta:fe.delta,toolCallId:fe.id,messages:pt,abortSignal:s,experimental_context:O}),Qe.enqueue(fe);break}case"error":{Qe.enqueue(fe),yn="error";break}case"raw":{dt&&Qe.enqueue(fe);break}default:{const it=C1;throw new Error(`Unknown chunk type: ${it}`)}}},async flush(fe){const Qe=ha.length>0?JSON.stringify(ha):void 0;try{or.setAttributes(vt({telemetry:t,attributes:{"ai.response.finishReason":yn,"ai.response.text":{output:()=>k1},"ai.response.toolCalls":{output:()=>Qe},"ai.response.id":Bt.id,"ai.response.model":Bt.modelId,"ai.response.timestamp":Bt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(yc),"ai.usage.inputTokens":Lt.inputTokens,"ai.usage.outputTokens":Lt.outputTokens,"ai.usage.totalTokens":Lt.totalTokens,"ai.usage.reasoningTokens":Lt.reasoningTokens,"ai.usage.cachedInputTokens":Lt.cachedInputTokens,"gen_ai.response.finish_reasons":[yn],"gen_ai.response.id":Bt.id,"gen_ai.response.model":Bt.modelId,"gen_ai.usage.input_tokens":Lt.inputTokens,"gen_ai.usage.output_tokens":Lt.outputTokens}}))}catch{}finally{or.end()}fe.enqueue({type:"finish-step",finishReason:yn,usage:Lt,providerMetadata:yc,response:{...Bt,headers:Be?.headers}});const uo=u0(Me,Lt);await D.promise;const po=ha.filter(sr=>sr.providerExecuted!==!0),ma=mc.filter(sr=>sr.providerExecuted!==!0);if(po.length>0&&ma.length===po.length&&!await y0({stopConditions:p,steps:V})){le.push(...ci({content:V[V.length-1].content,tools:c}));try{await K({currentStep:oe+1,responseMessages:le,usage:uo})}catch(sr){fe.enqueue({type:"error",error:sr}),H.closeStream()}}else fe.enqueue({type:"finish",finishReason:yn,totalUsage:uo}),H.closeStream()}})))}await K({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(W=>{H.addStream(new ReadableStream({start(K){K.enqueue({type:"error",error:W}),K.close()}})),H.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 qo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return qo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Z9({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 yp;return qo(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=Zr}={}){const c=t!=null?A9({originalMessages:e,responseMessageId:t}):void 0,u={},_=d=>{var p,v;const m=u[d];return((v=(p=this.tools)==null?void 0:p[m])==null?void 0:v.type)==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(d,p)=>{const v=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 w=_(d.id);p.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...w!=null?{dynamic:w}:{}});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 w=_(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}:{},...w!=null?{dynamic:w}:{},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}:{},...w!=null?{dynamic:w}:{}});break}case"tool-result":{const w=_(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}:{},...w!=null?{dynamic:w}:{}});break}case"tool-error":{const w=_(d.toolCallId);p.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...w!=null?{dynamic:w}:{}});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":{i&&p.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&p.enqueue({type:"finish",finishReason:d.finishReason,...v!=null?{messageMetadata:v}:{}});break}case"abort":{p.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const w=m;throw new Error(`Unknown chunk type: ${w}`)}}v!=null&&m!=="start"&&m!=="finish"&&p.enqueue({type:"message-metadata",messageMetadata:v})}}));return qo(D9({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}={}){z9({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){M9({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 N9({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 O9({textStream:this.textStream,...e})}};In({prefix:"aiobj",size:24}),In({prefix:"aiobj",size:24});var W9={};j3(W9,{object:()=>Y9,text:()=>K9});var K9=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Y9=({schema:e})=>{const t=Io(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:r}){const n=await E0(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 Cr({text:r});if(!o.success)throw new Pp({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 $t({value:o.value,schema:t});if(!s.success)throw new Pp({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 pi;pi=globalThis.crypto;async function Q9(e){return(await pi).getRandomValues(new Uint8Array(e))}async function X9(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await Q9(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function e4(e){return await X9(e)}async function t4(e){const t=await(await pi).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function x0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await e4(e),r=await t4(t);return{code_verifier:t,code_challenge:r}}var r4="AI_MCPClientError",R0=`vercel.ai.error.${r4}`,n4=Symbol.for(R0),P0,O0,Ie=class extends(O0=he,P0=n4,O0){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[P0]=!0,this.data=n,this.code=o}static isInstance(e){return he.hasMarker(e,R0)}},Qr="2025-06-18",o4=[Qr,"2025-03-26","2024-11-05"],s4=Ue({name:h(),version:h()}),Lo=Ue({_meta:ne($({}).loose())}),Jt=Lo,M0=$({method:h(),params:ne(Lo)}),N0=$({applyDefaults:ne(ce())}).loose(),a4=Ue({experimental:ne($({}).loose()),logging:ne($({}).loose()),prompts:ne(Ue({listChanged:ne(ce())})),resources:ne(Ue({subscribe:ne(ce()),listChanged:ne(ce())})),tools:ne(Ue({listChanged:ne(ce())})),elicitation:ne(N0)});$({elicitation:ne(N0)}).loose();var i4=Jt.extend({protocolVersion:h(),capabilities:a4,serverInfo:s4,instructions:ne(h())}),fi=Jt.extend({nextCursor:ne(h())}),l4=$({name:h(),description:ne(h()),inputSchema:$({type:q("object"),properties:ne($({}).loose())}).loose()}).loose(),c4=fi.extend({tools:N(l4)}),A0=$({type:q("text"),text:h()}).loose(),q0=$({type:q("image"),data:Ku(),mimeType:h()}).loose(),u4=$({uri:h(),name:h(),title:ne(h()),description:ne(h()),mimeType:ne(h()),size:ne(A())}).loose(),d4=fi.extend({resources:N(u4)}),L0=$({uri:h(),name:ne(h()),title:ne(h()),mimeType:ne(h())}).loose(),j0=L0.extend({text:h()}),U0=L0.extend({blob:Ku()}),D0=$({type:q("resource"),resource:re([j0,U0])}).loose(),p4=Jt.extend({content:N(re([A0,q0,D0])),isError:ce().default(!1).optional()}).or(Jt.extend({toolResult:ke()})),f4=$({uriTemplate:h(),name:h(),title:ne(h()),description:ne(h()),mimeType:ne(h())}).loose(),h4=Jt.extend({resourceTemplates:N(f4)}),m4=Jt.extend({contents:N(re([j0,U0]))}),g4=$({name:h(),description:ne(h()),required:ne(ce())}).loose(),_4=$({name:h(),title:ne(h()),description:ne(h()),arguments:ne(N(g4))}).loose(),y4=fi.extend({prompts:N(_4)}),v4=$({role:re([q("user"),q("assistant")]),content:re([A0,q0,D0])}).loose(),w4=Jt.extend({description:ne(h()),messages:N(v4)}),b4=Lo.extend({message:h(),requestedSchema:ke()}),z0=M0.extend({method:q("elicitation/create"),params:b4}),S4=Jt.extend({action:re([q("accept"),q("decline"),q("cancel")]),content:ne(me(h(),ke()))}),jo="2.0",k4=$({jsonrpc:q(jo),id:re([h(),A().int()])}).merge(M0).strict(),C4=$({jsonrpc:q(jo),id:re([h(),A().int()]),result:Jt}).strict(),$4=$({jsonrpc:q(jo),id:re([h(),A().int()]),error:$({code:A().int(),message:h(),data:ne(ke())})}).strict(),E4=$({jsonrpc:q(jo)}).merge($({method:h(),params:ne(Lo)})).strict(),Dn=re([k4,E4,C4,$4]),Z0=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",F0=$({access_token:h(),id_token:h().optional(),token_type:h(),expires_in:A().optional(),scope:h().optional(),refresh_token:h().optional()}).strip(),ct=h().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:id.custom,message:"URL must be parseable",fatal:!0}),su}).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"}),T4=$({resource:h().url(),authorization_servers:N(ct).optional(),jwks_uri:h().url().optional(),scopes_supported:N(h()).optional(),bearer_methods_supported:N(h()).optional(),resource_signing_alg_values_supported:N(h()).optional(),resource_name:h().optional(),resource_documentation:h().optional(),resource_policy_uri:h().url().optional(),resource_tos_uri:h().url().optional(),tls_client_certificate_bound_access_tokens:ce().optional(),authorization_details_types_supported:N(h()).optional(),dpop_signing_alg_values_supported:N(h()).optional(),dpop_bound_access_tokens_required:ce().optional()}).passthrough(),V0=$({issuer:h(),authorization_endpoint:ct,token_endpoint:ct,registration_endpoint:ct.optional(),scopes_supported:N(h()).optional(),response_types_supported:N(h()),grant_types_supported:N(h()).optional(),code_challenge_methods_supported:N(h()),token_endpoint_auth_methods_supported:N(h()).optional(),token_endpoint_auth_signing_alg_values_supported:N(h()).optional()}).passthrough(),I4=$({issuer:h(),authorization_endpoint:ct,token_endpoint:ct,userinfo_endpoint:ct.optional(),jwks_uri:ct,registration_endpoint:ct.optional(),scopes_supported:N(h()).optional(),response_types_supported:N(h()),grant_types_supported:N(h()).optional(),subject_types_supported:N(h()),id_token_signing_alg_values_supported:N(h()),claims_supported:N(h()).optional(),token_endpoint_auth_methods_supported:N(h()).optional()}).passthrough(),x4=I4.merge(V0.pick({code_challenge_methods_supported:!0})),R4=$({client_id:h(),client_secret:h().optional(),client_id_issued_at:A().optional(),client_secret_expires_at:A().optional()}).strip(),P4=$({redirect_uris:N(ct),token_endpoint_auth_method:h().optional(),grant_types:N(h()).optional(),response_types:N(h()).optional(),client_name:h().optional(),client_uri:ct.optional(),logo_uri:ct.optional(),scope:h().optional(),contacts:N(h()).optional(),tos_uri:ct.optional(),policy_uri:h().optional(),jwks_uri:ct.optional(),jwks:tt().optional(),software_id:h().optional(),software_version:h().optional(),software_statement:h().optional()}).strip(),O4=$({error:h(),error_description:h().optional(),error_uri:h().optional()}),M4=P4.merge(R4),N4="AI_MCPClientOAuthError",B0=`vercel.ai.error.${N4}`,A4=Symbol.for(B0),H0,J0,zn=class extends(J0=he,H0=A4,J0){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[H0]=!0}static isInstance(e){return he.hasMarker(e,B0)}},Xr=class extends zn{};Xr.errorCode="server_error";var Uo=class extends zn{};Uo.errorCode="invalid_client";var Do=class extends zn{};Do.errorCode="invalid_grant";var zo=class extends zn{};zo.errorCode="unauthorized_client";var q4={[Xr.errorCode]:Xr,[Uo.errorCode]:Uo,[Do.errorCode]:Do,[zo.errorCode]:zo};function L4(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function j4({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 Zo=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Fo(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 U4(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}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}}async function G0(e,t,r=fetch){return await hi(e,{"MCP-Protocol-Version":t},r)}function D4(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function z4(e,t,r,n){var o,s;const i=new URL(e),a=(o=n?.protocolVersion)!=null?o:Qr;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=U4(t,i.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:i),l.search=i.search}let c=await G0(l,a,r);if(!n?.metadataUrl&&D4(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await G0(u,a,r)}return c}async function Z4(e,t,r=fetch){const n=await z4(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 T4.parse(await n.json())}function F4(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 V4(e,{fetchFn:t=fetch,protocolVersion:r=Qr}={}){var n;const o={"MCP-Protocol-Version":r},s=F4(e);for(const{url:i,type:a}of s){const l=await hi(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 V0.parse(await l.json());{const c=x4.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 B4(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 x0(),_=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:_}}function W0(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 K0(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":H4(o,s,r);return;case"client_secret_post":J4(o,s,n);return;case"none":G4(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function H4(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 J4(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function G4(e,t){t.set("client_id",e)}async function mi(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=O4.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=q4[o]||Xr;return new a({message:s||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Xr({message:o})}}async function W4(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:a,fetchFn:l}){var c;const u="authorization_code",_=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"}),d=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(a)a(f,d,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],m=W0(r,v);K0(m,r,f,d)}i&&d.set("resource",i.href);const p=await(l??fetch)(_,{method:"POST",headers:f,body:d});if(!p.ok)throw await mi(p);return F0.parse(await p.json())}async function K4(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"}),_=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,_,e,t);else{const d=(a=t?.token_endpoint_auth_methods_supported)!=null?a:[],p=W0(r,d);K0(p,r,u,_)}o&&_.set("resource",o.href);const f=await(i??fetch)(c,{method:"POST",headers:u,body:_});if(!f.ok)throw await mi(f);return F0.parse({refresh_token:n,...await f.json()})}async function Y4(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 mi(s);return M4.parse(await s.json())}async function Vo(e,t){var r,n;try{return await gi(e,t)}catch(o){if(o instanceof Uo||o instanceof zo)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await gi(e,t);if(o instanceof Do)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await gi(e,t);throw o}}async function Q4(e,t,r){const n=L4(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!j4({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 gi(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await Z4(t,{resourceMetadataUrl:o},s),i.authorization_servers&&i.authorization_servers.length>0&&(a=i.authorization_servers[0])}catch{}a||(a=t);const l=await Q4(t,e,i),c=await V4(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 Y4(a,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),m=await W4(a,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}const _=await e.tokens();if(_?.refresh_token)try{const v=await K4(a,{metadata:c,clientInformation:u,refreshToken:_.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof zn)||v instanceof Xr))throw v}const f=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:p}=await B4(a,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(p),await e.redirectToAuthorization(d),"REDIRECT"}var X4=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 lr(t,`ai-sdk/${Z0}`,Rn())}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=Fo(u);try{if(await Vo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Zo;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(p){return(i=this.onerror)==null||i.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 v=new Ie({message:p});return(a=this.onerror)==null||a.call(this,v),t(v)}const f=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader(),d=async()=>{var p,v,m;try{for(;;){const{done:w,value:g}=await f.read();if(w){if(this.connected)throw this.connected=!1,new Ie({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 Ie({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=Dn.parse(JSON.parse(b));(p=this.onmessage)==null||p.call(this,S)}catch(S){const k=new Ie({message:"MCP SSE Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,k)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(m=this.onerror)==null||m.call(this,w),t(w)}};this.sseConnection={close:()=>f.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,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},_=await fetch(t,u);if(_.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Fo(_);try{if(await Vo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new Zo;(s=this.onerror)==null||s.call(this,d);return}}catch(f){(i=this.onerror)==null||i.call(this,f);return}return r(!0)}if(!_.ok){const f=await _.text().catch(()=>null),d=new Ie({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${_.status}): ${f}`});(a=this.onerror)==null||a.call(this,d);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},e6=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 lr(t,`ai-sdk/${Z0}`,Rn())}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,i,a,l,c;try{const _={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,_),d=f.headers.get("mcp-session-id");if(d&&(this.sessionId=d),f.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Fo(f);try{if(await Vo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Zo}catch(m){throw(o=this.onerror)==null||o.call(this,m),m}return t(!0)}if(f.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!f.ok){const m=await f.text().catch(()=>null);let w=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${f.status}): ${m}`;f.status===404&&(w+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new Ie({message:w});throw(s=this.onerror)==null||s.call(this,g),g}const p=f.headers.get("content-type")||"";if(p.includes("application/json")){const m=await f.json(),w=Array.isArray(m)?m.map(g=>Dn.parse(g)):[Dn.parse(m)];for(const g of w)(i=this.onmessage)==null||i.call(this,g);return}if(p.includes("text/event-stream")){if(!f.body){const y=new Ie({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 Vr).getReader();(async()=>{var y,b,S;try{for(;;){const{done:k,value:C}=await w.read();if(k)return;const{event:I,data:R}=C;if(I==="message")try{const L=Dn.parse(JSON.parse(R));(y=this.onmessage)==null||y.call(this,L)}catch(L){const O=new Ie({message:"MCP HTTP Transport Error: Failed to parse message",cause:L});(b=this.onerror)==null||b.call(this,O)}}}catch(k){if(k instanceof Error&&k.name==="AbortError")return;(S=this.onerror)==null||S.call(this,k)}})();return}const v=new Ie({message:`MCP HTTP Transport Error: Unexpected content type: ${p}`});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 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,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=Fo(c);try{if(await Vo(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new Zo;(n=this.onerror)==null||n.call(this,v);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 f=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Vr).getReader(),d=async()=>{var p,v,m,w;try{for(;;){const{done:g,value:y}=await f.read();if(g)return;const{event:b,data:S,id:k}=y;if(k&&(this.lastInboundEventId=k),b==="message")try{const C=Dn.parse(JSON.parse(S));(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});(v=this.onerror)==null||v.call(this,I)}}}catch(g){if(g instanceof Error&&g.name==="AbortError")return;(m=this.onerror)==null||m.call(this,g),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>f.cancel()},this.inboundReconnectAttempts=0,d()}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 t6(e){switch(e.type){case"sse":return new X4(e);case"http":return new e6(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 r6(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var n6="1.0.0";async function o6(e){const t=new s6(e);return await t.init(),t}var s6=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=n6,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},r6(e)?this.transport=e:this.transport=t6(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:i4});if(e===void 0)throw new Ie({message:"Server sent invalid initialize result"});if(!o4.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 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 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 _=new Ie({message:"Failed to parse server response",cause:u});o(_)}}),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:c4,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:p4,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:d4,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:m4,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:h4,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:y4,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:w4,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,_)=>{var f;return(f=_?.abortSignal)==null||f.throwIfAborted(),a.callTool({name:o,args:u,options:_})},c=e==="automatic"?gd({description:s,inputSchema:Pn({...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!==z0)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=z0.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=S4.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 Bo(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Y0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...Bo(t.headers),...Bo(n.headers)}:t.headers};return e(r,o)}:e}const Ho="2025-11-25",a6=[Ho,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Rr="io.modelcontextprotocol/related-task",Jo="2.0",He=sd(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Q0=re([h(),A().int()]),X0=h();Ue({ttl:re([A(),Ta()]).optional(),pollInterval:A().optional()});const i6=$({ttl:A().optional()}),l6=$({taskId:h()}),_i=Ue({progressToken:Q0.optional(),[Rr]:l6.optional()}),gt=$({_meta:_i.optional()}),Zn=gt.extend({task:i6.optional()}),c6=e=>Zn.safeParse(e).success,Je=$({method:h(),params:gt.loose().optional()}),wt=$({_meta:_i.optional()}),bt=$({method:h(),params:wt.loose().optional()}),Ge=Ue({_meta:_i.optional()}),Go=re([h(),A().int()]),ef=$({jsonrpc:q(Jo),id:Go,...Je.shape}).strict(),yi=e=>ef.safeParse(e).success,tf=$({jsonrpc:q(Jo),...bt.shape}).strict(),u6=e=>tf.safeParse(e).success,vi=$({jsonrpc:q(Jo),id:Go,result:Ge}).strict(),Fn=e=>vi.safeParse(e).success;var _e;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(_e||(_e={}));const wi=$({jsonrpc:q(Jo),id:Go.optional(),error:$({code:A().int(),message:h(),data:ke().optional()})}).strict(),d6=e=>wi.safeParse(e).success,Pr=re([ef,tf,vi,wi]);re([vi,wi]);const Or=Ge.strict(),p6=wt.extend({requestId:Go.optional(),reason:h().optional()}),bi=bt.extend({method:q("notifications/cancelled"),params:p6}),f6=$({src:h(),mimeType:h().optional(),sizes:N(h()).optional(),theme:be(["light","dark"]).optional()}),Vn=$({icons:N(f6).optional()}),en=$({name:h(),title:h().optional()}),rf=en.extend({...en.shape,...Vn.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),h6=Ia($({applyDefaults:ce().optional()}),me(h(),ke())),m6=ad(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ia($({form:h6.optional(),url:He.optional()}),me(h(),ke()).optional())),g6=Ue({list:He.optional(),cancel:He.optional(),requests:Ue({sampling:Ue({createMessage:He.optional()}).optional(),elicitation:Ue({create:He.optional()}).optional()}).optional()}),_6=Ue({list:He.optional(),cancel:He.optional(),requests:Ue({tools:Ue({call:He.optional()}).optional()}).optional()}),y6=$({experimental:me(h(),He).optional(),sampling:$({context:He.optional(),tools:He.optional()}).optional(),elicitation:m6.optional(),roots:$({listChanged:ce().optional()}).optional(),tasks:g6.optional()}),v6=gt.extend({protocolVersion:h(),capabilities:y6,clientInfo:rf}),w6=Je.extend({method:q("initialize"),params:v6}),b6=$({experimental:me(h(),He).optional(),logging:He.optional(),completions:He.optional(),prompts:$({listChanged:ce().optional()}).optional(),resources:$({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:$({listChanged:ce().optional()}).optional(),tasks:_6.optional()}),nf=Ge.extend({protocolVersion:h(),capabilities:b6,serverInfo:rf,instructions:h().optional()}),of=bt.extend({method:q("notifications/initialized"),params:wt.optional()}),S6=e=>of.safeParse(e).success,Si=Je.extend({method:q("ping"),params:gt.optional()}),k6=$({progress:A(),total:ne(A()),message:ne(h())}),C6=$({...wt.shape,...k6.shape,progressToken:Q0}),ki=bt.extend({method:q("notifications/progress"),params:C6}),$6=gt.extend({cursor:X0.optional()}),Bn=Je.extend({params:$6.optional()}),Hn=Ge.extend({nextCursor:X0.optional()}),E6=be(["working","input_required","completed","failed","cancelled"]),Jn=$({taskId:h(),status:E6,ttl:re([A(),Ta()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ne(A()),statusMessage:ne(h())}),Gn=Ge.extend({task:Jn}),T6=wt.merge(Jn),Wo=bt.extend({method:q("notifications/tasks/status"),params:T6}),Ci=Je.extend({method:q("tasks/get"),params:gt.extend({taskId:h()})}),$i=Ge.merge(Jn),Ei=Je.extend({method:q("tasks/result"),params:gt.extend({taskId:h()})});Ge.loose();const Ti=Bn.extend({method:q("tasks/list")}),Ii=Hn.extend({tasks:N(Jn)}),xi=Je.extend({method:q("tasks/cancel"),params:gt.extend({taskId:h()})}),I6=Ge.merge(Jn),sf=$({uri:h(),mimeType:ne(h()),_meta:me(h(),ke()).optional()}),af=sf.extend({text:h()}),Ri=h().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),lf=sf.extend({blob:Ri}),Wn=be(["user","assistant"]),tn=$({audience:N(Wn).optional(),priority:A().min(0).max(1).optional(),lastModified:Bu({offset:!0}).optional()}),cf=$({...en.shape,...Vn.shape,uri:h(),description:ne(h()),mimeType:ne(h()),annotations:tn.optional(),_meta:ne(Ue({}))}),x6=$({...en.shape,...Vn.shape,uriTemplate:h(),description:ne(h()),mimeType:ne(h()),annotations:tn.optional(),_meta:ne(Ue({}))}),R6=Bn.extend({method:q("resources/list")}),uf=Hn.extend({resources:N(cf)}),P6=Bn.extend({method:q("resources/templates/list")}),df=Hn.extend({resourceTemplates:N(x6)}),Pi=gt.extend({uri:h()}),O6=Pi,M6=Je.extend({method:q("resources/read"),params:O6}),pf=Ge.extend({contents:N(re([af,lf]))}),Oi=bt.extend({method:q("notifications/resources/list_changed"),params:wt.optional()}),N6=Pi,A6=Je.extend({method:q("resources/subscribe"),params:N6}),q6=Pi,L6=Je.extend({method:q("resources/unsubscribe"),params:q6}),j6=wt.extend({uri:h()}),ff=bt.extend({method:q("notifications/resources/updated"),params:j6}),U6=$({name:h(),description:ne(h()),required:ne(ce())}),D6=$({...en.shape,...Vn.shape,description:ne(h()),arguments:ne(N(U6)),_meta:ne(Ue({}))}),z6=Bn.extend({method:q("prompts/list")}),hf=Hn.extend({prompts:N(D6)}),Z6=gt.extend({name:h(),arguments:me(h(),h()).optional()}),F6=Je.extend({method:q("prompts/get"),params:Z6}),Mi=$({type:q("text"),text:h(),annotations:tn.optional(),_meta:me(h(),ke()).optional()}),Ni=$({type:q("image"),data:Ri,mimeType:h(),annotations:tn.optional(),_meta:me(h(),ke()).optional()}),Ai=$({type:q("audio"),data:Ri,mimeType:h(),annotations:tn.optional(),_meta:me(h(),ke()).optional()}),V6=$({type:q("tool_use"),name:h(),id:h(),input:me(h(),ke()),_meta:me(h(),ke()).optional()}),B6=$({type:q("resource"),resource:re([af,lf]),annotations:tn.optional(),_meta:me(h(),ke()).optional()}),H6=cf.extend({type:q("resource_link")}),qi=re([Mi,Ni,Ai,H6,B6]),J6=$({role:Wn,content:qi}),mf=Ge.extend({description:h().optional(),messages:N(J6)}),Li=bt.extend({method:q("notifications/prompts/list_changed"),params:wt.optional()}),G6=$({title:h().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),W6=$({taskSupport:be(["required","optional","forbidden"]).optional()}),gf=$({...en.shape,...Vn.shape,description:h().optional(),inputSchema:$({type:q("object"),properties:me(h(),He).optional(),required:N(h()).optional()}).catchall(ke()),outputSchema:$({type:q("object"),properties:me(h(),He).optional(),required:N(h()).optional()}).catchall(ke()).optional(),annotations:G6.optional(),execution:W6.optional(),_meta:me(h(),ke()).optional()}),K6=Bn.extend({method:q("tools/list")}),_f=Hn.extend({tools:N(gf)}),Kn=Ge.extend({content:N(qi).default([]),structuredContent:me(h(),ke()).optional(),isError:ce().optional()});Kn.or(Ge.extend({toolResult:ke()}));const Y6=Zn.extend({name:h(),arguments:me(h(),ke()).optional()}),Q6=Je.extend({method:q("tools/call"),params:Y6}),ji=bt.extend({method:q("notifications/tools/list_changed"),params:wt.optional()}),X6=$({autoRefresh:ce().default(!0),debounceMs:A().int().nonnegative().default(300)}),yf=be(["debug","info","notice","warning","error","critical","alert","emergency"]),e5=gt.extend({level:yf}),t5=Je.extend({method:q("logging/setLevel"),params:e5}),r5=wt.extend({level:yf,logger:h().optional(),data:ke()}),vf=bt.extend({method:q("notifications/message"),params:r5}),n5=$({name:h().optional()}),o5=$({hints:N(n5).optional(),costPriority:A().min(0).max(1).optional(),speedPriority:A().min(0).max(1).optional(),intelligencePriority:A().min(0).max(1).optional()}),s5=$({mode:be(["auto","required","none"]).optional()}),a5=$({type:q("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:N(qi).default([]),structuredContent:$({}).loose().optional(),isError:ce().optional(),_meta:me(h(),ke()).optional()}),i5=Ze("type",[Mi,Ni,Ai]),Ko=Ze("type",[Mi,Ni,Ai,V6,a5]),l5=$({role:Wn,content:re([Ko,N(Ko)]),_meta:me(h(),ke()).optional()}),c5=Zn.extend({messages:N(l5),modelPreferences:o5.optional(),systemPrompt:h().optional(),includeContext:be(["none","thisServer","allServers"]).optional(),temperature:A().optional(),maxTokens:A().int(),stopSequences:N(h()).optional(),metadata:He.optional(),tools:N(gf).optional(),toolChoice:s5.optional()}),Ui=Je.extend({method:q("sampling/createMessage"),params:c5}),Di=Ge.extend({model:h(),stopReason:ne(be(["endTurn","stopSequence","maxTokens"]).or(h())),role:Wn,content:i5}),wf=Ge.extend({model:h(),stopReason:ne(be(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:Wn,content:re([Ko,N(Ko)])}),u5=$({type:q("boolean"),title:h().optional(),description:h().optional(),default:ce().optional()}),d5=$({type:q("string"),title:h().optional(),description:h().optional(),minLength:A().optional(),maxLength:A().optional(),format:be(["email","uri","date","date-time"]).optional(),default:h().optional()}),p5=$({type:be(["number","integer"]),title:h().optional(),description:h().optional(),minimum:A().optional(),maximum:A().optional(),default:A().optional()}),f5=$({type:q("string"),title:h().optional(),description:h().optional(),enum:N(h()),default:h().optional()}),h5=$({type:q("string"),title:h().optional(),description:h().optional(),oneOf:N($({const:h(),title:h()})),default:h().optional()}),m5=$({type:q("string"),title:h().optional(),description:h().optional(),enum:N(h()),enumNames:N(h()).optional(),default:h().optional()}),g5=re([f5,h5]),_5=$({type:q("array"),title:h().optional(),description:h().optional(),minItems:A().optional(),maxItems:A().optional(),items:$({type:q("string"),enum:N(h())}),default:N(h()).optional()}),y5=$({type:q("array"),title:h().optional(),description:h().optional(),minItems:A().optional(),maxItems:A().optional(),items:$({anyOf:N($({const:h(),title:h()}))}),default:N(h()).optional()}),v5=re([_5,y5]),w5=re([m5,g5,v5]),b5=re([w5,u5,d5,p5]),S5=Zn.extend({mode:q("form").optional(),message:h(),requestedSchema:$({type:q("object"),properties:me(h(),b5),required:N(h()).optional()})}),k5=Zn.extend({mode:q("url"),message:h(),elicitationId:h(),url:h().url()}),C5=re([S5,k5]),zi=Je.extend({method:q("elicitation/create"),params:C5}),$5=wt.extend({elicitationId:h()}),E5=bt.extend({method:q("notifications/elicitation/complete"),params:$5}),Zi=Ge.extend({action:be(["accept","decline","cancel"]),content:ad(e=>e===null?void 0:e,me(h(),re([h(),A(),ce(),N(h())])).optional())}),T5=$({type:q("ref/resource"),uri:h()}),I5=$({type:q("ref/prompt"),name:h()}),x5=gt.extend({ref:re([I5,T5]),argument:$({name:h(),value:h()}),context:$({arguments:me(h(),h()).optional()}).optional()}),R5=Je.extend({method:q("completion/complete"),params:x5}),bf=Ge.extend({completion:Ue({values:N(h()).max(100),total:ne(A().int()),hasMore:ne(ce())})}),P5=$({uri:h().startsWith("file://"),name:h().optional(),_meta:me(h(),ke()).optional()}),Sf=Je.extend({method:q("roots/list"),params:gt.optional()}),kf=Ge.extend({roots:N(P5)}),O5=bt.extend({method:q("notifications/roots/list_changed"),params:wt.optional()});re([Si,w6,R5,t5,F6,z6,R6,P6,M6,A6,L6,Q6,K6,Ci,Ei,Ti,xi]),re([bi,ki,of,O5,Wo]),re([Or,Di,wf,Zi,kf,$i,Ii,Gn]),re([Si,Ui,zi,Sf,Ci,Ei,Ti,xi]),re([bi,ki,vf,ff,Oi,ji,Li,Wo,E5]),re([Or,nf,bf,mf,hf,uf,df,pf,Kn,_f,$i,Ii,Gn]);class ue extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===_e.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new M5(o.elicitations,r)}return new ue(t,r,n)}}class M5 extends ue{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(_e.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const We=Gy().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:id.custom,message:"URL must be parseable",fatal:!0}),su}).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"}),N5=Ue({resource:h().url(),authorization_servers:N(We).optional(),jwks_uri:h().url().optional(),scopes_supported:N(h()).optional(),bearer_methods_supported:N(h()).optional(),resource_signing_alg_values_supported:N(h()).optional(),resource_name:h().optional(),resource_documentation:h().optional(),resource_policy_uri:h().url().optional(),resource_tos_uri:h().url().optional(),tls_client_certificate_bound_access_tokens:ce().optional(),authorization_details_types_supported:N(h()).optional(),dpop_signing_alg_values_supported:N(h()).optional(),dpop_bound_access_tokens_required:ce().optional()}),Cf=Ue({issuer:h(),authorization_endpoint:We,token_endpoint:We,registration_endpoint:We.optional(),scopes_supported:N(h()).optional(),response_types_supported:N(h()),response_modes_supported:N(h()).optional(),grant_types_supported:N(h()).optional(),token_endpoint_auth_methods_supported:N(h()).optional(),token_endpoint_auth_signing_alg_values_supported:N(h()).optional(),service_documentation:We.optional(),revocation_endpoint:We.optional(),revocation_endpoint_auth_methods_supported:N(h()).optional(),revocation_endpoint_auth_signing_alg_values_supported:N(h()).optional(),introspection_endpoint:h().optional(),introspection_endpoint_auth_methods_supported:N(h()).optional(),introspection_endpoint_auth_signing_alg_values_supported:N(h()).optional(),code_challenge_methods_supported:N(h()).optional(),client_id_metadata_document_supported:ce().optional()}),A5=Ue({issuer:h(),authorization_endpoint:We,token_endpoint:We,userinfo_endpoint:We.optional(),jwks_uri:We,registration_endpoint:We.optional(),scopes_supported:N(h()).optional(),response_types_supported:N(h()),response_modes_supported:N(h()).optional(),grant_types_supported:N(h()).optional(),acr_values_supported:N(h()).optional(),subject_types_supported:N(h()),id_token_signing_alg_values_supported:N(h()),id_token_encryption_alg_values_supported:N(h()).optional(),id_token_encryption_enc_values_supported:N(h()).optional(),userinfo_signing_alg_values_supported:N(h()).optional(),userinfo_encryption_alg_values_supported:N(h()).optional(),userinfo_encryption_enc_values_supported:N(h()).optional(),request_object_signing_alg_values_supported:N(h()).optional(),request_object_encryption_alg_values_supported:N(h()).optional(),request_object_encryption_enc_values_supported:N(h()).optional(),token_endpoint_auth_methods_supported:N(h()).optional(),token_endpoint_auth_signing_alg_values_supported:N(h()).optional(),display_values_supported:N(h()).optional(),claim_types_supported:N(h()).optional(),claims_supported:N(h()).optional(),service_documentation:h().optional(),claims_locales_supported:N(h()).optional(),ui_locales_supported:N(h()).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:We.optional(),op_tos_uri:We.optional(),client_id_metadata_document_supported:ce().optional()}),q5=$({...A5.shape,...Cf.pick({code_challenge_methods_supported:!0}).shape}),L5=$({access_token:h(),id_token:h().optional(),token_type:h(),expires_in:ld().optional(),scope:h().optional(),refresh_token:h().optional()}).strip(),j5=$({error:h(),error_description:h().optional(),error_uri:h().optional()}),$f=We.optional().or(q("").transform(()=>{})),U5=$({redirect_uris:N(We),token_endpoint_auth_method:h().optional(),grant_types:N(h()).optional(),response_types:N(h()).optional(),client_name:h().optional(),client_uri:We.optional(),logo_uri:$f,scope:h().optional(),contacts:N(h()).optional(),tos_uri:$f,policy_uri:h().optional(),jwks_uri:We.optional(),jwks:tt().optional(),software_id:h().optional(),software_version:h().optional(),software_statement:h().optional()}).strip(),D5=$({client_id:h(),client_secret:h().optional(),client_id_issued_at:A().optional(),client_secret_expires_at:A().optional()}).strip(),z5=U5.merge(D5);$({error:h(),error_description:h().optional()}).strip(),$({token:h(),token_type_hint:h().optional()}).strip();function Z5(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function F5({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 Fi extends Ve{}Fi.errorCode="invalid_request";class Yo extends Ve{}Yo.errorCode="invalid_client";class Qo extends Ve{}Qo.errorCode="invalid_grant";class Xo extends Ve{}Xo.errorCode="unauthorized_client";class Vi extends Ve{}Vi.errorCode="unsupported_grant_type";class Bi extends Ve{}Bi.errorCode="invalid_scope";class Hi extends Ve{}Hi.errorCode="access_denied";class rn extends Ve{}rn.errorCode="server_error";class Ji extends Ve{}Ji.errorCode="temporarily_unavailable";class Gi extends Ve{}Gi.errorCode="unsupported_response_type";class Wi extends Ve{}Wi.errorCode="unsupported_token_type";class Ki extends Ve{}Ki.errorCode="invalid_token";class Yi extends Ve{}Yi.errorCode="method_not_allowed";class Qi extends Ve{}Qi.errorCode="too_many_requests";class es extends Ve{}es.errorCode="invalid_client_metadata";class Xi extends Ve{}Xi.errorCode="insufficient_scope";class el extends Ve{}el.errorCode="invalid_target";const V5={[Fi.errorCode]:Fi,[Yo.errorCode]:Yo,[Qo.errorCode]:Qo,[Xo.errorCode]:Xo,[Vi.errorCode]:Vi,[Bi.errorCode]:Bi,[Hi.errorCode]:Hi,[rn.errorCode]:rn,[Ji.errorCode]:Ji,[Gi.errorCode]:Gi,[Wi.errorCode]:Wi,[Ki.errorCode]:Ki,[Yi.errorCode]:Yi,[Qi.errorCode]:Qi,[es.errorCode]:es,[Xi.errorCode]:Xi,[el.errorCode]:el};class St extends Error{constructor(t){super(t??"Unauthorized")}}function B5(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const tl="code",rl="S256";function H5(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&&B5(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 J5(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":G5(o,s,r);return;case"client_secret_post":W5(o,s,n);return;case"none":K5(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function G5(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 W5(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function K5(e,t){t.set("client_id",e)}async function Ef(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=j5.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=V5[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 Mr(e,t){try{return await nl(e,t)}catch(r){if(r instanceof Yo||r instanceof Xo)return await e.invalidateCredentials?.("all"),await nl(e,t);if(r instanceof Qo)return await e.invalidateCredentials?.("tokens"),await nl(e,t);throw r}}async function nl(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await X5(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 Q5(t,e,i),c=await o8(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 m=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!Y5(w))throw new es(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(m&&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 c8(a,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(y),u=y}}const _=!e.redirectUrl;if(r!==void 0||_){const m=await l8(e,a,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}const f=await e.tokens();if(f?.refresh_token)try{const m=await i8(a,{metadata:c,clientInformation:u,refreshToken:f.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(m),"AUTHORIZED"}catch(m){if(!(!(m instanceof Ve)||m instanceof rn))throw m}const d=e.state?await e.state():void 0,{authorizationUrl:p,codeVerifier:v}=await s8(a,{metadata:c,clientInformation:u,state:d,redirectUrl:e.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(p),"REDIRECT"}function Y5(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Q5(e,t,r){const n=Z5(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!F5({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 ts(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=ol(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=ol(e,"scope")||void 0,a=ol(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function ol(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 X5(e,t,r=fetch){const n=await r8(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 N5.parse(await n.json())}async function sl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?sl(e,void 0,r):void 0;throw n}}function e8(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Tf(e,t,r=fetch){return await sl(e,{"MCP-Protocol-Version":t},r)}function t8(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function r8(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??Ho;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=e8(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await Tf(i,s,r);if(!n?.metadataUrl&&t8(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await Tf(l,s,r)}return a}function n8(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 o8(e,{fetchFn:t=fetch,protocolVersion:r=Ho}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=n8(e);for(const{url:s,type:i}of o){const a=await sl(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"?Cf.parse(await a.json()):q5.parse(await a.json())}}}async function s8(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(tl))throw new Error(`Incompatible auth server: does not support response type ${tl}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(rl))throw new Error(`Incompatible auth server: does not support code challenge method ${rl}`)}else a=new URL("/authorize",e);const l=await x0(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",tl),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",rl),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 a8(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function If(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??[],_=H5(n,u);J5(_,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await Ef(c);return L5.parse(await c.json())}async function i8(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 If(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function l8(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=a8(o,c,e.redirectUrl)}const l=await e.clientInformation();return If(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function c8(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 Ef(s);return z5.parse(await s.json())}const u8={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 rs{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=Y0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??u8}async _authThenStart(){if(!this._authProvider)throw new St("No auth provider");let t;try{t=await Mr(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 St;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=Bo(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 nn(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 Vr({onRetry:d=>{this._serverRetryMs=d}})).getReader();for(;;){const{value:d,done:p}=await u.read();if(p)break;if(d.id&&(i=d.id,a=!0,o?.(d.id)),!!d.data&&(!d.event||d.event==="message"))try{const v=Pr.parse(JSON.parse(d.data));Fn(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(d){this.onerror?.(new Error(`Failed to reconnect: ${d instanceof Error?d.message:String(d)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new St("No auth provider");if(await Mr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new St("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:yi(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 nn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:d,scope:p}=ts(a);if(this._resourceMetadataUrl=d,this._scope=p,await Mr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new St;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){const{resourceMetadataUrl:d,scope:p,error:v}=ts(a);if(v==="insufficient_scope"){const m=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===m)throw new nn(403,"Server returned 403 after trying upscoping");if(p&&(this._scope=p),d&&(this._resourceMetadataUrl=d),this._lastUpscopingHeader=m??void 0,await Mr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new St;return this.send(t)}}throw new nn(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),S6(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,_=a.headers.get("content-type");if(u)if(_?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(_?.includes("application/json")){const f=await a.json(),d=Array.isArray(f)?f.map(p=>Pr.parse(p)):[Pr.parse(f)];for(const p of d)this.onmessage?.(p)}else throw await a.body?.cancel(),new nn(-1,`Unexpected content type: ${_}`);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 nn(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class ns{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new ns,r=new ns;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}var xf="vercel.ai.error",d8=Symbol.for(xf),Rf,Pf,De=class I1 extends(Pf=Error,Rf=d8,Pf){constructor({name:t,message:r,cause:n}){super(r),this[Rf]=!0,this.name=t,this.cause=n}static isInstance(t){return I1.hasMarker(t,xf)}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}},Of="AI_APICallError",Mf=`vercel.ai.error.${Of}`,p8=Symbol.for(Mf),Nf,Af,kt=class extends(Af=De,Nf=p8,Af){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:Of,message:e,cause:i}),this[Nf]=!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 De.hasMarker(e,Mf)}},qf="AI_EmptyResponseBodyError",Lf=`vercel.ai.error.${qf}`,f8=Symbol.for(Lf),jf,Uf,h8=class extends(Uf=De,jf=f8,Uf){constructor({message:e="Empty response body"}={}){super({name:qf,message:e}),this[jf]=!0}static isInstance(e){return De.hasMarker(e,Lf)}};function Df(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var zf="AI_InvalidArgumentError",Zf=`vercel.ai.error.${zf}`,m8=Symbol.for(Zf),Ff,Vf,Bf=class extends(Vf=De,Ff=m8,Vf){constructor({message:e,cause:t,argument:r}){super({name:zf,message:e,cause:t}),this[Ff]=!0,this.argument=r}static isInstance(e){return De.hasMarker(e,Zf)}},Hf="AI_InvalidPromptError",Jf=`vercel.ai.error.${Hf}`,g8=Symbol.for(Jf),Gf,Wf,_8=class extends(Wf=De,Gf=g8,Wf){constructor({prompt:e,message:t,cause:r}){super({name:Hf,message:`Invalid prompt: ${t}`,cause:r}),this[Gf]=!0,this.prompt=e}static isInstance(e){return De.hasMarker(e,Jf)}},Kf="AI_InvalidResponseDataError",Yf=`vercel.ai.error.${Kf}`,y8=Symbol.for(Yf),Qf,Xf,al=class extends(Xf=De,Qf=y8,Xf){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Kf,message:t}),this[Qf]=!0,this.data=e}static isInstance(e){return De.hasMarker(e,Yf)}},eh="AI_JSONParseError",th=`vercel.ai.error.${eh}`,v8=Symbol.for(th),rh,nh,os=class extends(nh=De,rh=v8,nh){constructor({text:e,cause:t}){super({name:eh,message:`JSON parsing failed: Text: ${e}.
58
- Error message: ${Df(t)}`,cause:t}),this[rh]=!0,this.text=e}static isInstance(e){return De.hasMarker(e,th)}},oh="AI_LoadAPIKeyError",sh=`vercel.ai.error.${oh}`,w8=Symbol.for(sh),ah,ih,ss=class extends(ih=De,ah=w8,ih){constructor({message:e}){super({name:oh,message:e}),this[ah]=!0}static isInstance(e){return De.hasMarker(e,sh)}},lh="AI_TooManyEmbeddingValuesForCallError",ch=`vercel.ai.error.${lh}`,b8=Symbol.for(ch),uh,dh,S8=class extends(dh=De,uh=b8,dh){constructor(e){super({name:lh,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[uh]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return De.hasMarker(e,ch)}},ph="AI_TypeValidationError",fh=`vercel.ai.error.${ph}`,k8=Symbol.for(fh),hh,mh,Yn=class bc extends(mh=De,hh=k8,mh){constructor({value:t,cause:r}){super({name:ph,message:`Type validation failed: Value: ${JSON.stringify(t)}.
59
- Error message: ${Df(r)}`,cause:r}),this[hh]=!0,this.value=t}static isInstance(t){return De.hasMarker(t,fh)}static wrap({value:t,cause:r}){return bc.isInstance(r)&&r.value===t?r:new bc({value:t,cause:r})}},gh="AI_UnsupportedFunctionalityError",_h=`vercel.ai.error.${gh}`,C8=Symbol.for(_h),yh,vh,Gt=class extends(vh=De,yh=C8,vh){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:gh,message:t}),this[yh]=!0,this.functionality=e}static isInstance(e){return De.hasMarker(e,_h)}};function Zt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Qn(e){return Object.fromEntries([...e.headers])}var $8=({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 Bf({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},It=$8();function il(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var E8=["fetch failed","failed to fetch"];function T8({error:e,url:t,requestBodyValues:r}){if(il(e))return e;if(e instanceof TypeError&&E8.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new kt({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function I8(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 x8(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 wh(e,...t){const r=new Headers(x8(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var R8="3.0.20";function P8({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ss({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ss({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 ss({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ss({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function O8({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 M8(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 N8=/"__proto__"\s*:/,A8=/"constructor"\s*:/;function bh(e){const t=JSON.parse(e);return t===null||typeof t!="object"||N8.test(e)===!1&&A8.test(e)===!1?t:q8(t)}function q8(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 ll(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return bh(e)}try{return bh(e)}finally{Error.stackTraceLimit=t}}var as=Symbol.for("vercel.ai.validator");function L8(e){return{[as]:!0,validate:e}}function j8(e){return typeof e=="object"&&e!==null&&as in e&&e[as]===!0&&"validate"in e}function nt(e){let t;return()=>(t==null&&(t=e()),t)}function U8(e){return j8(e)?e:typeof e=="function"?e():D8(e)}function D8(e){return L8(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Yn({value:t,cause:r.issues})}})}async function ur({value:e,schema:t}){const r=await cl({value:e,schema:t});if(!r.success)throw Yn.wrap({value:e,cause:r.error});return r.value}async function cl({value:e,schema:t}){const r=U8(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:Yn.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Yn.wrap({value:e,cause:n}),rawValue:e}}}async function z8({text:e,schema:t}){try{const r=ll(e);return t==null?r:ur({value:r,schema:t})}catch(r){throw os.isInstance(r)||Yn.isInstance(r)?r:new os({text:e,cause:r})}}async function Sh({text:e,schema:t}){try{const r=ll(e);return t==null?{success:!0,value:r,rawValue:r}:await cl({value:r,schema:t})}catch(r){return{success:!1,error:os.isInstance(r)?r:new os({text:e,cause:r}),rawValue:void 0}}}function kh(e){try{return ll(e),!0}catch{return!1}}function Z8({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 Sh({text:r,schema:t}))}}))}async function dr({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await cl({value:t[e],schema:r});if(!n.success)throw new Bf({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var F8=()=>globalThis.fetch,Wt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Ch({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),V8=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Ch({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Ch=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=F8()})=>{try{const a=await i(e,{method:"POST",headers:wh(t,`ai-sdk/provider-utils/${R8}`,I8()),body:r.content,signal:s}),l=Qn(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw il(u)||kt.isInstance(u)?u:new kt({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)||kt.isInstance(c))?c:new kt({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw T8({error:a,url:e,requestBodyValues:r.values})}};function A$(e){return e}function on({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 B8=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=Qn(n);if(i.trim()==="")return{responseHeaders:a,value:new kt({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await z8({text:i,schema:e});return{responseHeaders:a,value:new kt({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 kt({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},ul=e=>async({response:t})=>{const r=Qn(t);if(t.body==null)throw new h8({});return{responseHeaders:r,value:Z8({stream:t.body,schema:e})}},sn=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Sh({text:o,schema:e}),i=Qn(t);if(!s.success)throw new kt({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}},H8=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Qn(e);if(!e.body)throw new kt({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 kt({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function is(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const r in t)t[r]=is(t[r])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>is(t)):e.items=is(e.items)),e}var J8=(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("/")},G8=Symbol("Let zodToJsonSchema decide on which parser to use"),$h={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"},W8=e=>typeof e=="string"?{...$h,name:e}:{...$h,...e};function _t(){return{}}function K8(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)!==Y.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 Y8(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 Q8(){return{type:"boolean"}}function Eh(e,t){return xe(e.type._def,t)}var X8=(e,t)=>xe(e.innerType._def,t);function Th(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Th(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 e7(e)}}var e7=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 t7(e,t){return{...xe(e.innerType._def,t),default:e.defaultValue()}}function r7(e,t){return t.effectStrategy==="input"?xe(e.schema._def,t):_t()}function n7(e){return{type:"string",enum:Array.from(e.values)}}var o7=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function s7(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(o7(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 a7(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 dl=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:()=>(dl===void 0&&(dl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dl),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 Ih(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":ot(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":ot(r,n.regex,n.message,t);break;case"cuid":ot(r,xt.cuid,n.message,t);break;case"cuid2":ot(r,xt.cuid2,n.message,t);break;case"startsWith":ot(r,RegExp(`^${pl(n.value,t)}`),n.message,t);break;case"endsWith":ot(r,RegExp(`${pl(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":{ot(r,RegExp(pl(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":ot(r,xt.base64url,n.message,t);break;case"jwt":ot(r,xt.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&ot(r,xt.ipv4Cidr,n.message,t),n.version!=="v4"&&ot(r,xt.ipv6Cidr,n.message,t);break}case"emoji":ot(r,xt.emoji(),n.message,t);break;case"ulid":{ot(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":{ot(r,xt.base64,n.message,t);break}}break}case"nanoid":ot(r,xt.nanoid,n.message,t)}return r}function pl(e,t){return t.patternStrategy==="escape"?l7(e):e}var i7=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function l7(e){let t="";for(let r=0;r<e.length;r++)i7.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 ot(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:xh(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=xh(t,n)}function xh(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
60
- ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
61
- ]))`;continue}}if(n.s&&o[c]==="."){s+=a?`${o[c]}\r
62
- `:`[${o[c]}\r
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 Rh(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)===Y.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Ih(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===Y.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===Y.ZodBranded&&e.keyType._def.type._def.typeName===Y.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=Eh(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function c7(e,t){if(t.mapStrategy==="record")return Rh(e,t);const r=xe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||_t(),n=xe(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 u7(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 d7(){return{not:_t()}}function p7(){return{type:"null"}}var fl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function f7(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in fl&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const i=fl[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 h7(e,t)}var h7=(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 m7(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[fl[e.innerType._def.typeName],"null"]};const r=xe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function g7(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 _7(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=v7(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=y7(e,t);return s!==void 0&&(r.additionalProperties=s),r}function y7(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 v7(e){try{return e.isOptional()}catch{return!0}}var w7=(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:_t()},n]}:_t()},b7=(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 S7(e,t){return xe(e.type._def,t)}function k7(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 C7(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 $7(){return{not:_t()}}function E7(){return _t()}var T7=(e,t)=>xe(e.innerType._def,t),I7=(e,t,r)=>{switch(t){case Y.ZodString:return Ih(e,r);case Y.ZodNumber:return g7(e);case Y.ZodObject:return _7(e,r);case Y.ZodBigInt:return Y8(e);case Y.ZodBoolean:return Q8();case Y.ZodDate:return Th(e,r);case Y.ZodUndefined:return $7();case Y.ZodNull:return p7();case Y.ZodArray:return K8(e,r);case Y.ZodUnion:case Y.ZodDiscriminatedUnion:return f7(e,r);case Y.ZodIntersection:return s7(e,r);case Y.ZodTuple:return C7(e,r);case Y.ZodRecord:return Rh(e,r);case Y.ZodLiteral:return a7(e);case Y.ZodEnum:return n7(e);case Y.ZodNativeEnum:return u7(e);case Y.ZodNullable:return m7(e,r);case Y.ZodOptional:return w7(e,r);case Y.ZodMap:return c7(e,r);case Y.ZodSet:return k7(e,r);case Y.ZodLazy:return()=>e.getter()._def;case Y.ZodPromise:return S7(e,r);case Y.ZodNaN:case Y.ZodNever:return d7();case Y.ZodEffects:return r7(e,r);case Y.ZodAny:return _t();case Y.ZodUnknown:return E7();case Y.ZodDefault:return t7(e,r);case Y.ZodBranded:return Eh(e,r);case Y.ZodReadonly:return T7(e,r);case Y.ZodCatch:return X8(e,r);case Y.ZodPipeline:return b7(e,r);case Y.ZodFunction:case Y.ZodVoid:case Y.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!==G8)return l}if(o&&!r){const l=x7(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=I7(e,e.typeName,t),a=typeof i=="function"?xe(i(),t):i;if(a&&R7(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var x7=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:J8(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}},R7=(e,t,r)=>(e.description&&(r.description=e.description),r),P7=e=>{const t=W8(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}]))}},O7=(e,t)=>{var r;const n=P7(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,_])=>{var f;return{...c,[u]:(f=xe(_._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=xe(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},M7=O7;function N7(e,t){var r;const n=(r=void 0)!=null?r:!1;return Ph(()=>M7(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 A7(e,t){var r;const n=(r=void 0)!=null?r:!1;return Ph(()=>is(Vu(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 q7(e){return"_zod"in e}function $e(e,t){return q7(e)?A7(e):N7(e)}var L7=Symbol.for("vercel.ai.schema");function Xe(e){let t;return()=>(t==null&&(t=e()),t)}function Ph(e,{validate:t}={}){return{[L7]:!0,_type:void 0,[as]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}var{btoa:j7,atob:U7}=globalThis;function D7(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=U7(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function z7(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return j7(t)}function an(e){return e instanceof Uint8Array?z7(e):e}function Z7(e){return e?.replace(/\/$/,"")}var hl=$({error:$({message:h(),type:h().nullish(),param:tt().nullish(),code:re([h(),A()]).nullish()})}),Ft=B8({errorSchema:hl,errorToMessage:e=>e.error.message});function Oh(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 F7({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 _=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${_};base64,${an(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 Gt({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:an(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:an(i.data),format:"mp3"}};default:throw new Gt({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new Gt({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,${an(i.data)}`}}}else throw new Gt({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 ml({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function Mh(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 V7=nt(()=>$e($({id:h().nullish(),created:A().nullish(),model:h().nullish(),choices:N($({message:$({role:q("assistant").nullish(),content:h().nullish(),tool_calls:N($({id:h().nullish(),type:q("function"),function:$({name:h(),arguments:h()})})).nullish(),annotations:N($({type:q("url_citation"),url_citation:$({start_index:A(),end_index:A(),url:h(),title:h()})})).nullish()}),index:A(),logprobs:$({content:N($({token:h(),logprob:A(),top_logprobs:N($({token:h(),logprob:A()}))})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:$({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:$({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:$({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}))),B7=nt(()=>$e(re([$({id:h().nullish(),created:A().nullish(),model:h().nullish(),choices:N($({delta:$({role:be(["assistant"]).nullish(),content:h().nullish(),tool_calls:N($({index:A(),id:h().nullish(),type:q("function").nullish(),function:$({name:h().nullish(),arguments:h().nullish()})})).nullish(),annotations:N($({type:q("url_citation"),url_citation:$({start_index:A(),end_index:A(),url:h(),title:h()})})).nullish()}).nullish(),logprobs:$({content:N($({token:h(),logprob:A(),top_logprobs:N($({token:h(),logprob:A()}))})).nullish()}).nullish(),finish_reason:h().nullish(),index:A()})),usage:$({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:$({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:$({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish()}),hl]))),H7=nt(()=>$e($({logitBias:me(ld(),A()).optional(),logprobs:re([ce(),A()]).optional(),parallelToolCalls:ce().optional(),user:h().optional(),reasoningEffort:be(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:A().optional(),store:ce().optional(),metadata:me(h().max(64),h().max(512)).optional(),prediction:me(h(),tt()).optional(),structuredOutputs:ce().optional(),serviceTier:be(["auto","flex","priority","default"]).optional(),strictJsonSchema:ce().optional(),textVerbosity:be(["low","medium","high"]).optional(),promptCacheKey:h().optional(),promptCacheRetention:be(["in_memory","24h"]).optional(),safetyIdentifier:h().optional()})));function J7({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 Gt({functionality:`tool choice type: ${a}`})}}}var G7=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:_,providerOptions:f}){var d,p,v,m;const w=[],g=(d=await dr({provider:"openai",providerOptions:f,schema:H7}))!=null?d:{},y=(p=g.structuredOutputs)!=null?p:!0,b=Oh(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:k}=F7({prompt:e,systemMessageMode:b.systemMessageMode});w.push(...k);const C=(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:C,name:(m=l.name)!=null?m:"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:R,toolChoice:L,toolWarnings:O}=J7({tools:u,toolChoice:_,structuredOutputs:y,strictJsonSchema:C});return{args:{...I,tools:R,tool_choice:L},warnings:[...w,...O]}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,_,f,d,p;const{args:v,warnings:m}=await this.getArgs(e),{responseHeaders:w,value:g,rawValue:y}=await Wt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Zt(this.config.headers(),e.headers),body:v,failedResponseHandler:Ft,successfulResponseHandler:sn(V7),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=g.choices[0],S=[],k=b.message.content;k!=null&&k.length>0&&S.push({type:"text",text:k});for(const L of(t=b.message.tool_calls)!=null?t:[])S.push({type:"tool-call",toolCallId:(r=L.id)!=null?r:It(),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:It(),url:L.url_citation.url,title:L.url_citation.title});const C=(o=g.usage)==null?void 0:o.completion_tokens_details,I=(s=g.usage)==null?void 0:s.prompt_tokens_details,R={openai:{}};return C?.accepted_prediction_tokens!=null&&(R.openai.acceptedPredictionTokens=C?.accepted_prediction_tokens),C?.rejected_prediction_tokens!=null&&(R.openai.rejectedPredictionTokens=C?.rejected_prediction_tokens),((i=b.logprobs)==null?void 0:i.content)!=null&&(R.openai.logprobs=b.logprobs.content),{content:S,finishReason:Mh(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=(_=g.usage)==null?void 0:_.total_tokens)!=null?f:void 0,reasoningTokens:(d=C?.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(p=I?.cached_tokens)!=null?p:void 0},request:{body:v},response:{...ml(g),headers:w,body:y},warnings:m,providerMetadata:R}}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 Wt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Zt(this.config.headers(),e.headers),body:n,failedResponseHandler:Ft,successfulResponseHandler:ul(B7),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 _={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,d){var p,v,m,w,g,y,b,S,k,C,I,R,L,O,U,D,F,ee,ie,se,X,de,V,P;if(e.includeRawChunks&&d.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){a="error",d.enqueue({type:"error",error:f.error});return}const Z=f.value;if("error"in Z){a="error",d.enqueue({type:"error",error:Z.error});return}if(!c){const x=ml(Z);Object.values(x).some(Boolean)&&(c=!0,d.enqueue({type:"response-metadata",...ml(Z)}))}Z.usage!=null&&(l.inputTokens=(p=Z.usage.prompt_tokens)!=null?p:void 0,l.outputTokens=(v=Z.usage.completion_tokens)!=null?v:void 0,l.totalTokens=(m=Z.usage.total_tokens)!=null?m: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&&(_.openai.acceptedPredictionTokens=(k=Z.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens),((C=Z.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens)!=null&&(_.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&&(a=Mh(j.finish_reason)),((R=j?.logprobs)==null?void 0:R.content)!=null&&(_.openai.logprobs=j.logprobs.content),j?.delta==null)return;const T=j.delta;if(T.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.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 al({data:x,message:"Expected 'function' type."});if(x.id==null)throw new al({data:x,message:"Expected 'id' to be a string."});if(((L=x.function)==null?void 0:L.name)==null)throw new al({data:x,message:"Expected 'function.name' to be a string."});d.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:(O=x.function.arguments)!=null?O:""},hasFinished:!1};const G=i[E];((U=G.function)==null?void 0:U.name)!=null&&((D=G.function)==null?void 0:D.arguments)!=null&&(G.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:G.id,delta:G.function.arguments}),kh(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 B=i[E];B.hasFinished||(((ee=x.function)==null?void 0:ee.arguments)!=null&&(B.function.arguments+=(se=(ie=x.function)==null?void 0:ie.arguments)!=null?se:""),d.enqueue({type:"tool-input-delta",id:B.id,delta:(X=x.function.arguments)!=null?X:""}),((de=B.function)==null?void 0:de.name)!=null&&((V=B.function)==null?void 0:V.arguments)!=null&&kh(B.function.arguments)&&(d.enqueue({type:"tool-input-end",id:B.id}),d.enqueue({type:"tool-call",toolCallId:(P=B.id)!=null?P:It(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}if(T.annotations!=null)for(const x of T.annotations)d.enqueue({type:"source",sourceType:"url",id:It(),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,..._!=null?{providerMetadata:_}:{}})}})),request:{body:n},response:{headers:o}}}};function W7({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
68
+ `)}})}},rm={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function c5({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new tm);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Xs(r,rm)})}function u5({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 d5(e){return e.type.startsWith("data-")}function Fl(e){return e.type.startsWith("tool-")}function p5(e){return e.type==="dynamic-tool"}function f5(e){return Fl(e)||p5(e)}function nm(e){return e.type.split("-").slice(1).join("-")}function h5({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function m5({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var m,p,f,g;function v(h){const k=c.message.parts.filter(f5).find(C=>C.toolCallId===h);if(k==null)throw new Xn({chunkType:"tool-invocation",chunkId:h,message:`No tool invocation found for tool call ID "${h}".`});return k}function y(h){var S;const k=c.message.parts.find(E=>Fl(E)&&E.toolCallId===h.toolCallId),C=h,b=k;k!=null?(k.state=h.state,b.input=C.input,b.output=C.output,b.errorText=C.errorText,b.rawInput=C.rawInput,b.preliminary=C.preliminary,h.title!==void 0&&(b.title=h.title),b.providerExecuted=(S=C.providerExecuted)!=null?S:k.providerExecuted,C.providerMetadata!=null&&(k.callProviderMetadata=C.providerMetadata)):c.message.parts.push({type:`tool-${h.toolName}`,toolCallId:h.toolCallId,state:h.state,title:h.title,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 w(h){var S,k;const C=c.message.parts.find(I=>I.type==="dynamic-tool"&&I.toolCallId===h.toolCallId),b=h,E=C;C!=null?(C.state=h.state,E.toolName=h.toolName,E.input=b.input,E.output=b.output,E.errorText=b.errorText,E.rawInput=(S=b.rawInput)!=null?S:E.rawInput,E.preliminary=b.preliminary,h.title!==void 0&&(E.title=h.title),E.providerExecuted=(k=b.providerExecuted)!=null?k:C.providerExecuted,b.providerMetadata!=null&&(C.callProviderMetadata=b.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:h.toolName,toolCallId:h.toolCallId,state:h.state,input:b.input,output:b.output,errorText:b.errorText,preliminary:b.preliminary,providerExecuted:b.providerExecuted,title:h.title,...b.providerMetadata!=null?{callProviderMetadata:b.providerMetadata}:{}})}async function _(h){if(h!=null){const S=c.message.metadata!=null?Ks(c.message.metadata,h):h;t!=null&&await Tt({value:S,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=S}}switch(i.type){case"text-start":{const h={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=h,c.message.parts.push(h),u();break}case"text-delta":{const h=c.activeTextParts[i.id];if(h==null)throw new Xn({chunkType:"text-delta",chunkId:i.id,message:`Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});h.text+=i.delta,h.providerMetadata=(m=i.providerMetadata)!=null?m:h.providerMetadata,u();break}case"text-end":{const h=c.activeTextParts[i.id];if(h==null)throw new Xn({chunkType:"text-end",chunkId:i.id,message:`Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});h.state="done",h.providerMetadata=(p=i.providerMetadata)!=null?p:h.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const h={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=h,c.message.parts.push(h),u();break}case"reasoning-delta":{const h=c.activeReasoningParts[i.id];if(h==null)throw new Xn({chunkType:"reasoning-delta",chunkId:i.id,message:`Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});h.text+=i.delta,h.providerMetadata=(f=i.providerMetadata)!=null?f:h.providerMetadata,u();break}case"reasoning-end":{const h=c.activeReasoningParts[i.id];if(h==null)throw new Xn({chunkType:"reasoning-end",chunkId:i.id,message:`Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});h.providerMetadata=(g=i.providerMetadata)!=null?g:h.providerMetadata,h.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const h=c.message.parts.filter(Fl);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:h.length,dynamic:i.dynamic,title:i.title},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"tool-input-delta":{const h=c.partialToolCalls[i.toolCallId];if(h==null)throw new Xn({chunkType:"tool-input-delta",chunkId:i.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});h.text+=i.inputTextDelta;const{value:S}=await Vo(h.text);h.dynamic?w({toolCallId:i.toolCallId,toolName:h.toolName,state:"input-streaming",input:S,title:h.title}):y({toolCallId:i.toolCallId,toolName:h.toolName,state:"input-streaming",input:S,title:h.title}),u();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-approval-request":{const h=v(i.toolCallId);h.state="approval-requested",h.approval={id:i.approvalId},u();break}case"tool-output-denied":{const h=v(i.toolCallId);h.state="output-denied",u();break}case"tool-output-available":{const h=v(i.toolCallId);h.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:h.toolName,state:"output-available",input:h.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:h.title}):y({toolCallId:i.toolCallId,toolName:nm(h),state:"output-available",input:h.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,title:h.title}),u();break}case"tool-output-error":{const h=v(i.toolCallId);h.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:h.toolName,state:"output-error",input:h.input,errorText:i.errorText,providerExecuted:i.providerExecuted,title:h.title}):y({toolCallId:i.toolCallId,toolName:nm(h),state:"output-error",input:h.input,rawInput:h.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,title:h.title}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(d5(i)){if(r?.[i.type]!=null){const k=c.message.parts.findIndex(b=>"id"in b&&"data"in b&&b.id===i.id&&b.type===i.type),C=k>=0?k:c.message.parts.length;await Tt({value:i.data,schema:r[i.type],context:{field:`message.parts[${C}].data`,entityName:i.type,entityId:i.id}})}const h=i;if(h.transient){a?.(h);break}const S=h.id!=null?c.message.parts.find(k=>h.type===k.type&&h.id===k.id):void 0;S!=null?S.data=h.data:c.message.parts.push(h),a?.(h),u()}}l.enqueue(i)})}}))}function g5({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let a=t?.[t.length-1];a?.role!=="assistant"?a=void 0:e=a.id;let i=!1;const l=s.pipeThrough(new TransformStream({transform(g,v){if(g.type==="start"){const y=g;y.messageId==null&&e!=null&&(y.messageId=e)}g.type==="abort"&&(i=!0),v.enqueue(g)}}));if(n==null&&r==null)return l;const c=h5({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async g=>{await g({state:c,write:()=>{}})};let m=!1;const p=async()=>{if(m||!n)return;m=!0;const g=c.message.id===a?.id;await n({isAborted:i,isContinuation:g,responseMessage:c.message,messages:[...g?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},f=async()=>{if(!r)return;const g=c.message.id===a?.id;try{await r({isContinuation:g,responseMessage:structuredClone(c.message),messages:[...g?t.slice(0,-1):t,structuredClone(c.message)]})}catch(v){o(v)}};return m5({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(g,v){g.type==="finish-step"&&await f(),v.enqueue(g)},async cancel(){await p()},async flush(){await p()}}))}function y5({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new tm);if(s){const[i,l]=a.tee();a=i,s({stream:l})}em({response:e,status:t,statusText:r,headers:Object.fromEntries(Xs(n,rm).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Zo(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var a;if(!n){n=!0;try{s&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:a}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function _5({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 om(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function v5(){let e=[],t=null,r=!1,n=om();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=om(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length===0&&r?t?.close():await s()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function w5({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l,generateId:c,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f}){let g=null;const v=new ReadableStream({start(b){g=b}}),y=new Set,w=new Map,_=new Map;let h=!1,S;function k(){h&&y.size===0&&(S!=null&&g.enqueue(S),g.close())}const C=new TransformStream({async transform(b,E){const I=b.type;switch(I){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{E.enqueue(b);break}case"file":{E.enqueue({type:"file",file:new Yk({data:b.data,mediaType:b.mediaType})});break}case"finish":{S={type:"finish",finishReason:b.finishReason.unified,rawFinishReason:b.finishReason.raw,usage:q0(b.usage),providerMetadata:b.providerMetadata};break}case"tool-approval-request":{const L=_.get(b.toolCallId);if(L==null){g.enqueue({type:"error",error:new Ml({toolCallId:b.toolCallId,approvalId:b.approvalId})});break}E.enqueue({type:"tool-approval-request",approvalId:b.approvalId,toolCall:L});break}case"tool-call":{try{const L=await B0({toolCall:b,tools:e,repairToolCall:i,system:o,messages:s});if(_.set(L.toolCallId,L),E.enqueue(L),L.invalid){g.enqueue({type:"tool-error",toolCallId:L.toolCallId,toolName:L.toolName,input:L.input,error:cl(L.error),dynamic:!0,title:L.title});break}const M=e?.[L.toolName];if(M==null)break;if(M.onInputAvailable!=null&&await M.onInputAvailable({input:L.input,toolCallId:L.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await Z0({tool:M,toolCall:L,messages:s,experimental_context:l})){g.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:L});break}if(w.set(L.toolCallId,L.input),M.execute!=null&&L.providerExecuted!==!0){const A=c();y.add(A),Dl({toolCall:L,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f,onPreliminaryToolResult:O=>{g.enqueue(O)}}).then(O=>{g.enqueue(O)}).catch(O=>{g.enqueue({type:"error",error:O})}).finally(()=>{y.delete(A),k()})}}catch(L){g.enqueue({type:"error",error:L})}break}case"tool-result":{const L=b.toolName;b.isError?g.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:L,input:w.get(b.toolCallId),providerExecuted:!0,error:b.result,dynamic:b.dynamic}):E.enqueue({type:"tool-result",toolCallId:b.toolCallId,toolName:L,input:w.get(b.toolCallId),output:b.result,providerExecuted:!0,dynamic:b.dynamic});break}default:{const L=I;throw new Error(`Unhandled chunk type: ${L}`)}}},flush(){h=!0,k()}});return new ReadableStream({async start(b){return Promise.all([t.pipeThrough(C).pipeTo(new WritableStream({write(E){b.enqueue(E)},close(){}})),v.pipeTo(new WritableStream({write(E){b.enqueue(E)},close(){b.close()}}))])}})}var b5=Ro({prefix:"aitxt",size:24});function Vl({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Ul(1),experimental_output:m,output:p=m,experimental_telemetry:f,prepareStep:g,providerOptions:v,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:_,experimental_transform:h,experimental_download:S,includeRawChunks:k=!1,onChunk:C,onError:b=({error:Z})=>{console.error(Z)},onFinish:E,onAbort:I,onStepFinish:L,experimental_onStart:M,experimental_onStepStart:A,experimental_onToolCallStart:O,experimental_onToolCallFinish:U,experimental_context:G,experimental_include:H,_internal:{now:le=Ys,generateId:ee=b5}={},...he}){const Z=ql(l),R=v0(l),B=Ck(l),F=R!=null?new AbortController:void 0,x=B!=null?new AbortController:void 0;return new C5({model:Gs(e),telemetry:f,headers:c,settings:he,maxRetries:a,abortSignal:K0(i,Z!=null?AbortSignal.timeout(Z):void 0,F?.signal,x?.signal),stepTimeoutMs:R,stepAbortController:F,chunkTimeoutMs:B,chunkAbortController:x,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:jo(h),activeTools:w,repairToolCall:_,stopConditions:jo(u),output:p,providerOptions:v,prepareStep:g,includeRawChunks:k,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:C,onError:b,onFinish:E,onAbort:I,onStepFinish:L,onStart:M,onStepStart:A,onToolCallStart:O,onToolCallFinish:U,now:le,generateId:ee,experimental_context:G,download:S,include:H})}function k5(e){let t,r="",n="",o,s="";function a({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&a({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&a({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const m=JSON.stringify(u.partial);m!==s&&(a({controller:l,partialOutput:u.partial}),s=m)}}})}var C5=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:a,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:m,messages:p,tools:f,toolChoice:g,transforms:v,activeTools:y,repairToolCall:w,stopConditions:_,output:h,providerOptions:S,prepareStep:k,includeRawChunks:C,now:b,generateId:E,timeout:I,stopWhen:L,originalAbortSignal:M,onChunk:A,onError:O,onFinish:U,onAbort:G,onStepFinish:H,onStart:le,onStepStart:ee,onToolCallStart:he,onToolCallFinish:Z,experimental_context:R,download:B,include:F}){this._totalUsage=new $o,this._finishReason=new $o,this._rawFinishReason=new $o,this._steps=new $o,this.outputSpecification=h,this.includeRawChunks=C,this.tools=f;let x,N=[];const D=[];let W,re,se,Te={},z=[];const V=[],K=new Map;let Q,ie={},ve={};const Qe=new TransformStream({async transform(et,Se){var nt,Ie,Je,gr;Se.enqueue(et);const{part:Y}=et;if((Y.type==="text-delta"||Y.type==="reasoning-delta"||Y.type==="source"||Y.type==="tool-call"||Y.type==="tool-result"||Y.type==="tool-input-start"||Y.type==="tool-input-delta"||Y.type==="raw")&&await A?.({chunk:Y}),Y.type==="error"&&await O({error:P0(Y.error)}),Y.type==="text-start"&&(ie[Y.id]={type:"text",text:"",providerMetadata:Y.providerMetadata},N.push(ie[Y.id])),Y.type==="text-delta"){const Be=ie[Y.id];if(Be==null){Se.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}Be.text+=Y.text,Be.providerMetadata=(nt=Y.providerMetadata)!=null?nt:Be.providerMetadata}if(Y.type==="text-end"){const Be=ie[Y.id];if(Be==null){Se.enqueue({part:{type:"error",error:`text part ${Y.id} not found`},partialOutput:void 0});return}Be.providerMetadata=(Ie=Y.providerMetadata)!=null?Ie:Be.providerMetadata,delete ie[Y.id]}if(Y.type==="reasoning-start"&&(ve[Y.id]={type:"reasoning",text:"",providerMetadata:Y.providerMetadata},N.push(ve[Y.id])),Y.type==="reasoning-delta"){const Be=ve[Y.id];if(Be==null){Se.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}Be.text+=Y.text,Be.providerMetadata=(Je=Y.providerMetadata)!=null?Je:Be.providerMetadata}if(Y.type==="reasoning-end"){const Be=ve[Y.id];if(Be==null){Se.enqueue({part:{type:"error",error:`reasoning part ${Y.id} not found`},partialOutput:void 0});return}Be.providerMetadata=(gr=Y.providerMetadata)!=null?gr:Be.providerMetadata,delete ve[Y.id]}if(Y.type==="file"&&N.push({type:"file",file:Y.file}),Y.type==="source"&&N.push(Y),Y.type==="tool-call"&&N.push(Y),Y.type==="tool-result"&&!Y.preliminary&&N.push(Y),Y.type==="tool-approval-request"&&N.push(Y),Y.type==="tool-error"&&N.push(Y),Y.type==="start-step"&&(N=[],ve={},ie={},Te=Y.request,z=Y.warnings),Y.type==="finish-step"){const Be=await zl({content:N,tools:f}),yr=new G0({stepNumber:V.length,model:Wt,...Fr,experimental_context:R,content:N,finishReason:Y.finishReason,rawFinishReason:Y.rawFinishReason,usage:Y.usage,warnings:z,request:Te,response:{...Y.response,messages:[...D,...Be]},providerMetadata:Y.providerMetadata});await H?.(yr),Al({warnings:z,provider:Wt.provider,model:Wt.modelId}),V.push(yr),D.push(...Be),x.resolve()}Y.type==="finish"&&(se=Y.totalUsage,W=Y.finishReason,re=Y.rawFinishReason)},async flush(et){try{if(V.length===0){const Je=s?.aborted?s.reason:new Xh({message:"No output generated. Check the stream for errors."});Xe._finishReason.reject(Je),Xe._rawFinishReason.reject(Je),Xe._totalUsage.reject(Je),Xe._steps.reject(Je);return}const Se=W??"other",nt=se??jl();Xe._finishReason.resolve(Se),Xe._rawFinishReason.resolve(re),Xe._totalUsage.resolve(nt),Xe._steps.resolve(V);const Ie=V[V.length-1];await U?.({stepNumber:Ie.stepNumber,model:Ie.model,functionId:Ie.functionId,metadata:Ie.metadata,experimental_context:Ie.experimental_context,finishReason:Ie.finishReason,rawFinishReason:Ie.rawFinishReason,totalUsage:nt,usage:Ie.usage,content:Ie.content,text:Ie.text,reasoningText:Ie.reasoningText,reasoning:Ie.reasoning,files:Ie.files,sources:Ie.sources,toolCalls:Ie.toolCalls,staticToolCalls:Ie.staticToolCalls,dynamicToolCalls:Ie.dynamicToolCalls,toolResults:Ie.toolResults,staticToolResults:Ie.staticToolResults,dynamicToolResults:Ie.dynamicToolResults,request:Ie.request,response:Ie.response,warnings:Ie.warnings,providerMetadata:Ie.providerMetadata,steps:V}),Q.setAttributes(await Tr({telemetry:t,attributes:{"ai.response.finishReason":Se,"ai.response.text":{output:()=>Ie.text},"ai.response.reasoning":{output:()=>Ie.reasoningText},"ai.response.toolCalls":{output:()=>{var Je;return(Je=Ie.toolCalls)!=null&&Je.length?JSON.stringify(Ie.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Ie.providerMetadata),"ai.usage.inputTokens":nt.inputTokens,"ai.usage.outputTokens":nt.outputTokens,"ai.usage.totalTokens":nt.totalTokens,"ai.usage.reasoningTokens":nt.reasoningTokens,"ai.usage.cachedInputTokens":nt.cachedInputTokens}}))}catch(Se){et.error(Se)}finally{Q.end()}}}),P=v5();this.addStream=P.addStream,this.closeStream=P.close;const X=P.stream.getReader();let Re=new ReadableStream({async start(et){et.enqueue({type:"start"})},async pull(et){function Se(){G?.({steps:V}),et.enqueue({type:"abort",...s?.reason!==void 0?{reason:hn(s.reason)}:{}}),et.close()}try{const{done:nt,value:Ie}=await X.read();if(nt){et.close();return}if(s?.aborted){Se();return}et.enqueue(Ie)}catch(nt){wn(nt)&&s?.aborted?Se():et.error(nt)}},cancel(et){return P.stream.cancel(et)}});for(const et of v)Re=Re.pipeThrough(et({tools:f,stopStream(){P.terminate()}}));this.baseStream=Re.pipeThrough(k5(h??Qs())).pipeThrough(Qe);const{maxRetries:qe,retry:Vt}=D0({maxRetries:o,abortSignal:s}),ft=M0(t),Ke=Ll(n),zr=N0({model:e,telemetry:t,headers:r,settings:{...Ke,maxRetries:qe}}),Xe=this,Wt={provider:e.provider,modelId:e.modelId},Fr={functionId:t?.functionId,metadata:t?.metadata};Fo({name:"ai.streamText",attributes:Tr({telemetry:t,attributes:{...zo({operationId:"ai.streamText",telemetry:t}),...zr,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:m,messages:p})}}}),tracer:ft,endWhenDone:!1,fn:async et=>{Q=et;const Se=await R0({system:u,prompt:m,messages:p});try{await le?.({model:Wt,system:u,prompt:m,messages:p,tools:f,toolChoice:g,activeTools:y,maxOutputTokens:Ke.maxOutputTokens,temperature:Ke.temperature,topP:Ke.topP,topK:Ke.topK,presencePenalty:Ke.presencePenalty,frequencyPenalty:Ke.frequencyPenalty,stopSequences:Ke.stopSequences,seed:Ke.seed,maxRetries:qe,timeout:I,headers:r,providerOptions:S,stopWhen:L,output:h,abortSignal:M,include:F,...Fr,experimental_context:R})}catch{}const nt=Se.messages,Ie=[],{approvedToolApprovals:Je,deniedToolApprovals:gr}=U0({messages:nt});if(gr.length>0||Je.length>0){const Be=[...Je,...gr].filter(dt=>dt.toolCall.providerExecuted),yr=Je.filter(dt=>!dt.toolCall.providerExecuted),ot=gr.filter(dt=>!dt.toolCall.providerExecuted),kt=gr.filter(dt=>dt.toolCall.providerExecuted);let Ce;const Nt=new ReadableStream({start(dt){Ce=dt}});Xe.addStream(Nt);try{for(const Ct of[...ot,...kt])Ce?.enqueue({type:"tool-output-denied",toolCallId:Ct.toolCall.toolCallId,toolName:Ct.toolCall.toolName});const dt=[];if(await Promise.all(yr.map(async Ct=>{const ct=await Dl({toolCall:Ct.toolCall,tools:f,tracer:ft,telemetry:t,messages:nt,abortSignal:s,experimental_context:R,stepNumber:V.length,model:Wt,onToolCallStart:he,onToolCallFinish:Z,onPreliminaryToolResult:Vr=>{Ce?.enqueue(Vr)}});ct!=null&&(Ce?.enqueue(ct),dt.push(ct))})),Be.length>0&&Ie.push({role:"tool",content:Be.map(Ct=>({type:"tool-approval-response",approvalId:Ct.approvalResponse.approvalId,approved:Ct.approvalResponse.approved,reason:Ct.approvalResponse.reason,providerExecuted:!0}))}),dt.length>0||ot.length>0){const Ct=[];for(const ct of dt)Ct.push({type:"tool-result",toolCallId:ct.toolCallId,toolName:ct.toolName,output:await Do({toolCallId:ct.toolCallId,input:ct.input,tool:f?.[ct.toolName],output:ct.type==="tool-result"?ct.output:ct.error,errorMode:ct.type==="tool-error"?"json":"none"})});for(const ct of ot)Ct.push({type:"tool-result",toolCallId:ct.toolCall.toolCallId,toolName:ct.toolCall.toolName,output:{type:"execution-denied",reason:ct.approvalResponse.reason}});Ie.push({role:"tool",content:Ct})}}finally{Ce?.close()}}D.push(...Ie);async function Y({currentStep:Be,responseMessages:yr,usage:ot}){var kt,Ce,Nt,dt,Ct,ct,Vr,go,Ri;const Pi=Xe.includeRawChunks,ms=a!=null?setTimeout(()=>i.abort(),a):void 0;let nr;function gs(){l!=null&&(nr!=null&&clearTimeout(nr),nr=setTimeout(()=>c.abort(),l))}function Ni(){nr!=null&&(clearTimeout(nr),nr=void 0)}function ys(){ms!=null&&clearTimeout(ms)}try{x=new $o;const pn=[...nt,...yr],gt=await k?.({model:e,steps:V,stepNumber:V.length,messages:pn,experimental_context:R}),Ir=Gs((kt=gt?.model)!=null?kt:e),_s={provider:Ir.provider,modelId:Ir.modelId},Pe=await C0({prompt:{system:(Ce=gt?.system)!=null?Ce:Se.system,messages:(Nt=gt?.messages)!=null?Nt:pn},supportedUrls:await Ir.supportedUrls,download:B}),Mt=(dt=gt?.activeTools)!=null?dt:y,{toolChoice:fn,tools:Zr}=await I0({tools:f,toolChoice:(Ct=gt?.toolChoice)!=null?Ct:g,activeTools:Mt});R=(ct=gt?.experimental_context)!=null?ct:R;const Mi=(Vr=gt?.messages)!=null?Vr:pn,Oi=(go=gt?.system)!=null?go:Se.system,vs=Ks(S,gt?.providerOptions);try{await ee?.({stepNumber:V.length,model:_s,system:Oi,messages:Mi,tools:f,toolChoice:fn,activeTools:Mt,steps:[...V],providerOptions:vs,timeout:I,headers:r,stopWhen:L,output:h,abortSignal:M,include:F,...Fr,experimental_context:R})}catch{}const{result:{stream:Ai,response:ws,request:yo},doStreamSpan:ut,startTimestampMs:Br}=await Vt(()=>Fo({name:"ai.streamText.doStream",attributes:Tr({telemetry:t,attributes:{...zo({operationId:"ai.streamText.doStream",telemetry:t}),...zr,"ai.model.provider":Ir.provider,"ai.model.id":Ir.modelId,"ai.prompt.messages":{input:()=>A0(Pe)},"ai.prompt.tools":{input:()=>Zr?.map(ye=>JSON.stringify(ye))},"ai.prompt.toolChoice":{input:()=>fn!=null?JSON.stringify(fn):void 0},"gen_ai.system":Ir.provider,"gen_ai.request.model":Ir.modelId,"gen_ai.request.frequency_penalty":Ke.frequencyPenalty,"gen_ai.request.max_tokens":Ke.maxOutputTokens,"gen_ai.request.presence_penalty":Ke.presencePenalty,"gen_ai.request.stop_sequences":Ke.stopSequences,"gen_ai.request.temperature":Ke.temperature,"gen_ai.request.top_k":Ke.topK,"gen_ai.request.top_p":Ke.topP}}),tracer:ft,endWhenDone:!1,fn:async ye=>({startTimestampMs:b(),doStreamSpan:ye,result:await Ir.doStream({...Ke,tools:Zr,toolChoice:fn,responseFormat:await h?.responseFormat,prompt:Pe,providerOptions:vs,abortSignal:s,headers:r,includeRawChunks:Pi})})})),qi=w5({tools:f,generatorStream:Ai,tracer:ft,telemetry:t,system:u,messages:pn,repairToolCall:w,abortSignal:s,experimental_context:R,generateId:E,stepNumber:V.length,model:_s,onToolCallStart:he,onToolCallFinish:Z}),IE=(Ri=F?.requestBody)==null||Ri?yo??{}:{...yo,body:void 0},bs=[],ks=[];let Zu;const Bu={};let _o="other",Hu,_r=jl(),Ju,B_=!0,xr={id:E(),timestamp:new Date,modelId:Wt.modelId},H_="";Xe.addStream(qi.pipeThrough(new TransformStream({async transform(ye,Rt){var Cs,Ts,Li,pt,Er;if(gs(),ye.type==="stream-start"){Zu=ye.warnings;return}if(B_){const ht=b()-Br;B_=!1,ut.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":ht}),ut.setAttributes({"ai.response.msToFirstChunk":ht}),Rt.enqueue({type:"start-step",request:IE,warnings:Zu??[]})}const Gu=ye.type;switch(Gu){case"tool-approval-request":case"text-start":case"text-end":{Rt.enqueue(ye);break}case"text-delta":{ye.delta.length>0&&(Rt.enqueue({type:"text-delta",id:ye.id,text:ye.delta,providerMetadata:ye.providerMetadata}),H_+=ye.delta);break}case"reasoning-start":case"reasoning-end":{Rt.enqueue(ye);break}case"reasoning-delta":{Rt.enqueue({type:"reasoning-delta",id:ye.id,text:ye.delta,providerMetadata:ye.providerMetadata});break}case"tool-call":{Rt.enqueue(ye),bs.push(ye);break}case"tool-result":{Rt.enqueue(ye),ye.preliminary||ks.push(ye);break}case"tool-error":{Rt.enqueue(ye),ks.push(ye);break}case"response-metadata":{xr={id:(Cs=ye.id)!=null?Cs:xr.id,timestamp:(Ts=ye.timestamp)!=null?Ts:xr.timestamp,modelId:(Li=ye.modelId)!=null?Li:xr.modelId};break}case"finish":{_r=ye.usage,_o=ye.finishReason,Hu=ye.rawFinishReason,Ju=ye.providerMetadata;const ht=b()-Br;ut.addEvent("ai.stream.finish"),ut.setAttributes({"ai.response.msToFinish":ht,"ai.response.avgOutputTokensPerSecond":1e3*((pt=_r.outputTokens)!=null?pt:0)/ht});break}case"file":{Rt.enqueue(ye);break}case"source":{Rt.enqueue(ye);break}case"tool-input-start":{Bu[ye.id]=ye.toolName;const ht=f?.[ye.toolName];ht?.onInputStart!=null&&await ht.onInputStart({toolCallId:ye.id,messages:pn,abortSignal:s,experimental_context:R}),Rt.enqueue({...ye,dynamic:(Er=ye.dynamic)!=null?Er:ht?.type==="dynamic",title:ht?.title});break}case"tool-input-end":{delete Bu[ye.id],Rt.enqueue(ye);break}case"tool-input-delta":{const ht=Bu[ye.id],Wu=f?.[ht];Wu?.onInputDelta!=null&&await Wu.onInputDelta({inputTextDelta:ye.delta,toolCallId:ye.id,messages:pn,abortSignal:s,experimental_context:R}),Rt.enqueue(ye);break}case"error":{Rt.enqueue(ye),_o="error";break}case"raw":{Pi&&Rt.enqueue(ye);break}default:{const ht=Gu;throw new Error(`Unknown chunk type: ${ht}`)}}},async flush(ye){const Rt=bs.length>0?JSON.stringify(bs):void 0;try{ut.setAttributes(await Tr({telemetry:t,attributes:{"ai.response.finishReason":_o,"ai.response.text":{output:()=>H_},"ai.response.reasoning":{output:()=>{const pt=N.filter(Er=>Er.type==="reasoning");return pt.length>0?pt.map(Er=>Er.text).join(`
69
+ `):void 0}},"ai.response.toolCalls":{output:()=>Rt},"ai.response.id":xr.id,"ai.response.model":xr.modelId,"ai.response.timestamp":xr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ju),"ai.usage.inputTokens":_r.inputTokens,"ai.usage.outputTokens":_r.outputTokens,"ai.usage.totalTokens":_r.totalTokens,"ai.usage.reasoningTokens":_r.reasoningTokens,"ai.usage.cachedInputTokens":_r.cachedInputTokens,"gen_ai.response.finish_reasons":[_o],"gen_ai.response.id":xr.id,"gen_ai.response.model":xr.modelId,"gen_ai.usage.input_tokens":_r.inputTokens,"gen_ai.usage.output_tokens":_r.outputTokens}}))}catch{}finally{ut.end()}ye.enqueue({type:"finish-step",finishReason:_o,rawFinishReason:Hu,usage:_r,providerMetadata:Ju,response:{...xr,headers:ws?.headers}});const Cs=L0(ot,_r);await x.promise;const Ts=bs.filter(pt=>pt.providerExecuted!==!0),Li=ks.filter(pt=>pt.providerExecuted!==!0);for(const pt of bs){if(pt.providerExecuted!==!0)continue;const Er=f?.[pt.toolName];Er?.type==="provider"&&Er.supportsDeferredResults&&(ks.some(ht=>(ht.type==="tool-result"||ht.type==="tool-error")&&ht.toolCallId===pt.toolCallId)||K.set(pt.toolCallId,{toolName:pt.toolName}))}for(const pt of ks)(pt.type==="tool-result"||pt.type==="tool-error")&&K.delete(pt.toolCallId);if(ys(),Ni(),(Ts.length>0&&Li.length===Ts.length||K.size>0)&&!await W0({stopConditions:_,steps:V})){yr.push(...await zl({content:V[V.length-1].content,tools:f}));try{await Y({currentStep:Be+1,responseMessages:yr,usage:Cs})}catch(pt){ye.enqueue({type:"error",error:pt}),Xe.closeStream()}}else ye.enqueue({type:"finish",finishReason:_o,rawFinishReason:Hu,totalUsage:Cs}),Xe.closeStream()}})))}finally{ys(),Ni()}}await Y({currentStep:0,responseMessages:Ie,usage:jl()})}}).catch(et=>{Xe.addStream(new ReadableStream({start(Se){Se.enqueue({type:"error",error:et}),Se.close()}})),Xe.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Zo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Zo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await _5({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Zo(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new vr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Zo(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Qs()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=hn}={}){const c=t!=null?u5({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var f;const g=(f=this.tools)==null?void 0:f[p.toolName];return g==null?p.dynamic:g?.type==="dynamic"?!0:void 0},m=this.fullStream.pipeThrough(new TransformStream({transform:async(p,f)=>{const g=n?.({part:p}),v=p.type;switch(v){case"text-start":{f.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&f.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`});break}case"source":{s&&p.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const y=u(p);f.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const y=u(p);p.invalid?f.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):f.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{f.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const y=u(p);f.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=u(p);f.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-output-denied":{f.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{f.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:p.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{f.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=v;throw new Error(`Unknown chunk type: ${y}`)}}g!=null&&v!=="start"&&v!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:g})}}));return Zo(g5({stream:m,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){y5({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){l5({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 c5({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 i5({textStream:this.textStream,...e})}};Ro({prefix:"aiobj",size:24}),Ro({prefix:"aiobj",size:24});let Zl;Zl=globalThis.crypto;async function T5(e){return(await Zl).getRandomValues(new Uint8Array(e))}async function S5(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await T5(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function I5(e){return await S5(e)}async function x5(e){const t=await(await Zl).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function sm(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await I5(e),r=await x5(t);return{code_verifier:t,code_challenge:r}}var E5="AI_MCPClientError",am=`vercel.ai.error.${E5}`,$5=Symbol.for(am),im,lm,ze=class extends(lm=me,im=$5,lm){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[im]=!0,this.data=n,this.code=o}static isInstance(e){return me.hasMarker(e,am)}},eo="2025-06-18",R5=[eo,"2025-03-26","2024-11-05"],P5=ce(ge(d(),$e())),N5=it({name:d(),version:d()}),ea=it({_meta:ce(T({}).loose())}),Mr=ea,cm=T({method:d(),params:ce(ea)}),um=T({applyDefaults:ce(fe())}).loose(),M5=it({experimental:ce(T({}).loose()),logging:ce(T({}).loose()),prompts:ce(it({listChanged:ce(fe())})),resources:ce(it({subscribe:ce(fe()),listChanged:ce(fe())})),tools:ce(it({listChanged:ce(fe())})),elicitation:ce(um)});T({elicitation:ce(um)}).loose();var O5=Mr.extend({protocolVersion:d(),capabilities:M5,serverInfo:N5,instructions:ce(d())}),Bl=Mr.extend({nextCursor:ce(d())}),A5=T({name:d(),title:ce(d()),description:ce(d()),inputSchema:T({type:$("object"),properties:ce(T({}).loose())}).loose(),outputSchema:ce(T({}).loose()),annotations:ce(T({title:ce(d())}).loose()),_meta:P5}).loose(),q5=Bl.extend({tools:q(A5)}),dm=T({type:$("text"),text:d()}).loose(),pm=T({type:$("image"),data:Np(),mimeType:d()}).loose(),L5=T({uri:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d()),size:ce(j())}).loose(),j5=Bl.extend({resources:q(L5)}),fm=T({uri:d(),name:ce(d()),title:ce(d()),mimeType:ce(d())}).loose(),hm=fm.extend({text:d()}),mm=fm.extend({blob:Np()}),gm=T({type:$("resource"),resource:oe([hm,mm])}).loose(),D5=Mr.extend({content:q(oe([dm,pm,gm])),structuredContent:ce($e()),isError:fe().default(!1).optional()}).or(Mr.extend({toolResult:$e()})),U5=T({uriTemplate:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d())}).loose(),z5=Mr.extend({resourceTemplates:q(U5)}),F5=Mr.extend({contents:q(oe([hm,mm]))}),V5=T({name:d(),description:ce(d()),required:ce(fe())}).loose(),Z5=T({name:d(),title:ce(d()),description:ce(d()),arguments:ce(q(V5))}).loose(),B5=Bl.extend({prompts:q(Z5)}),H5=T({role:oe([$("user"),$("assistant")]),content:oe([dm,pm,gm])}).loose(),J5=Mr.extend({description:ce(d()),messages:q(H5)}),G5=ea.extend({message:d(),requestedSchema:$e()}),ym=cm.extend({method:$("elicitation/create"),params:G5}),W5=Mr.extend({action:oe([$("accept"),$("decline"),$("cancel")]),content:ce(ge(d(),$e()))}),ta="2.0",K5=T({jsonrpc:$(ta),id:oe([d(),j().int()])}).merge(cm).strict(),Y5=T({jsonrpc:$(ta),id:oe([d(),j().int()]),result:Mr}).strict(),Q5=T({jsonrpc:$(ta),id:oe([d(),j().int()]),error:T({code:j().int(),message:d(),data:ce($e())})}).strict(),X5=T({jsonrpc:$(ta)}).merge(T({method:d(),params:ce(ea)})).strict(),Bo=oe([K5,X5,Y5,Q5]),_m=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",vm=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:j().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),zt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Fp.custom,message:"URL must be parseable",fatal:!0}),zd}).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"}),eC=T({resource:d().url(),authorization_servers:q(zt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:fe().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:fe().optional()}).passthrough(),wm=T({issuer:d(),authorization_endpoint:zt,token_endpoint:zt,registration_endpoint:zt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),code_challenge_methods_supported:q(d()),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional()}).passthrough(),tC=T({issuer:d(),authorization_endpoint:zt,token_endpoint:zt,userinfo_endpoint:zt.optional(),jwks_uri:zt,registration_endpoint:zt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),claims_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional()}).passthrough(),rC=tC.merge(wm.pick({code_challenge_methods_supported:!0})),nC=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),oC=T({redirect_uris:q(zt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:zt.optional(),logo_uri:zt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:zt.optional(),policy_uri:d().optional(),jwks_uri:zt.optional(),jwks:vt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),sC=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),aC=oC.merge(nC),iC="AI_MCPClientOAuthError",bm=`vercel.ai.error.${iC}`,lC=Symbol.for(bm),km,Cm,Ho=class extends(Cm=me,km=lC,Cm){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[km]=!0}static isInstance(e){return me.hasMarker(e,bm)}},to=class extends Ho{};to.errorCode="server_error";var ra=class extends Ho{};ra.errorCode="invalid_client";var na=class extends Ho{};na.errorCode="invalid_grant";var oa=class extends Ho{};oa.errorCode="unauthorized_client";var cC={[to.errorCode]:to,[ra.errorCode]:ra,[na.errorCode]:na,[oa.errorCode]:oa};function uC(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function dC({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 sa=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function aa(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 pC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Hl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Hl(e,void 0,r):void 0;throw n}}async function Tm(e,t,r=fetch){return await Hl(e,{"MCP-Protocol-Version":t},r)}function fC(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function hC(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:eo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=pC(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await Tm(l,i,r);if(!n?.metadataUrl&&fC(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await Tm(u,i,r)}return c}async function mC(e,t,r=fetch){const n=await hC(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 eC.parse(await n.json())}function gC(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 yC(e,{fetchFn:t=fetch,protocolVersion:r=eo}={}){var n;const o={"MCP-Protocol-Version":r},s=gC(e);for(const{url:a,type:i}of s){const l=await Hl(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 wm.parse(await l.json());{const c=rC.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 _C(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 sm(),m=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:m}}function Sm(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 Im(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":vC(o,s,r);return;case"client_secret_post":wC(o,s,n);return;case"none":bC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function vC(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 wC(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function bC(e,t){t.set("client_id",e)}async function Jl(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=sC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=cC[o]||to;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new to({message:o})}}async function kC(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",m=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(p,f,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=Sm(r,v);Im(y,r,p,f)}a&&f.set("resource",a.href);const g=await(l??fetch)(m,{method:"POST",headers:p,body:f});if(!g.ok)throw await Jl(g);return vm.parse(await g.json())}async function CC(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),m=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,m,e,t);else{const f=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],g=Sm(r,f);Im(g,r,u,m)}o&&m.set("resource",o.href);const p=await(a??fetch)(c,{method:"POST",headers:u,body:m});if(!p.ok)throw await Jl(p);return vm.parse({refresh_token:n,...await p.json()})}async function TC(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 Jl(s);return aC.parse(await s.json())}async function ia(e,t){var r,n;try{return await Gl(e,t)}catch(o){if(o instanceof ra||o instanceof oa)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Gl(e,t);if(o instanceof na)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Gl(e,t);throw o}}async function SC(e,t,r){const n=uC(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!dC({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 Gl(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await mC(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await SC(t,e,a),c=await yC(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await TC(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),y=await kC(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const m=await e.tokens();if(m?.refresh_token)try{const v=await CC(i,{metadata:c,clientInformation:u,refreshToken:m.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Ho)||v instanceof to))throw v}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await _C(i,{metadata:c,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(g),await e.redirectToAuthorization(f),"REDIRECT"}var IC=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":eo};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return tn(t,`ai-sdk/${_m}`,Po())}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=aa(u);try{if(await ia(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new sa;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(g){return(a=this.onerror)==null||a.call(this,g),t(g)}return r(!0)}if(!u.ok||!u.body){let g=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(g+=". This server does not support SSE transport. Try using `http` transport instead");const v=new ze({message:g});return(i=this.onerror)==null||i.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).getReader(),f=async()=>{var g,v,y;try{for(;;){const{done:w,value:_}=await p.read();if(w){if(this.connected)throw this.connected=!1,new ze({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:h,data:S}=_;if(h==="endpoint"){if(this.endpoint=new URL(S,this.url),this.endpoint.origin!==this.url.origin)throw new ze({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(h==="message")try{const k=Bo.parse(JSON.parse(S));(g=this.onmessage)==null||g.call(this,k)}catch(k){const C=new ze({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(v=this.onerror)==null||v.call(this,C)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(y=this.onerror)==null||y.call(this,w),t(w)}};this.sseConnection={close:()=>p.cancel()},f()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new ze({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},m=await fetch(t,u);if(m.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=aa(m);try{if(await ia(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new sa;(s=this.onerror)==null||s.call(this,f);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!m.ok){const p=await m.text().catch(()=>null),f=new ze({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${p}`});(i=this.onerror)==null||i.call(this,f);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},xC=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":eo};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 tn(t,`ai-sdk/${_m}`,Po())}async start(){if(this.abortController)throw new ze({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,a,i,l,c;try{const m={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},p=await fetch(this.url,m),f=p.headers.get("mcp-session-id");if(f&&(this.sessionId=f),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=aa(p);try{if(await ia(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new sa}catch(w){throw(o=this.onerror)==null||o.call(this,w),w}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const w=await p.text().catch(()=>null);let _=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(_+=". This server does not support HTTP transport. Try using `sse` transport instead");const h=new ze({message:_});throw(s=this.onerror)==null||s.call(this,h),h}if(!("id"in e))return;const v=p.headers.get("content-type")||"";if(v.includes("application/json")){const w=await p.json(),_=Array.isArray(w)?w.map(h=>Bo.parse(h)):[Bo.parse(w)];for(const h of _)(a=this.onmessage)==null||a.call(this,h);return}if(v.includes("text/event-stream")){if(!p.body){const S=new ze({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,S),S}const _=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).getReader();(async()=>{var S,k,C;try{for(;;){const{done:b,value:E}=await _.read();if(b)return;const{event:I,data:L}=E;if(I==="message")try{const M=Bo.parse(JSON.parse(L));(S=this.onmessage)==null||S.call(this,M)}catch(M){const A=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:M});(k=this.onerror)==null||k.call(this,A)}}}catch(b){if(b instanceof Error&&b.name==="AbortError")return;(C=this.onerror)==null||C.call(this,b)}})();return}const y=new ze({message:`MCP HTTP Transport Error: Unexpected content type: ${v}`});throw(l=this.onerror)==null||l.call(this,y),y}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new ze({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await fetch(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=aa(c);try{if(await ia(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new sa;(n=this.onerror)==null||n.call(this,v);return}}catch(g){(o=this.onerror)==null||o.call(this,g);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const g=new ze({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,g);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).getReader(),f=async()=>{var g,v,y,w;try{for(;;){const{done:_,value:h}=await p.read();if(_)return;const{event:S,data:k,id:C}=h;if(C&&(this.lastInboundEventId=C),S==="message")try{const b=Bo.parse(JSON.parse(k));(g=this.onmessage)==null||g.call(this,b)}catch(b){const E=new ze({message:"MCP HTTP Transport Error: Failed to parse message",cause:b});(v=this.onerror)==null||v.call(this,E)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(y=this.onerror)==null||y.call(this,_),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,f()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function EC(e){switch(e.type){case"sse":return new IC(e);case"http":return new xC(e);default:throw new ze({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function $C(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var RC="1.0.0";function xm({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function PC(e){const t=new NC(e);return await t.init(),t}var NC=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=RC,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},$C(e)?this.transport=e:this.transport=EC(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new ze({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:eo,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:O5});if(e===void 0)throw new ze({message:"Server sent invalid initialize result"});if(!R5.includes(e.protocolVersion))throw new ze({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new ze({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new ze({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new ze({message:"Server does not support prompts"});break;default:throw new ze({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new ze({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s?.aborted)return o(new ze({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const m=new ze({message:"Failed to parse server response",cause:u});o(m)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:q5,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:D5,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:j5,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:F5,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:z5,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:B5,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:J5,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:s,title:a,description:i,inputSchema:l,annotations:c,_meta:u}of e.tools){const m=a??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,f=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,g=async(y,w)=>{var _;(_=w?.abortSignal)==null||_.throwIfAborted();const h=await p.callTool({name:s,args:y,options:w});return f!=null?p.extractStructuredContent(h,f,s):h},v=t==="automatic"?Mf({description:i,title:m,inputSchema:Qn({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:xm}):{description:i,title:m,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:g,toModelOutput:xm};o[s]={...v,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await Yt({value:e.structuredContent,schema:kn(t)});if(!n.success)throw new ze({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await Qt({text:n.text,schema:t});if(!o.success)throw new ze({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new ze({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==ym)throw new ze({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=ym.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=W5.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new ze({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new ze({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new ze({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function la(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Em(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...la(t.headers),...la(n.headers)}:t.headers};return e(r,o)}:e}const ca="2025-11-25",MC=[ca,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],xn="io.modelcontextprotocol/related-task",ua="2.0",St=Up(e=>e!==null&&(typeof e=="object"||typeof e=="function")),$m=oe([d(),j().int()]),Rm=d();it({ttl:oe([j(),qs()]).optional(),pollInterval:j().optional()});const OC=T({ttl:j().optional()}),AC=T({taskId:d()}),Wl=it({progressToken:$m.optional(),[xn]:AC.optional()}),Jt=T({_meta:Wl.optional()}),Jo=Jt.extend({task:OC.optional()}),qC=e=>Jo.safeParse(e).success,It=T({method:d(),params:Jt.loose().optional()}),er=T({_meta:Wl.optional()}),tr=T({method:d(),params:er.loose().optional()}),xt=it({_meta:Wl.optional()}),da=oe([d(),j().int()]),Pm=T({jsonrpc:$(ua),id:da,...It.shape}).strict(),Kl=e=>Pm.safeParse(e).success,Nm=T({jsonrpc:$(ua),...tr.shape}).strict(),LC=e=>Nm.safeParse(e).success,Yl=T({jsonrpc:$(ua),id:da,result:xt}).strict(),Go=e=>Yl.safeParse(e).success;var Ee;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ee||(Ee={}));const Ql=T({jsonrpc:$(ua),id:da.optional(),error:T({code:j().int(),message:d(),data:$e().optional()})}).strict(),jC=e=>Ql.safeParse(e).success,En=oe([Pm,Nm,Yl,Ql]);oe([Yl,Ql]);const $n=xt.strict(),DC=er.extend({requestId:da.optional(),reason:d().optional()}),Xl=tr.extend({method:$("notifications/cancelled"),params:DC}),UC=T({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:_e(["light","dark"]).optional()}),Wo=T({icons:q(UC).optional()}),ro=T({name:d(),title:d().optional()}),Mm=ro.extend({...ro.shape,...Wo.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),zC=Gi(T({applyDefaults:fe().optional()}),ge(d(),$e())),FC=zp(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Gi(T({form:zC.optional(),url:St.optional()}),ge(d(),$e()).optional())),VC=it({list:St.optional(),cancel:St.optional(),requests:it({sampling:it({createMessage:St.optional()}).optional(),elicitation:it({create:St.optional()}).optional()}).optional()}),ZC=it({list:St.optional(),cancel:St.optional(),requests:it({tools:it({call:St.optional()}).optional()}).optional()}),BC=T({experimental:ge(d(),St).optional(),sampling:T({context:St.optional(),tools:St.optional()}).optional(),elicitation:FC.optional(),roots:T({listChanged:fe().optional()}).optional(),tasks:VC.optional()}),HC=Jt.extend({protocolVersion:d(),capabilities:BC,clientInfo:Mm}),JC=It.extend({method:$("initialize"),params:HC}),GC=T({experimental:ge(d(),St).optional(),logging:St.optional(),completions:St.optional(),prompts:T({listChanged:fe().optional()}).optional(),resources:T({subscribe:fe().optional(),listChanged:fe().optional()}).optional(),tools:T({listChanged:fe().optional()}).optional(),tasks:ZC.optional()}),Om=xt.extend({protocolVersion:d(),capabilities:GC,serverInfo:Mm,instructions:d().optional()}),Am=tr.extend({method:$("notifications/initialized"),params:er.optional()}),WC=e=>Am.safeParse(e).success,ec=It.extend({method:$("ping"),params:Jt.optional()}),KC=T({progress:j(),total:ce(j()),message:ce(d())}),YC=T({...er.shape,...KC.shape,progressToken:$m}),tc=tr.extend({method:$("notifications/progress"),params:YC}),QC=Jt.extend({cursor:Rm.optional()}),Ko=It.extend({params:QC.optional()}),Yo=xt.extend({nextCursor:Rm.optional()}),XC=_e(["working","input_required","completed","failed","cancelled"]),Qo=T({taskId:d(),status:XC,ttl:oe([j(),qs()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ce(j()),statusMessage:ce(d())}),Xo=xt.extend({task:Qo}),eT=er.merge(Qo),pa=tr.extend({method:$("notifications/tasks/status"),params:eT}),rc=It.extend({method:$("tasks/get"),params:Jt.extend({taskId:d()})}),nc=xt.merge(Qo),oc=It.extend({method:$("tasks/result"),params:Jt.extend({taskId:d()})});xt.loose();const sc=Ko.extend({method:$("tasks/list")}),ac=Yo.extend({tasks:q(Qo)}),ic=It.extend({method:$("tasks/cancel"),params:Jt.extend({taskId:d()})}),tT=xt.merge(Qo),qm=T({uri:d(),mimeType:ce(d()),_meta:ge(d(),$e()).optional()}),Lm=qm.extend({text:d()}),lc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),jm=qm.extend({blob:lc}),es=_e(["user","assistant"]),no=T({audience:q(es).optional(),priority:j().min(0).max(1).optional(),lastModified:Ip({offset:!0}).optional()}),Dm=T({...ro.shape,...Wo.shape,uri:d(),description:ce(d()),mimeType:ce(d()),annotations:no.optional(),_meta:ce(it({}))}),rT=T({...ro.shape,...Wo.shape,uriTemplate:d(),description:ce(d()),mimeType:ce(d()),annotations:no.optional(),_meta:ce(it({}))}),nT=Ko.extend({method:$("resources/list")}),Um=Yo.extend({resources:q(Dm)}),oT=Ko.extend({method:$("resources/templates/list")}),zm=Yo.extend({resourceTemplates:q(rT)}),cc=Jt.extend({uri:d()}),sT=cc,aT=It.extend({method:$("resources/read"),params:sT}),Fm=xt.extend({contents:q(oe([Lm,jm]))}),uc=tr.extend({method:$("notifications/resources/list_changed"),params:er.optional()}),iT=cc,lT=It.extend({method:$("resources/subscribe"),params:iT}),cT=cc,uT=It.extend({method:$("resources/unsubscribe"),params:cT}),dT=er.extend({uri:d()}),Vm=tr.extend({method:$("notifications/resources/updated"),params:dT}),pT=T({name:d(),description:ce(d()),required:ce(fe())}),fT=T({...ro.shape,...Wo.shape,description:ce(d()),arguments:ce(q(pT)),_meta:ce(it({}))}),hT=Ko.extend({method:$("prompts/list")}),Zm=Yo.extend({prompts:q(fT)}),mT=Jt.extend({name:d(),arguments:ge(d(),d()).optional()}),gT=It.extend({method:$("prompts/get"),params:mT}),dc=T({type:$("text"),text:d(),annotations:no.optional(),_meta:ge(d(),$e()).optional()}),pc=T({type:$("image"),data:lc,mimeType:d(),annotations:no.optional(),_meta:ge(d(),$e()).optional()}),fc=T({type:$("audio"),data:lc,mimeType:d(),annotations:no.optional(),_meta:ge(d(),$e()).optional()}),yT=T({type:$("tool_use"),name:d(),id:d(),input:ge(d(),$e()),_meta:ge(d(),$e()).optional()}),_T=T({type:$("resource"),resource:oe([Lm,jm]),annotations:no.optional(),_meta:ge(d(),$e()).optional()}),vT=Dm.extend({type:$("resource_link")}),hc=oe([dc,pc,fc,vT,_T]),wT=T({role:es,content:hc}),Bm=xt.extend({description:d().optional(),messages:q(wT)}),mc=tr.extend({method:$("notifications/prompts/list_changed"),params:er.optional()}),bT=T({title:d().optional(),readOnlyHint:fe().optional(),destructiveHint:fe().optional(),idempotentHint:fe().optional(),openWorldHint:fe().optional()}),kT=T({taskSupport:_e(["required","optional","forbidden"]).optional()}),Hm=T({...ro.shape,...Wo.shape,description:d().optional(),inputSchema:T({type:$("object"),properties:ge(d(),St).optional(),required:q(d()).optional()}).catchall($e()),outputSchema:T({type:$("object"),properties:ge(d(),St).optional(),required:q(d()).optional()}).catchall($e()).optional(),annotations:bT.optional(),execution:kT.optional(),_meta:ge(d(),$e()).optional()}),CT=Ko.extend({method:$("tools/list")}),Jm=Yo.extend({tools:q(Hm)}),ts=xt.extend({content:q(hc).default([]),structuredContent:ge(d(),$e()).optional(),isError:fe().optional()});ts.or(xt.extend({toolResult:$e()}));const TT=Jo.extend({name:d(),arguments:ge(d(),$e()).optional()}),ST=It.extend({method:$("tools/call"),params:TT}),gc=tr.extend({method:$("notifications/tools/list_changed"),params:er.optional()}),IT=T({autoRefresh:fe().default(!0),debounceMs:j().int().nonnegative().default(300)}),Gm=_e(["debug","info","notice","warning","error","critical","alert","emergency"]),xT=Jt.extend({level:Gm}),ET=It.extend({method:$("logging/setLevel"),params:xT}),$T=er.extend({level:Gm,logger:d().optional(),data:$e()}),Wm=tr.extend({method:$("notifications/message"),params:$T}),RT=T({name:d().optional()}),PT=T({hints:q(RT).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),NT=T({mode:_e(["auto","required","none"]).optional()}),MT=T({type:$("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(hc).default([]),structuredContent:T({}).loose().optional(),isError:fe().optional(),_meta:ge(d(),$e()).optional()}),OT=De("type",[dc,pc,fc]),fa=De("type",[dc,pc,fc,yT,MT]),AT=T({role:es,content:oe([fa,q(fa)]),_meta:ge(d(),$e()).optional()}),qT=Jo.extend({messages:q(AT),modelPreferences:PT.optional(),systemPrompt:d().optional(),includeContext:_e(["none","thisServer","allServers"]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:q(d()).optional(),metadata:St.optional(),tools:q(Hm).optional(),toolChoice:NT.optional()}),yc=It.extend({method:$("sampling/createMessage"),params:qT}),_c=xt.extend({model:d(),stopReason:ce(_e(["endTurn","stopSequence","maxTokens"]).or(d())),role:es,content:OT}),Km=xt.extend({model:d(),stopReason:ce(_e(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:es,content:oe([fa,q(fa)])}),LT=T({type:$("boolean"),title:d().optional(),description:d().optional(),default:fe().optional()}),jT=T({type:$("string"),title:d().optional(),description:d().optional(),minLength:j().optional(),maxLength:j().optional(),format:_e(["email","uri","date","date-time"]).optional(),default:d().optional()}),DT=T({type:_e(["number","integer"]),title:d().optional(),description:d().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),UT=T({type:$("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),zT=T({type:$("string"),title:d().optional(),description:d().optional(),oneOf:q(T({const:d(),title:d()})),default:d().optional()}),FT=T({type:$("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),VT=oe([UT,zT]),ZT=T({type:$("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:T({type:$("string"),enum:q(d())}),default:q(d()).optional()}),BT=T({type:$("array"),title:d().optional(),description:d().optional(),minItems:j().optional(),maxItems:j().optional(),items:T({anyOf:q(T({const:d(),title:d()}))}),default:q(d()).optional()}),HT=oe([ZT,BT]),JT=oe([FT,VT,HT]),GT=oe([JT,LT,jT,DT]),WT=Jo.extend({mode:$("form").optional(),message:d(),requestedSchema:T({type:$("object"),properties:ge(d(),GT),required:q(d()).optional()})}),KT=Jo.extend({mode:$("url"),message:d(),elicitationId:d(),url:d().url()}),YT=oe([WT,KT]),vc=It.extend({method:$("elicitation/create"),params:YT}),QT=er.extend({elicitationId:d()}),XT=tr.extend({method:$("notifications/elicitation/complete"),params:QT}),wc=xt.extend({action:_e(["accept","decline","cancel"]),content:zp(e=>e===null?void 0:e,ge(d(),oe([d(),j(),fe(),q(d())])).optional())}),eS=T({type:$("ref/resource"),uri:d()}),tS=T({type:$("ref/prompt"),name:d()}),rS=Jt.extend({ref:oe([tS,eS]),argument:T({name:d(),value:d()}),context:T({arguments:ge(d(),d()).optional()}).optional()}),nS=It.extend({method:$("completion/complete"),params:rS}),Ym=xt.extend({completion:it({values:q(d()).max(100),total:ce(j().int()),hasMore:ce(fe())})}),oS=T({uri:d().startsWith("file://"),name:d().optional(),_meta:ge(d(),$e()).optional()}),Qm=It.extend({method:$("roots/list"),params:Jt.optional()}),Xm=xt.extend({roots:q(oS)}),sS=tr.extend({method:$("notifications/roots/list_changed"),params:er.optional()});oe([ec,JC,nS,ET,gT,hT,nT,oT,aT,lT,uT,ST,CT,rc,oc,sc,ic]),oe([Xl,tc,Am,sS,pa]),oe([$n,_c,Km,wc,Xm,nc,ac,Xo]),oe([ec,yc,vc,Qm,rc,oc,sc,ic]),oe([Xl,tc,Wm,Vm,uc,gc,mc,pa,XT]),oe([$n,Om,Ym,Bm,Zm,Um,zm,Fm,ts,Jm,nc,ac,Xo]);class ke extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===Ee.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new aS(o.elicitations,r)}return new ke(t,r,n)}}class aS extends ke{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(Ee.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const Et=gb().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Fp.custom,message:"URL must be parseable",fatal:!0}),zd}).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"}),iS=it({resource:d().url(),authorization_servers:q(Et).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:fe().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:fe().optional()}),e2=it({issuer:d(),authorization_endpoint:Et,token_endpoint:Et,registration_endpoint:Et.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),service_documentation:Et.optional(),revocation_endpoint:Et.optional(),revocation_endpoint_auth_methods_supported:q(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:q(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(d()).optional(),code_challenge_methods_supported:q(d()).optional(),client_id_metadata_document_supported:fe().optional()}),lS=it({issuer:d(),authorization_endpoint:Et,token_endpoint:Et,userinfo_endpoint:Et.optional(),jwks_uri:Et,registration_endpoint:Et.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),acr_values_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),id_token_encryption_alg_values_supported:q(d()).optional(),id_token_encryption_enc_values_supported:q(d()).optional(),userinfo_signing_alg_values_supported:q(d()).optional(),userinfo_encryption_alg_values_supported:q(d()).optional(),userinfo_encryption_enc_values_supported:q(d()).optional(),request_object_signing_alg_values_supported:q(d()).optional(),request_object_encryption_alg_values_supported:q(d()).optional(),request_object_encryption_enc_values_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),display_values_supported:q(d()).optional(),claim_types_supported:q(d()).optional(),claims_supported:q(d()).optional(),service_documentation:d().optional(),claims_locales_supported:q(d()).optional(),ui_locales_supported:q(d()).optional(),claims_parameter_supported:fe().optional(),request_parameter_supported:fe().optional(),request_uri_parameter_supported:fe().optional(),require_request_uri_registration:fe().optional(),op_policy_uri:Et.optional(),op_tos_uri:Et.optional(),client_id_metadata_document_supported:fe().optional()}),cS=T({...lS.shape,...e2.pick({code_challenge_methods_supported:!0}).shape}),uS=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Vp().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),dS=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),t2=Et.optional().or($("").transform(()=>{})),pS=T({redirect_uris:q(Et),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Et.optional(),logo_uri:t2,scope:d().optional(),contacts:q(d()).optional(),tos_uri:t2,policy_uri:d().optional(),jwks_uri:Et.optional(),jwks:vt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),fS=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:j().optional(),client_secret_expires_at:j().optional()}).strip(),hS=pS.merge(fS);T({error:d(),error_description:d().optional()}).strip(),T({token:d(),token_type_hint:d().optional()}).strip();function mS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function gS({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 wt 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 bc extends wt{}bc.errorCode="invalid_request";class ha extends wt{}ha.errorCode="invalid_client";class ma extends wt{}ma.errorCode="invalid_grant";class ga extends wt{}ga.errorCode="unauthorized_client";class kc extends wt{}kc.errorCode="unsupported_grant_type";class Cc extends wt{}Cc.errorCode="invalid_scope";class Tc extends wt{}Tc.errorCode="access_denied";class oo extends wt{}oo.errorCode="server_error";class Sc extends wt{}Sc.errorCode="temporarily_unavailable";class Ic extends wt{}Ic.errorCode="unsupported_response_type";class xc extends wt{}xc.errorCode="unsupported_token_type";class Ec extends wt{}Ec.errorCode="invalid_token";class $c extends wt{}$c.errorCode="method_not_allowed";class Rc extends wt{}Rc.errorCode="too_many_requests";class ya extends wt{}ya.errorCode="invalid_client_metadata";class Pc extends wt{}Pc.errorCode="insufficient_scope";class Nc extends wt{}Nc.errorCode="invalid_target";const yS={[bc.errorCode]:bc,[ha.errorCode]:ha,[ma.errorCode]:ma,[ga.errorCode]:ga,[kc.errorCode]:kc,[Cc.errorCode]:Cc,[Tc.errorCode]:Tc,[oo.errorCode]:oo,[Sc.errorCode]:Sc,[Ic.errorCode]:Ic,[xc.errorCode]:xc,[Ec.errorCode]:Ec,[$c.errorCode]:$c,[Rc.errorCode]:Rc,[ya.errorCode]:ya,[Pc.errorCode]:Pc,[Nc.errorCode]:Nc};class rr extends Error{constructor(t){super(t??"Unauthorized")}}function _S(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Mc="code",Oc="S256";function vS(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&&_S(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 wS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":bS(o,s,r);return;case"client_secret_post":kS(o,s,n);return;case"none":CS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function bS(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 kS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function CS(e,t){t.set("client_id",e)}async function r2(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=dS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=yS[o]||oo;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new oo(o)}}async function Rn(e,t){try{return await Ac(e,t)}catch(r){if(r instanceof ha||r instanceof ga)return await e.invalidateCredentials?.("all"),await Ac(e,t);if(r instanceof ma)return await e.invalidateCredentials?.("tokens"),await Ac(e,t);throw r}}async function Ac(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await IS(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const l=await SS(t,e,a),c=await PS(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const y=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!TS(w))throw new ya(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(y&&w)u={client_id:w},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const h=await qS(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(h),u=h}}const m=!e.redirectUrl;if(r!==void 0||m){const y=await AS(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const y=await OS(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof wt)||y instanceof oo))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:v}=await NS(i,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(g),"REDIRECT"}function TS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function SS(e,t,r){const n=mS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!gS({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 _a(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=qc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=qc(e,"scope")||void 0,i=qc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function qc(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 IS(e,t,r=fetch){const n=await $S(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 iS.parse(await n.json())}async function Lc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Lc(e,void 0,r):void 0;throw n}}function xS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function n2(e,t,r=fetch){return await Lc(e,{"MCP-Protocol-Version":t},r)}function ES(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function $S(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??ca;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=xS(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await n2(a,s,r);if(!n?.metadataUrl&&ES(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await n2(l,s,r)}return i}function RS(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 PS(e,{fetchFn:t=fetch,protocolVersion:r=ca}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=RS(e);for(const{url:s,type:a}of o){const i=await Lc(s,n,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?e2.parse(await i.json()):cS.parse(await i.json())}}}async function NS(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(Mc))throw new Error(`Incompatible auth server: does not support response type ${Mc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Oc))throw new Error(`Incompatible auth server: does not support code challenge method ${Oc}`)}else i=new URL("/authorize",e);const l=await sm(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Mc),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Oc),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 MS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function o2(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,i,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],m=vS(n,u);wS(m,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await r2(c);return uS.parse(await c.json())}async function OS(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 o2(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function AS(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=MS(o,c,e.redirectUrl)}const l=await e.clientInformation();return o2(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function qS(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 r2(s);return hS.parse(await s.json())}const LS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class so extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class va{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=Em(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??LS}async _authThenStart(){if(!this._authProvider)throw new rr("No auth provider");let t;try{t=await Rn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new rr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=la(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 so(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Hn({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:g}=await u.read();if(g)break;if(f.id&&(a=f.id,i=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const v=En.parse(JSON.parse(f.data));Go(v)&&(l=!0,s!==void 0&&(v.id=s)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new rr("No auth provider");if(await Rn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Kl(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),l=i.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!i.ok){const p=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new so(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:g}=_a(i);if(this._resourceMetadataUrl=f,this._scope=g,await Rn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:g,error:v}=_a(i);if(v==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new so(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await Rn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new rr;return this.send(t)}}throw new so(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),WC(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,m=i.headers.get("content-type");if(u)if(m?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(m?.includes("application/json")){const p=await i.json(),f=Array.isArray(p)?p.map(g=>En.parse(g)):[En.parse(p)];for(const g of f)this.onmessage?.(g)}else throw await i.body?.cancel(),new so(-1,`Unexpected content type: ${m}`);else await i.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new so(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}class wa{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new wa,r=new wa;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}var jc=T({error:T({message:d(),type:d().nullish(),param:vt().nullish(),code:oe([d(),j()]).nullish()})}),cr=rn({errorSchema:jc,errorToMessage:e=>e.error.message});function s2(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function a2(e){var t,r,n,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const i=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:i,noCache:i-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function jS({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map((i,l)=>{var c,u,m;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const p=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${p};base64,${Kn(i.data)}`,detail:(u=(c=i.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new vr({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Kn(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Kn(i.data),format:"mp3"}};default:throw new vr({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new vr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(m=i.filename)!=null?m:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Kn(i.data)}`}}}else throw new vr({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const l=[];for(const c of a)switch(c.type){case"text":{i+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}n.push({role:"assistant",content:i,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const i of a){if(i.type==="tool-approval-response")continue;const l=i.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:i.toolCallId,content:c})}break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:o}}function Dc({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function i2(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var DS=be(()=>we(T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({message:T({role:$("assistant").nullish(),content:d().nullish(),tool_calls:q(T({id:d().nullish(),type:$("function"),function:T({name:d(),arguments:d()})})).nullish(),annotations:q(T({type:$("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}),index:j(),logprobs:T({content:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),US=be(()=>we(oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({delta:T({role:_e(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(T({index:j(),id:d().nullish(),type:$("function").nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(T({type:$("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:j()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),jc]))),zS=be(()=>we(T({logitBias:ge(Vp(),j()).optional(),logprobs:oe([fe(),j()]).optional(),parallelToolCalls:fe().optional(),user:d().optional(),reasoningEffort:_e(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:fe().optional(),metadata:ge(d().max(64),d().max(512)).optional(),prediction:ge(d(),vt()).optional(),serviceTier:_e(["auto","flex","priority","default"]).optional(),strictJsonSchema:fe().optional(),textVerbosity:_e(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:_e(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:_e(["system","developer","remove"]).optional(),forceReasoning:fe().optional()})));function FS({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new vr({functionality:`tool choice type: ${s}`})}}}var VS=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:m,providerOptions:p}){var f,g,v,y,w;const _=[],h=(f=await Pr({provider:"openai",providerOptions:p,schema:zS}))!=null?f:{},S=s2(this.modelId),k=(g=h.forceReasoning)!=null?g:S.isReasoningModel;o!=null&&_.push({type:"unsupported",feature:"topK"});const{messages:C,warnings:b}=jS({prompt:e,systemMessageMode:(v=h.systemMessageMode)!=null?v:k?"developer":S.systemMessageMode});_.push(...b);const E=(y=h.strictJsonSchema)!=null?y:!0,I={model:this.modelId,logit_bias:h.logitBias,logprobs:h.logprobs===!0||typeof h.logprobs=="number"?!0:void 0,top_logprobs:typeof h.logprobs=="number"?h.logprobs:typeof h.logprobs=="boolean"&&h.logprobs?0:void 0,user:h.user,parallel_tool_calls:h.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:E,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:h.textVerbosity,max_completion_tokens:h.maxCompletionTokens,store:h.store,metadata:h.metadata,prediction:h.prediction,reasoning_effort:h.reasoningEffort,service_tier:h.serviceTier,prompt_cache_key:h.promptCacheKey,prompt_cache_retention:h.promptCacheRetention,safety_identifier:h.safetyIdentifier,messages:C};k?((h.reasoningEffort!=="none"||!S.supportsNonReasoningParameters)&&(I.temperature!=null&&(I.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,_.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,_.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,_.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&I.temperature!=null&&(I.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),h.serviceTier==="flex"&&!S.supportsFlexProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),h.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),I.service_tier=void 0);const{tools:L,toolChoice:M,toolWarnings:A}=FS({tools:u,toolChoice:m});return{args:{...I,tools:L,tool_choice:M},warnings:[..._,...A]}}async doGenerate(e){var t,r,n,o,s,a,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:m,rawValue:p}=await Dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Pt(this.config.headers(),e.headers),body:l,failedResponseHandler:cr,successfulResponseHandler:Xt(DS),abortSignal:e.abortSignal,fetch:this.config.fetch}),f=m.choices[0],g=[],v=f.message.content;v!=null&&v.length>0&&g.push({type:"text",text:v});for(const _ of(t=f.message.tool_calls)!=null?t:[])g.push({type:"tool-call",toolCallId:(r=_.id)!=null?r:Ot(),toolName:_.function.name,input:_.function.arguments});for(const _ of(n=f.message.annotations)!=null?n:[])g.push({type:"source",sourceType:"url",id:Ot(),url:_.url_citation.url,title:_.url_citation.title});const y=(o=m.usage)==null?void 0:o.completion_tokens_details;(s=m.usage)==null||s.prompt_tokens_details;const w={openai:{}};return y?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=y?.accepted_prediction_tokens),y?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=y?.rejected_prediction_tokens),((a=f.logprobs)==null?void 0:a.content)!=null&&(w.openai.logprobs=f.logprobs.content),{content:g,finishReason:{unified:i2(f.finish_reason),raw:(i=f.finish_reason)!=null?i:void 0},usage:a2(m.usage),request:{body:l},response:{...Dc(m),headers:u,body:p},warnings:c,providerMetadata:w}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Pt(this.config.headers(),e.headers),body:n,failedResponseHandler:cr,successfulResponseHandler:Zs(US),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const m={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,f){var g,v,y,w,_,h,S,k,C,b,E,I,L,M,A,O,U;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const G=p.value;if("error"in G){i={unified:"error",raw:void 0},f.enqueue({type:"error",error:G.error});return}if(!c){const ee=Dc(G);Object.values(ee).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Dc(G)}))}G.usage!=null&&(l=G.usage,((g=G.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(m.openai.acceptedPredictionTokens=(v=G.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens),((y=G.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(m.openai.rejectedPredictionTokens=(w=G.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const H=G.choices[0];if(H?.finish_reason!=null&&(i={unified:i2(H.finish_reason),raw:H.finish_reason}),((_=H?.logprobs)==null?void 0:_.content)!=null&&(m.openai.logprobs=H.logprobs.content),H?.delta==null)return;const le=H.delta;if(le.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:le.content})),le.tool_calls!=null)for(const ee of le.tool_calls){const he=ee.index;if(a[he]==null){if(ee.type!=="function")throw new ji({data:ee,message:"Expected 'function' type."});if(ee.id==null)throw new ji({data:ee,message:"Expected 'id' to be a string."});if(((h=ee.function)==null?void 0:h.name)==null)throw new ji({data:ee,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:ee.id,toolName:ee.function.name}),a[he]={id:ee.id,type:"function",function:{name:ee.function.name,arguments:(S=ee.function.arguments)!=null?S:""},hasFinished:!1};const R=a[he];((k=R.function)==null?void 0:k.name)!=null&&((C=R.function)==null?void 0:C.arguments)!=null&&(R.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:R.id,delta:R.function.arguments}),$f(R.function.arguments)&&(f.enqueue({type:"tool-input-end",id:R.id}),f.enqueue({type:"tool-call",toolCallId:(b=R.id)!=null?b:Ot(),toolName:R.function.name,input:R.function.arguments}),R.hasFinished=!0));continue}const Z=a[he];Z.hasFinished||(((E=ee.function)==null?void 0:E.arguments)!=null&&(Z.function.arguments+=(L=(I=ee.function)==null?void 0:I.arguments)!=null?L:""),f.enqueue({type:"tool-input-delta",id:Z.id,delta:(M=ee.function.arguments)!=null?M:""}),((A=Z.function)==null?void 0:A.name)!=null&&((O=Z.function)==null?void 0:O.arguments)!=null&&$f(Z.function.arguments)&&(f.enqueue({type:"tool-input-end",id:Z.id}),f.enqueue({type:"tool-call",toolCallId:(U=Z.id)!=null?U:Ot(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}if(le.annotations!=null)for(const ee of le.annotations)f.enqueue({type:"source",sourceType:"url",id:Ot(),url:ee.url_citation.url,title:ee.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:a2(l),...m!=null?{providerMetadata:m}:{}})}})),request:{body:n},response:{headers:o}}}};function l2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}function ZS({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
64
70
 
65
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new _8({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}
71
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new mn({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${t}:
72
+ ${a}
67
73
 
68
- `;break}case"assistant":{const i=s.map(a=>{switch(a.type){case"text":return a.text;case"tool-call":throw new Gt({functionality:"tool-call messages"})}}).join("");n+=`${r}:
69
- ${i}
74
+ `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new vr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
75
+ ${a}
70
76
 
71
- `;break}case"tool":throw new Gt({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return n+=`${r}:
77
+ `;break}case"tool":throw new vr({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
72
78
  `,{prompt:n,stopSequences:[`
73
- ${t}:`]}}function Nh({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 Ah(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 K7=nt(()=>$e($({id:h().nullish(),created:A().nullish(),model:h().nullish(),choices:N($({text:h(),finish_reason:h(),logprobs:$({tokens:N(h()),token_logprobs:N(A()),top_logprobs:N(me(h(),A())).nullish()}).nullish()})),usage:$({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}))),Y7=nt(()=>$e(re([$({id:h().nullish(),created:A().nullish(),model:h().nullish(),choices:N($({text:h(),finish_reason:h().nullish(),index:A(),logprobs:$({tokens:N(h()),token_logprobs:N(A()),top_logprobs:N(me(h(),A())).nullish()}).nullish()})),usage:$({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()}).nullish()}),hl]))),qh=nt(()=>$e($({echo:ce().optional(),logitBias:me(h(),A()).optional(),suffix:h().optional(),user:h().optional(),logprobs:re([ce(),A()]).optional()}))),Q7=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:_,providerOptions:f}){const d=[],p={...await dr({provider:"openai",providerOptions:f,schema:qh}),...await dr({provider:this.providerOptionsName,providerOptions:f,schema:qh})};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:v,stopSequences:m}=W7({prompt:e}),w=[...m??[],...a??[]];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:i,seed:_,prompt:v,stop:w.length>0?w:void 0},warnings:d}}async doGenerate(e){var t,r,n;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:l}=await Wt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Zt(this.config.headers(),e.headers),body:o,failedResponseHandler:Ft,successfulResponseHandler:sn(K7),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:Ah(c.finish_reason),request:{body:o},response:{...Nh(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 Wt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Zt(this.config.headers(),e.headers),body:n,failedResponseHandler:Ft,successfulResponseHandler:ul(Y7),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,_){if(e.includeRawChunks&&_.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){i="error",_.enqueue({type:"error",error:u.error});return}const f=u.value;if("error"in f){i="error",_.enqueue({type:"error",error:f.error});return}c&&(c=!1,_.enqueue({type:"response-metadata",...Nh(f)}),_.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 d=f.choices[0];d?.finish_reason!=null&&(i=Ah(d.finish_reason)),d?.logprobs!=null&&(a.openai.logprobs=d.logprobs),d?.text!=null&&d.text.length>0&&_.enqueue({type:"text-delta",id:"0",delta:d.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}}}},X7=nt(()=>$e($({dimensions:A().optional(),user:h().optional()}))),eS=nt(()=>$e($({data:N($({embedding:N(A())})),usage:$({prompt_tokens:A()}).nullish()}))),tS=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 dr({provider:"openai",providerOptions:n,schema:X7}))!=null?o:{},{responseHeaders:i,value:a,rawValue:l}=await Wt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Zt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Ft,successfulResponseHandler:sn(eS),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}}}},rS=nt(()=>$e($({created:A().nullish(),data:N($({b64_json:h(),revised_prompt:h().nullish()})),background:h().nullish(),output_format:h().nullish(),size:h().nullish(),quality:h().nullish(),usage:$({input_tokens:A().nullish(),output_tokens:A().nullish(),total_tokens:A().nullish(),input_tokens_details:$({image_tokens:A().nullish(),text_tokens:A().nullish()}).nullish()}).nullish()}))),nS={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},oS=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),sS=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=nS[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,_;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 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:v}=await Wt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Zt(this.config.headers(),i),body:{model:this.modelId,prompt:e,n:t,size:r,...(_=s.openai)!=null?_:{},...oS.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Ft,successfulResponseHandler:sn(rS),abortSignal:a,fetch:this.config.fetch});return{images:p.data.map(m=>m.b64_json),warnings:f,response:{timestamp:d,modelId:this.modelId,headers:v},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}:{}}))}}}}},aS=Xe(()=>$e($({code:h().nullish(),containerId:h()}))),iS=Xe(()=>$e($({outputs:N(Ze("type",[$({type:q("logs"),logs:h()}),$({type:q("image"),url:h()})])).nullish()}))),lS=Xe(()=>$e($({container:re([h(),$({fileIds:N(h()).optional()})]).optional()}))),cS=on({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:aS,outputSchema:iS}),uS=(e={})=>cS(e),Lh=$({key:h(),type:be(["eq","ne","gt","gte","lt","lte","in","nin"]),value:re([h(),A(),ce(),N(h())])}),jh=$({type:be(["and","or"]),filters:N(re([Lh,od(()=>jh)]))}),dS=Xe(()=>$e($({vectorStoreIds:N(h()),maxNumResults:A().optional(),ranking:$({ranker:h().optional(),scoreThreshold:A().optional()}).optional(),filters:re([Lh,jh]).optional()}))),pS=Xe(()=>$e($({queries:N(h()),results:N($({attributes:me(h(),ke()),fileId:h(),filename:h(),score:A(),text:h()})).nullable()}))),fS=on({id:"openai.file_search",name:"file_search",inputSchema:$({}),outputSchema:pS}),hS=Xe(()=>$e($({background:be(["auto","opaque","transparent"]).optional(),inputFidelity:be(["low","high"]).optional(),inputImageMask:$({fileId:h().optional(),imageUrl:h().optional()}).optional(),model:h().optional(),moderation:be(["auto"]).optional(),outputCompression:A().int().min(0).max(100).optional(),outputFormat:be(["png","jpeg","webp"]).optional(),partialImages:A().int().min(0).max(3).optional(),quality:be(["auto","low","medium","high"]).optional(),size:be(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),mS=Xe(()=>$e($({}))),gS=Xe(()=>$e($({result:h()}))),_S=on({id:"openai.image_generation",name:"image_generation",inputSchema:mS,outputSchema:gS}),yS=(e={})=>_S(e),Uh=Xe(()=>$e($({action:$({type:q("exec"),command:N(h()),timeoutMs:A().optional(),user:h().optional(),workingDirectory:h().optional(),env:me(h(),h()).optional()})}))),Dh=Xe(()=>$e($({output:h()}))),vS=on({id:"openai.local_shell",name:"local_shell",inputSchema:Uh,outputSchema:Dh}),wS=Xe(()=>$e($({externalWebAccess:ce().optional(),filters:$({allowedDomains:N(h()).optional()}).optional(),searchContextSize:be(["low","medium","high"]).optional(),userLocation:$({type:q("approximate"),country:h().optional(),city:h().optional(),region:h().optional(),timezone:h().optional()}).optional()}))),bS=Xe(()=>$e($({}))),SS=Xe(()=>$e($({action:Ze("type",[$({type:q("search"),query:h().optional()}),$({type:q("openPage"),url:h().nullish()}),$({type:q("findInPage"),url:h().nullish(),pattern:h().nullish()})]),sources:N(Ze("type",[$({type:q("url"),url:h()}),$({type:q("api"),name:h()})])).optional()}))),kS=on({id:"openai.web_search",name:"web_search",inputSchema:bS,outputSchema:SS}),CS=(e={})=>kS(e),$S=Xe(()=>$e($({searchContextSize:be(["low","medium","high"]).optional(),userLocation:$({type:q("approximate"),country:h().optional(),city:h().optional(),region:h().optional(),timezone:h().optional()}).optional()}))),ES=Xe(()=>$e($({}))),TS=Xe(()=>$e($({action:Ze("type",[$({type:q("search"),query:h().optional()}),$({type:q("openPage"),url:h().nullish()}),$({type:q("findInPage"),url:h().nullish(),pattern:h().nullish()})])}))),IS=on({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:ES,outputSchema:TS}),xS={codeInterpreter:uS,fileSearch:fS,imageGeneration:yS,localShell:vS,webSearchPreview:IS,webSearch:CS};function zh(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function RS({prompt:e,systemMessageMode:t,fileIdPrefixes:r,store:n,hasLocalShellTool:o=!1}){var s,i,a,l;const c=[],u=[];for(const{role:_,content:f}of e)switch(_){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 d=t;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{c.push({role:"user",content:f.map((d,p)=>{var v,m,w;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const g=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&zh(d.data,r)?{file_id:d.data}:{image_url:`data:${g};base64,${an(d.data)}`},detail:(m=(v=d.providerOptions)==null?void 0:v.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"&&zh(d.data,r)?{file_id:d.data}:{filename:(w=d.filename)!=null?w:`part-${p}.pdf`,file_data:`data:application/pdf;base64,${an(d.data)}`}};throw new Gt({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},p={};for(const v of f)switch(v.type){case"text":{const m=(i=(s=v.providerOptions)==null?void 0:s.openai)==null?void 0:i.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:m});break}case"tool-call":{if(p[v.toolCallId]=v,v.providerExecuted)break;const m=(l=(a=v.providerOptions)==null?void 0:a.openai)==null?void 0:l.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}if(o&&v.toolName==="local_shell"){const w=await ur({value:v.input,schema:Uh});c.push({type:"local_shell_call",call_id:v.toolCallId,id:m,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:m});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 m=await dr({provider:"openai",providerOptions:v.providerOptions,schema:PS}),w=m?.itemId;if(w!=null){const g=d[w];if(n)g===void 0&&(c.push({type:"item_reference",id:w}),d[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?(d[w]={type:"reasoning",id:w,encrypted_content:m?.reasoningEncryptedContent,summary:y},c.push(d[w])):(g.summary.push(...y),m?.reasoningEncryptedContent!=null&&(g.encrypted_content=m.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 d of f){const p=d.output;if(o&&d.toolName==="local_shell"&&p.type==="json"){const m=await ur({value:p.value,schema:Dh});c.push({type:"local_shell_call_output",call_id:d.toolCallId,output:m.output});break}let v;switch(p.type){case"text":case"error-text":v=p.value;break;case"json":case"error-json":v=JSON.stringify(p.value);break;case"content":v=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:v})}break}default:{const d=_;throw new Error(`Unsupported role: ${d}`)}}return{input:c,warnings:u}}var PS=$({itemId:h().nullish(),reasoningEncryptedContent:h().nullish()});function Zh({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 OS=nt(()=>$e(re([$({type:q("response.output_text.delta"),item_id:h(),delta:h(),logprobs:N($({token:h(),logprob:A(),top_logprobs:N($({token:h(),logprob:A()}))})).nullish()}),$({type:be(["response.completed","response.incomplete"]),response:$({incomplete_details:$({reason:h()}).nullish(),usage:$({input_tokens:A(),input_tokens_details:$({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:$({reasoning_tokens:A().nullish()}).nullish()}),service_tier:h().nullish()})}),$({type:q("response.created"),response:$({id:h(),created_at:A(),model:h(),service_tier:h().nullish()})}),$({type:q("response.output_item.added"),output_index:A(),item:Ze("type",[$({type:q("message"),id:h()}),$({type:q("reasoning"),id:h(),encrypted_content:h().nullish()}),$({type:q("function_call"),id:h(),call_id:h(),name:h(),arguments:h()}),$({type:q("web_search_call"),id:h(),status:h()}),$({type:q("computer_call"),id:h(),status:h()}),$({type:q("file_search_call"),id:h()}),$({type:q("image_generation_call"),id:h()}),$({type:q("code_interpreter_call"),id:h(),container_id:h(),code:h().nullable(),outputs:N(Ze("type",[$({type:q("logs"),logs:h()}),$({type:q("image"),url:h()})])).nullable(),status:h()})])}),$({type:q("response.output_item.done"),output_index:A(),item:Ze("type",[$({type:q("message"),id:h()}),$({type:q("reasoning"),id:h(),encrypted_content:h().nullish()}),$({type:q("function_call"),id:h(),call_id:h(),name:h(),arguments:h(),status:q("completed")}),$({type:q("code_interpreter_call"),id:h(),code:h().nullable(),container_id:h(),outputs:N(Ze("type",[$({type:q("logs"),logs:h()}),$({type:q("image"),url:h()})])).nullable()}),$({type:q("image_generation_call"),id:h(),result:h()}),$({type:q("web_search_call"),id:h(),status:h(),action:Ze("type",[$({type:q("search"),query:h().nullish(),sources:N(Ze("type",[$({type:q("url"),url:h()}),$({type:q("api"),name:h()})])).nullish()}),$({type:q("open_page"),url:h().nullish()}),$({type:q("find_in_page"),url:h().nullish(),pattern:h().nullish()})])}),$({type:q("file_search_call"),id:h(),queries:N(h()),results:N($({attributes:me(h(),ke()),file_id:h(),filename:h(),score:A(),text:h()})).nullish()}),$({type:q("local_shell_call"),id:h(),call_id:h(),action:$({type:q("exec"),command:N(h()),timeout_ms:A().optional(),user:h().optional(),working_directory:h().optional(),env:me(h(),h()).optional()})}),$({type:q("computer_call"),id:h(),status:q("completed")})])}),$({type:q("response.function_call_arguments.delta"),item_id:h(),output_index:A(),delta:h()}),$({type:q("response.image_generation_call.partial_image"),item_id:h(),output_index:A(),partial_image_b64:h()}),$({type:q("response.code_interpreter_call_code.delta"),item_id:h(),output_index:A(),delta:h()}),$({type:q("response.code_interpreter_call_code.done"),item_id:h(),output_index:A(),code:h()}),$({type:q("response.output_text.annotation.added"),annotation:Ze("type",[$({type:q("url_citation"),start_index:A(),end_index:A(),url:h(),title:h()}),$({type:q("file_citation"),file_id:h(),filename:h().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:h().nullish()})])}),$({type:q("response.reasoning_summary_part.added"),item_id:h(),summary_index:A()}),$({type:q("response.reasoning_summary_text.delta"),item_id:h(),summary_index:A(),delta:h()}),$({type:q("response.reasoning_summary_part.done"),item_id:h(),summary_index:A()}),$({type:q("error"),sequence_number:A(),error:$({type:h(),code:h(),message:h(),param:h().nullish()})}),$({type:h()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),MS=nt(()=>$e($({id:h().optional(),created_at:A().optional(),error:$({message:h(),type:h(),param:h().nullish(),code:h()}).nullish(),model:h().optional(),output:N(Ze("type",[$({type:q("message"),role:q("assistant"),id:h(),content:N($({type:q("output_text"),text:h(),logprobs:N($({token:h(),logprob:A(),top_logprobs:N($({token:h(),logprob:A()}))})).nullish(),annotations:N(Ze("type",[$({type:q("url_citation"),start_index:A(),end_index:A(),url:h(),title:h()}),$({type:q("file_citation"),file_id:h(),filename:h().nullish(),index:A().nullish(),start_index:A().nullish(),end_index:A().nullish(),quote:h().nullish()}),$({type:q("container_file_citation"),container_id:h(),file_id:h(),filename:h().nullish(),start_index:A().nullish(),end_index:A().nullish(),index:A().nullish()}),$({type:q("file_path"),file_id:h(),index:A().nullish()})]))}))}),$({type:q("web_search_call"),id:h(),status:h(),action:Ze("type",[$({type:q("search"),query:h().nullish(),sources:N(Ze("type",[$({type:q("url"),url:h()}),$({type:q("api"),name:h()})])).nullish()}),$({type:q("open_page"),url:h().nullish()}),$({type:q("find_in_page"),url:h().nullish(),pattern:h().nullish()})])}),$({type:q("file_search_call"),id:h(),queries:N(h()),results:N($({attributes:me(h(),re([h(),A(),ce()])),file_id:h(),filename:h(),score:A(),text:h()})).nullish()}),$({type:q("code_interpreter_call"),id:h(),code:h().nullable(),container_id:h(),outputs:N(Ze("type",[$({type:q("logs"),logs:h()}),$({type:q("image"),url:h()})])).nullable()}),$({type:q("image_generation_call"),id:h(),result:h()}),$({type:q("local_shell_call"),id:h(),call_id:h(),action:$({type:q("exec"),command:N(h()),timeout_ms:A().optional(),user:h().optional(),working_directory:h().optional(),env:me(h(),h()).optional()})}),$({type:q("function_call"),call_id:h(),name:h(),arguments:h(),id:h()}),$({type:q("computer_call"),id:h(),status:h().optional()}),$({type:q("reasoning"),id:h(),encrypted_content:h().nullish(),summary:N($({type:q("summary_text"),text:h()}))})])).optional(),service_tier:h().nullish(),incomplete_details:$({reason:h()}).nullish(),usage:$({input_tokens:A(),input_tokens_details:$({cached_tokens:A().nullish()}).nullish(),output_tokens:A(),output_tokens_details:$({reasoning_tokens:A().nullish()}).nullish()}).optional()}))),Fh=20,NS=nt(()=>$e($({conversation:h().nullish(),include:N(be(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:h().nullish(),logprobs:re([ce(),A().min(1).max(Fh)]).optional(),maxToolCalls:A().nullish(),metadata:tt().nullish(),parallelToolCalls:ce().nullish(),previousResponseId:h().nullish(),promptCacheKey:h().nullish(),promptCacheRetention:be(["in_memory","24h"]).nullish(),reasoningEffort:h().nullish(),reasoningSummary:h().nullish(),safetyIdentifier:h().nullish(),serviceTier:be(["auto","flex","priority","default"]).nullish(),store:ce().nullish(),strictJsonSchema:ce().nullish(),textVerbosity:be(["low","medium","high"]).nullish(),truncation:be(["auto","disabled"]).nullish(),user:h().nullish()})));async function AS({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 ur({value:i.args,schema:dS});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 ur({value:i.args,schema:$S});o.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await ur({value:i.args,schema:wS});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 ur({value:i.args,schema:lS});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 ur({value:i.args,schema:hS});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 Gt({functionality:`tool choice type: ${i}`})}}}var qS=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:_,responseFormat:f}){var d,p,v,m;const w=[],g=Oh(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 dr({provider:"openai",providerOptions:c,schema:NS});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 RS({prompt:l,systemMessageMode:g.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=y?.store)!=null?d:!0,hasLocalShellTool:R("openai.local_shell")});w.push(...S);const k=(p=y?.strictJsonSchema)!=null?p:!1;let C=y?.include;function I(se){C==null?C=[se]:C.includes(se)||(C=[...C,se])}function R(se){return u?.find(X=>X.type==="provider-defined"&&X.id===se)!=null}const L=typeof y?.logprobs=="number"?y?.logprobs:y?.logprobs===!0?Fh:void 0;L&&I("message.output_text.logprobs");const O=(v=u?.find(se=>se.type==="provider-defined"&&(se.id==="openai.web_search"||se.id==="openai.web_search_preview")))==null?void 0:v.name;O&&I("web_search_call.action.sources"),R("openai.code_interpreter")&&I("code_interpreter_call.outputs");const U=y?.store;U===!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:k,name:(m=f.name)!=null?m:"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:U,user:y?.user,instructions:y?.instructions,service_tier:y?.serviceTier,include:C,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:ee,toolWarnings:ie}=await AS({tools:u,toolChoice:_,strictJsonSchema:k});return{webSearchToolName:O,args:{...D,tools:F,tool_choice:ee},warnings:[...w,...ie],store:U}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,_,f,d,p,v,m,w,g,y,b,S,k,C,I,R,L,O,U;const{args:D,warnings:F,webSearchToolName:ee}=await this.getArgs(e),ie=this.config.url({path:"/responses",modelId:this.modelId}),se=this.config.provider.replace(".responses",""),{responseHeaders:X,value:de,rawValue:V}=await Wt({url:ie,headers:Zt(this.config.headers(),e.headers),body:D,failedResponseHandler:Ft,successfulResponseHandler:sn(MS),abortSignal:e.abortSignal,fetch:this.config.fetch});if(de.error)throw new kt({message:de.error.message,url:ie,requestBodyValues:D,statusCode:400,responseHeaders:X,responseBody:V,isRetryable:!1});const P=[],Z=[];let j=!1;for(const E of de.output)switch(E.type){case"reasoning":{E.summary.length===0&&E.summary.push({type:"summary_text",text:""});for(const B of E.summary)P.push({type:"reasoning",text:B.text,providerMetadata:{[se]:{itemId:E.id,reasoningEncryptedContent:(t=E.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{P.push({type:"tool-call",toolCallId:E.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:E.id,toolName:"image_generation",result:{result:E.result},providerExecuted:!0});break}case"local_shell_call":{P.push({type:"tool-call",toolCallId:E.call_id,toolName:"local_shell",input:JSON.stringify({action:E.action}),providerMetadata:{[se]:{itemId:E.id}}});break}case"message":{for(const B of E.content){(n=(r=e.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&B.logprobs&&Z.push(B.logprobs),P.push({type:"text",text:B.text,providerMetadata:{[se]:{itemId:E.id}}});for(const G of B.annotations)G.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(i=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?i:It(),url:G.url,title:G.title}):G.type==="file_citation"?P.push({type:"source",sourceType:"document",id:(c=(l=(a=this.config).generateId)==null?void 0:l.call(a))!=null?c:It(),mediaType:"text/plain",title:(_=(u=G.quote)!=null?u:G.filename)!=null?_:"Document",filename:(f=G.filename)!=null?f:G.file_id,...G.file_id?{providerMetadata:{[se]:{fileId:G.file_id}}}:{}}):G.type==="container_file_citation"?P.push({type:"source",sourceType:"document",id:(v=(p=(d=this.config).generateId)==null?void 0:p.call(d))!=null?v:It(),mediaType:"text/plain",title:(w=(m=G.filename)!=null?m:G.file_id)!=null?w:"Document",filename:(g=G.filename)!=null?g:G.file_id,providerMetadata:{[se]:{fileId:G.file_id,containerId:G.container_id,...G.index!=null?{index:G.index}:{}}}}):G.type==="file_path"&&P.push({type:"source",sourceType:"document",id:(S=(b=(y=this.config).generateId)==null?void 0:b.call(y))!=null?S: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,P.push({type:"tool-call",toolCallId:E.call_id,toolName:E.name,input:E.arguments,providerMetadata:{[se]:{itemId:E.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:E.id,toolName:ee??"web_search",input:JSON.stringify({}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:E.id,toolName:ee??"web_search",result:Bh(E.action),providerExecuted:!0});break}case"computer_call":{P.push({type:"tool-call",toolCallId:E.id,toolName:"computer_use",input:"",providerExecuted:!0}),P.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":{P.push({type:"tool-call",toolCallId:E.id,toolName:"file_search",input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:E.id,toolName:"file_search",result:{queries:E.queries,results:(C=(k=E.results)==null?void 0:k.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?C:null},providerExecuted:!0});break}case"code_interpreter_call":{P.push({type:"tool-call",toolCallId:E.id,toolName:"code_interpreter",input:JSON.stringify({code:E.code,containerId:E.container_id}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:E.id,toolName:"code_interpreter",result:{outputs:E.outputs},providerExecuted:!0});break}}const T={[se]:{...de.id!=null?{responseId:de.id}:{}}};Z.length>0&&(T[se].logprobs=Z),typeof de.service_tier=="string"&&(T[se].serviceTier=de.service_tier);const x=de.usage;return{content:P,finishReason:Zh({finishReason:(I=de.incomplete_details)==null?void 0:I.reason,hasFunctionCall:j}),usage:{inputTokens:x.input_tokens,outputTokens:x.output_tokens,totalTokens:x.input_tokens+x.output_tokens,reasoningTokens:(L=(R=x.output_tokens_details)==null?void 0:R.reasoning_tokens)!=null?L:void 0,cachedInputTokens:(U=(O=x.input_tokens_details)==null?void 0:O.cached_tokens)!=null?U:void 0},request:{body:D},response:{id:de.id,timestamp:new Date(de.created_at*1e3),modelId:de.model,headers:X,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 Wt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Zt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Ft,successfulResponseHandler:ul(OS),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},_=[];let f=null;const d={},p=[];let v=!1;const m={};let w;return{stream:i.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,y){var b,S,k,C,I,R,L,O,U,D,F,ee,ie,se,X,de,V,P,Z,j,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(Vh(E))E.item.type==="function_call"?(d[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"?(d[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"?(d[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"?(d[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"?(p.splice(0,p.length),y.enqueue({type:"text-start",id:E.item.id,providerMetadata:{[l]:{itemId:E.item.id}}})):Vh(E)&&E.item.type==="reasoning"&&(m[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(jS(E)){if(E.item.type==="message")y.enqueue({type:"text-end",id:E.item.id,providerMetadata:{[l]:{itemId:E.item.id,...p.length>0&&{annotations:p}}}});else if(E.item.type==="function_call")d[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")d[E.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:n??"web_search",result:Bh(E.item.action),providerExecuted:!0});else if(E.item.type==="computer_call")d[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")d[E.output_index]=void 0,y.enqueue({type:"tool-result",toolCallId:E.item.id,toolName:"file_search",result:{queries:E.item.queries,results:(k=(S=E.item.results)==null?void 0:S.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?k:null},providerExecuted:!0});else if(E.item.type==="code_interpreter_call")d[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")d[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 B=m[E.item.id],G=Object.entries(B.summaryParts).filter(([pe,ae])=>ae==="active"||ae==="can-conclude").map(([pe])=>pe);for(const pe of G)y.enqueue({type:"reasoning-end",id:`${E.item.id}:${pe}`,providerMetadata:{[l]:{itemId:E.item.id,reasoningEncryptedContent:(C=E.item.encrypted_content)!=null?C:null}}});delete m[E.item.id]}}else if(zS(E)){const B=d[E.output_index];B!=null&&y.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:E.delta})}else if(ZS(E)){const B=d[E.output_index];B!=null&&y.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:JSON.stringify(E.delta).slice(1,-1)})}else if(FS(E)){const B=d[E.output_index];B!=null&&(y.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}'}),y.enqueue({type:"tool-input-end",id:B.toolCallId}),y.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:E.code,containerId:B.codeInterpreter.containerId}),providerExecuted:!0}))}else if(DS(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(LS(E))y.enqueue({type:"text-delta",id:E.item_id,delta:E.delta}),(R=(I=e.providerOptions)==null?void 0:I.openai)!=null&&R.logprobs&&E.logprobs&&_.push(E.logprobs);else if(E.type==="response.reasoning_summary_part.added"){if(E.summary_index>0){const B=m[E.item_id];B.summaryParts[E.summary_index]="active";for(const G of Object.keys(B.summaryParts))B.summaryParts[G]==="can-conclude"&&(y.enqueue({type:"reasoning-end",id:`${E.item_id}:${G}`,providerMetadata:{[l]:{itemId:E.item_id}}}),B.summaryParts[G]="concluded");y.enqueue({type:"reasoning-start",id:`${E.item_id}:${E.summary_index}`,providerMetadata:{[l]:{itemId:E.item_id,reasoningEncryptedContent:(O=(L=m[E.item_id])==null?void 0:L.encryptedContent)!=null?O: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}}}),m[E.item_id].summaryParts[E.summary_index]="concluded"):m[E.item_id].summaryParts[E.summary_index]="can-conclude":US(E)?(c=Zh({finishReason:(U=E.response.incomplete_details)==null?void 0:U.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=(ie=(ee=E.response.usage.input_tokens_details)==null?void 0:ee.cached_tokens)!=null?ie:void 0,typeof E.response.service_tier=="string"&&(w=E.response.service_tier)):VS(E)?(p.push(E.annotation),E.annotation.type==="url_citation"?y.enqueue({type:"source",sourceType:"url",id:(de=(X=(se=a.config).generateId)==null?void 0:X.call(se))!=null?de:It(),url:E.annotation.url,title:E.annotation.title}):E.annotation.type==="file_citation"&&y.enqueue({type:"source",sourceType:"document",id:(Z=(P=(V=a.config).generateId)==null?void 0:P.call(V))!=null?Z:It(),mediaType:"text/plain",title:(T=(j=E.annotation.quote)!=null?j: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}}}:{}})):BS(E)&&y.enqueue({type:"error",error:E})},flush(g){const y={[l]:{responseId:f}};_.length>0&&(y[l].logprobs=_),w!==void 0&&(y[l].serviceTier=w),g.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:y})}})),request:{body:t},response:{headers:s}}}};function LS(e){return e.type==="response.output_text.delta"}function jS(e){return e.type==="response.output_item.done"}function US(e){return e.type==="response.completed"||e.type==="response.incomplete"}function DS(e){return e.type==="response.created"}function zS(e){return e.type==="response.function_call_arguments.delta"}function ZS(e){return e.type==="response.code_interpreter_call_code.delta"}function FS(e){return e.type==="response.code_interpreter_call_code.done"}function Vh(e){return e.type==="response.output_item.added"}function VS(e){return e.type==="response.output_text.annotation.added"}function BS(e){return e.type==="error"}function Bh(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 HS=nt(()=>$e($({instructions:h().nullish(),speed:A().min(.25).max(4).default(1).nullish()}))),JS=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 dr({provider:"openai",providerOptions:i,schema:HS}),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 _ in u){const f=u[_];f!==void 0&&(c[_]=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 Wt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Zt(this.config.headers(),e.headers),body:s,failedResponseHandler:Ft,successfulResponseHandler:H8(),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}}}},GS=nt(()=>$e($({text:h(),language:h().nullish(),duration:A().nullish(),words:N($({word:h(),start:A(),end:A()})).nullish(),segments:N($({id:A(),seek:A(),start:A(),end:A(),text:h(),tokens:N(A()),temperature:A(),avg_logprob:A(),compression_ratio:A(),no_speech_prob:A()})).nullish()}))),WS=nt(()=>$e($({include:N(h()).optional(),language:h().optional(),prompt:h().optional(),temperature:A().min(0).max(1).default(0).optional(),timestampGranularities:N(be(["word","segment"])).default(["segment"]).optional()}))),Hh={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"},KS=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 dr({provider:"openai",providerOptions:r,schema:WS}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([D7(e)]);s.append("model",this.modelId);const a=M8(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 _ of u)s.append(`${c}[]`,String(_));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:_}=await this.getArgs(e),{value:f,responseHeaders:d,rawValue:p}=await V8({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Zt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Ft,successfulResponseHandler:sn(GS),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=f.language!=null&&f.language in Hh?Hh[f.language]:void 0;return{text:f.text,segments:(a=(i=(o=f.segments)==null?void 0:o.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?i:(s=f.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?a:[],language:v,durationInSeconds:(l=f.duration)!=null?l:void 0,warnings:_,response:{timestamp:c,modelId:this.modelId,headers:d,body:p}}}},YS="2.0.89";function Jh(e={}){var t,r;const n=(t=Z7(O8({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>wh({Authorization:`Bearer ${P8({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${YS}`),i=v=>new G7(v,{provider:`${o}.chat`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),a=v=>new Q7(v,{provider:`${o}.completion`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),l=v=>new tS(v,{provider:`${o}.embedding`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),c=v=>new sS(v,{provider:`${o}.image`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),u=v=>new KS(v,{provider:`${o}.transcription`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch}),_=v=>new JS(v,{provider:`${o}.speech`,url:({path:m})=>`${n}${m}`,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 d(v)},d=v=>new qS(v,{provider:`${o}.responses`,url:({path:m})=>`${n}${m}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(v){return f(v)};return p.languageModel=f,p.chat=i,p.completion=a,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=_,p.speechModel=_,p.tools=xS,p}Jh();function Xn(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function QS(e){const t=[];for(const{role:r,content:n,...o}of e){const s=Xn({...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,...Xn(n[0])});break}t.push({role:"user",content:n.map(i=>{const a=Xn(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,${Jw(i.data)}`},...a}}else throw new ru({functionality:`file part media type ${i.mediaType}`})}}),...s});break}case"assistant":{let i="";const a=[];for(const l of n){const c=Xn(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=Xn(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 Gh({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 Wh(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 gl=$({user:h().optional(),reasoningEffort:h().optional(),textVerbosity:h().optional()}),XS=$({error:$({message:h(),type:h().nullish(),param:tt().nullish(),code:re([h(),A()]).nullish()})}),ek={errorSchema:XS,errorToMessage:e=>e.error.message};function tk({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 ru({functionality:`tool choice type: ${s}`})}}}var rk=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:ek;this.chunkSchema=ok(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:i,providerOptions:a,stopSequences:l,responseFormat:c,seed:u,toolChoice:_,tools:f}){var d,p,v,m;const w=[],g=Object.assign((d=await md({provider:"openai-compatible",providerOptions:a,schema:gl}))!=null?d:{},(p=await md({provider:this.providerOptionsName,providerOptions:a,schema:gl}))!=null?p:{});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}=tk({tools:f,toolChoice:_});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((m=a?.[this.providerOptionsName])!=null?m:{}).filter(([k])=>!Object.keys(gl.shape).includes(k))),reasoning_effort:g.reasoningEffort,verbosity:g.textVerbosity,messages:QS(e),tools:y,tool_choice:b},warnings:[...w,...S]}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,_,f,d,p,v,m,w;const{args:g,warnings:y}=await this.getArgs({...e}),b=JSON.stringify(g),{responseHeaders:S,value:k,rawValue:C}=await Jr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:g,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Gr(nk),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=k.choices[0],R=[],L=I.message.content;L!=null&&L.length>0&&R.push({type:"text",text:L});const O=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(O!=null&&O.length>0&&R.push({type:"reasoning",text:O}),I.message.tool_calls!=null)for(const F of I.message.tool_calls)R.push({type:"tool-call",toolCallId:(r=F.id)!=null?r:xn(),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}))},D=(s=k.usage)==null?void 0:s.completion_tokens_details;return D?.accepted_prediction_tokens!=null&&(U[this.providerOptionsName].acceptedPredictionTokens=D?.accepted_prediction_tokens),D?.rejected_prediction_tokens!=null&&(U[this.providerOptionsName].rejectedPredictionTokens=D?.rejected_prediction_tokens),{content:R,finishReason:Wh(I.finish_reason),usage:{inputTokens:(a=(i=k.usage)==null?void 0:i.prompt_tokens)!=null?a:void 0,outputTokens:(c=(l=k.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(_=(u=k.usage)==null?void 0:u.total_tokens)!=null?_:void 0,reasoningTokens:(p=(d=(f=k.usage)==null?void 0:f.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(w=(m=(v=k.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?w:void 0},providerMetadata:U,request:{body:b},response:{...Gh(k),headers:S,body:C},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 Jr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Br(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:_d(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 _=!0;const f=this.providerOptionsName;let d=!1,p=!1;return{stream:a.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,m){var w,g,y,b,S,k,C,I,R,L,O,U,D;if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",m.enqueue({type:"error",error:v.error});return}const F=v.value;if(s?.processChunk(v.rawValue),"error"in F){c="error",m.enqueue({type:"error",error:F.error.message});return}if(_&&(_=!1,m.enqueue({type:"response-metadata",...Gh(F)})),F.usage!=null){const{prompt_tokens:X,completion_tokens:de,total_tokens:V,prompt_tokens_details:P,completion_tokens_details:Z}=F.usage;u.promptTokens=X??void 0,u.completionTokens=de??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),P?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=P?.cached_tokens)}const ee=F.choices[0];if(ee?.finish_reason!=null&&(c=Wh(ee.finish_reason)),ee?.delta==null)return;const ie=ee.delta,se=(w=ie.reasoning_content)!=null?w: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 X of ie.tool_calls){const de=X.index;if(l[de]==null){if(X.id==null)throw new Uc({data:X,message:"Expected 'id' to be a string."});if(((g=X.function)==null?void 0:g.name)==null)throw new Uc({data:X,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),l[de]={id:X.id,type:"function",function:{name:X.function.name,arguments:(y=X.function.arguments)!=null?y:""},hasFinished:!1};const P=l[de];((b=P.function)==null?void 0:b.name)!=null&&((S=P.function)==null?void 0:S.arguments)!=null&&(P.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),hd(P.function.arguments)&&(m.enqueue({type:"tool-input-end",id:P.id}),m.enqueue({type:"tool-call",toolCallId:(k=P.id)!=null?k:xn(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const V=l[de];V.hasFinished||(((C=X.function)==null?void 0:C.arguments)!=null&&(V.function.arguments+=(R=(I=X.function)==null?void 0:I.arguments)!=null?R:""),m.enqueue({type:"tool-input-delta",id:V.id,delta:(L=X.function.arguments)!=null?L:""}),((O=V.function)==null?void 0:O.name)!=null&&((U=V.function)==null?void 0:U.arguments)!=null&&hd(V.function.arguments)&&(m.enqueue({type:"tool-input-end",id:V.id}),m.enqueue({type:"tool-call",toolCallId:(D=V.id)!=null?D:xn(),toolName:V.function.name,input:V.function.arguments}),V.hasFinished=!0))}},flush(v){var m,w,g,y,b,S;d&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),p&&v.enqueue({type:"text-end",id:"txt-0"});for(const C of l.filter(I=>!I.hasFinished))v.enqueue({type:"tool-input-end",id:C.id}),v.enqueue({type:"tool-call",toolCallId:(m=C.id)!=null?m:xn(),toolName:C.function.name,input:C.function.arguments});const k={[f]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(k[f].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(k[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:k})}})),request:{body:o},response:{headers:i}}}},Kh=$({prompt_tokens:A().nullish(),completion_tokens:A().nullish(),total_tokens:A().nullish(),prompt_tokens_details:$({cached_tokens:A().nullish()}).nullish(),completion_tokens_details:$({reasoning_tokens:A().nullish(),accepted_prediction_tokens:A().nullish(),rejected_prediction_tokens:A().nullish()}).nullish()}).nullish(),nk=$({id:h().nullish(),created:A().nullish(),model:h().nullish(),choices:N($({message:$({role:q("assistant").nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:N($({id:h().nullish(),function:$({name:h(),arguments:h()})})).nullish()}),finish_reason:h().nullish()})),usage:Kh}),ok=e=>re([$({id:h().nullish(),created:A().nullish(),model:h().nullish(),choices:N($({delta:$({role:be(["assistant"]).nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:N($({index:A(),id:h().nullish(),function:$({name:h().nullish(),arguments:h().nullish()})})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:Kh}),e]);$({echo:ce().optional(),logitBias:me(h(),A()).optional(),suffix:h().optional(),user:h().optional()});var sk=$({prompt_tokens:A(),completion_tokens:A(),total_tokens:A()});$({id:h().nullish(),created:A().nullish(),model:h().nullish(),choices:N($({text:h(),finish_reason:h()})),usage:sk.nullish()}),$({dimensions:A().optional(),user:h().optional()}),$({data:N($({embedding:N(A())})),usage:$({prompt_tokens:A()}).nullish(),providerMetadata:me(h(),me(h(),tt())).optional()}),$({data:N($({b64_json:h()}))});var Yh=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}}},ak={extractMetadata:async({parsedBody:e})=>{const t=await $t({value:e,schema:ik});return!t.success||t.value.usage==null?void 0:Yh(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await $t({value:t,schema:lk});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:()=>Yh(e)}}},Qh=$({prompt_cache_hit_tokens:A().nullish(),prompt_cache_miss_tokens:A().nullish()}),ik=$({usage:Qh.nullish()}),lk=$({choices:N($({finish_reason:h().nullish()})).nullish(),usage:Qh.nullish()}),ck="1.0.30";function Xh(e={}){var t;const r=Cd((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>lr({Authorization:`Bearer ${Zv({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${ck}`);class o extends rk{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:ak}),i=a=>s(a);return i.languageModel=s,i.chat=s,i.textEmbeddingModel=a=>{throw new Wc({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new Wc({modelId:a,modelType:"imageModel"})},i}Xh();const uk=(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})},dk=(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 pk{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=dk("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Pr.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];uk("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 ls(e){return!!e._zod}function pr(e,t){return ls(e)?fu(e,t):e.safeParse(t)}function em(e){if(!e)return;let t;if(ls(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function fk(e){if(ls(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 Nr(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function tm(e){const r=em(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=fk(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function rm(e,t){const r=pr(e,t);if(!r.success)throw r.error;return r.data}const hk=6e4;class mk{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(bi,r=>{this._oncancel(r)}),this.setNotificationHandler(ki,r=>{this._onprogress(r)}),this.setRequestHandler(Si,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ci,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ue(_e.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ei,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 _=l,f=new ue(_.error.code,_.error.message,_.error.data);u(f)}else{const _=a.type==="response"?"Response":"Error";this._onerror(new Error(`${_} 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 ue(_e.InvalidParams,`Task not found: ${s}`);if(!Nr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Nr(i.status)){const a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Rr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ti,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 ue(_e.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(xi,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ue(_e.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nr(o.status))throw new ue(_e.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ue(_e.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ue?o:new ue(_e.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),ue.fromError(_e.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Fn(s)||d6(s)?this._onresponse(s):yi(s)?this._onrequest(s,i):u6(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=ue.fromError(_e.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[Rr]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:_e.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(_=>this._onerror(new Error(`Failed to enqueue error response: ${_}`))):o?.send(u).catch(_=>this._onerror(new Error(`Failed to send an error response: ${_}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const a=c6(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 _={relatedRequestId:t.id};s&&(_.relatedTask={taskId:s}),await this.notification(u,_)},sendRequest:async(u,_,f)=>{const d={...f,relatedRequestId:t.id};s&&!d.relatedTask&&(d.relatedTask={taskId:s});const p=d.relatedTask?.taskId??s;return p&&l&&await l.updateTaskStatus(p,"input_required"),await this.request(u,_,d)},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 _={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:_,timestamp:Date.now()},o?.sessionId):await o?.send(_)},async u=>{if(i.signal.aborted)return;const _={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:_e.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:_,timestamp:Date.now()},o?.sessionId):await o?.send(_)}).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),Fn(t))n(t);else{const i=new ue(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(Fn(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),Fn(t))o(t);else{const i=ue.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 ue?i:new ue(_e.InternalError,String(i))}}return}let s;try{const i=await this.request(t,Gn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new ue(_e.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Nr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new ue(_e.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new ue(_e.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 ue?i:new ue(_e.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 _=g=>{u(g)};if(!this._transport){_(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(g){_(g);return}n?.signal?.throwIfAborted();const f=this._requestMessageId++,d={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),d.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(d.params={...d.params,task:a}),l&&(d.params={...d.params,_meta:{...d.params?._meta||{},[Rr]:l}});const p=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 ue?g:new ue(_e.RequestTimeout,String(g));u(y)};this._responseHandlers.set(f,g=>{if(!n?.signal?.aborted){if(g instanceof Error)return u(g);try{const y=pr(r,g.result);y.success?c(y.data):u(y.error)}catch(y){u(y)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});const v=n?.timeout??hk,m=()=>p(ue.fromError(_e.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(f,v,n?.maxTotalTimeout,m,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:d,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(f),u(y)})}else this._transport.send(d,{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},$i,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},Ii,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},I6,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||{},[Rr]: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||{},[Rr]: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||{},[Rr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=tm(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const i=rm(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=tm(t);this._notificationHandlers.set(n,o=>{const s=rm(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"&&yi(o.message)){const s=o.message.id,i=this._requestResolvers.get(s);i?(i(new ue(_e.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new ue(_e.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new ue(_e.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new ue(_e.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=Wo.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Nr(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 ue(_e.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Nr(a.status))throw new ue(_e.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=Wo.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Nr(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function nm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gk(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];nm(i)&&nm(s)?r[o]={...i,...s}:r[o]=s}return r}var cs={exports:{}},_l={},Kt={},Ar={},yl={},vl={},wl={},om;function us(){return om||(om=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=[d(w[0])];let b=0;for(;b<g.length;)y.push(s),a(y,g[b]),y.push(s,d(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(_(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 _(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:d(Array.isArray(w)?w.join(","):w)}function f(w){return new n(d(w))}e.stringify=f;function d(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=d;function p(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=p;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 m(w){return new n(w.toString())}e.regexpCode=m})(wl)),wl}var bl={},sm;function am(){return sm||(sm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=us();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,_;if(!((_=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||_===void 0)&&_.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:_}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${_}]`}}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 _;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const f=this.toName(c),{prefix:d}=f,p=(_=u.key)!==null&&_!==void 0?_:u.ref;let v=this._values[d];if(v){const g=v.get(p);if(g)return g}else v=this._values[d]=new Map;v.set(p,f);const m=this._scope[d]||(this._scope[d]=[]),w=m.length;return m[w]=u.ref,f.setValue(u,{property:d,itemIndex:w}),f}getValue(c,u){const _=this._values[c];if(_)return _.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,_=>{if(_.scopePath===void 0)throw new Error(`CodeGen: name "${_}" has no value`);return(0,t._)`${c}${_.scopePath}`})}scopeCode(c=this._values,u,_){return this._reduceValues(c,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},u,_)}_reduceValues(c,u,_={},f){let d=t.nil;for(const p in c){const v=c[p];if(!v)continue;const m=_[p]=_[p]||new Map;v.forEach(w=>{if(m.has(w))return;m.set(w,n.Started);let g=u(w);if(g){const y=this.opts.es5?e.varKinds.var:e.varKinds.const;d=(0,t._)`${d}${y} ${w} = ${g};${this.opts._n}`}else if(g=f?.(w))d=(0,t._)`${d}${g}${this.opts._n}`;else throw new r(w);m.set(w,n.Completed)})}return d}}e.ValueScope=a})(bl)),bl}var im;function ye(){return im||(im=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=us(),r=am();var n=us();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=am();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,B=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${B};`+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,B){super(T,E,B),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 _ 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 d 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 B=E.length;for(;B--;){const G=E[B];G.optimizeNames(T,x)||(ee(T,G.names),E.splice(B,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((T,x)=>U(T,x.names),{})}}class p extends d{render(T){return"{"+T._n+super.render(T)+"}"+T._n}}class v extends d{}class m extends p{}m.kind="else";class w extends p{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 m(E):E}if(x)return T===!1?x instanceof w?x:x.nodes:this.nodes.length?this:new w(ie(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&&U(T,this.else.names),T}}w.kind="if";class g extends p{}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 U(super.names,this.iteration.names)}}class b extends g{constructor(T,x,E,B){super(),this.varKind=T,this.name=x,this.from=E,this.to=B}render(T){const x=T.es5?r.varKinds.var:this.varKind,{name:E,from:B,to:G}=this;return`for(${x} ${E}=${B}; ${E}<${G}; ${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,B){super(),this.loop=T,this.varKind=x,this.name=E,this.iterable=B}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 U(super.names,this.iterable.names)}}class k extends p{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)}}k.kind="func";class C extends d{render(T){return"return "+super.render(T)}}C.kind="return";class I extends p{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,B;return super.optimizeNames(T,x),(E=this.catch)===null||E===void 0||E.optimizeNames(T,x),(B=this.finally)===null||B===void 0||B.optimizeNames(T,x),this}get names(){const T=super.names;return this.catch&&U(T,this.catch.names),this.finally&&U(T,this.finally.names),T}}class R extends p{constructor(T){super(),this.error=T}render(T){return`catch(${this.error})`+super.render(T)}}R.kind="catch";class L extends p{render(T){return"finally"+super.render(T)}}L.kind="finally";class O{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,B){const G=this._scope.toName(x);return E!==void 0&&B&&(this._constants[G.str]=E),this._leafNode(new i(T,G,E)),G}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,B]of T)x.length>1&&x.push(","),x.push(E),(E!==B||this.opts.es5)&&(x.push(":"),(0,t.addCodeArg)(x,B));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 m)}endIf(){return this._endBlockNode(w,m)}_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,B,G=this.opts.es5?r.varKinds.var:r.varKinds.let){const pe=this._scope.toName(T);return this._for(new b(G,pe,x,E),()=>B(pe))}forOf(T,x,E,B=r.varKinds.const){const G=this._scope.toName(T);if(this.opts.es5){const pe=x instanceof t.Name?x:this.var("_arr",x);return this.forRange("_i",0,(0,t._)`${pe}.length`,ae=>{this.var(G,(0,t._)`${pe}[${ae}]`),E(G)})}return this._for(new S("of",B,G,x),()=>E(G))}forIn(T,x,E,B=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(T,(0,t._)`Object.keys(${x})`,E);const G=this._scope.toName(T);return this._for(new S("in",B,G,x),()=>E(G))}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 C;if(this._blockNode(x),this.code(T),x.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(T,x,E){if(!x&&!E)throw new Error('CodeGen: "try" without "catch" and "finally"');const B=new I;if(this._blockNode(B),this.code(T),x){const G=this.name("e");this._currNode=B.catch=new R(G),x(G)}return E&&(this._currNode=B.finally=new L,this.code(E)),this._endBlockNode(R,L)}throw(T){return this._leafNode(new _(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,B){return this._blockNode(new k(T,x,E)),B&&this.code(B).endFunc(),this}endFunc(){return this._endBlockNode(k)}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=O;function U(j,T){for(const x in T)j[x]=(j[x]||0)+(T[x]||0);return j}function D(j,T){return T instanceof t._CodeOrName?U(j,T.names):j}function F(j,T,x){if(j instanceof t.Name)return E(j);if(!B(j))return j;return new t._Code(j._items.reduce((G,pe)=>(pe instanceof t.Name&&(pe=E(pe)),pe instanceof t._Code?G.push(...pe._items):G.push(pe),G),[]));function E(G){const pe=x[G.str];return pe===void 0||T[G.str]!==1?G:(delete T[G.str],pe)}function B(G){return G instanceof t._Code&&G._items.some(pe=>pe instanceof t.Name&&T[pe.str]===1&&x[pe.str]!==void 0)}}function ee(j,T){for(const x in T)j[x]=(j[x]||0)-(T[x]||0)}function ie(j){return typeof j=="boolean"||typeof j=="number"||j===null?!j:(0,t._)`!${Z(j)}`}e.not=ie;const se=P(e.operators.AND);function X(...j){return j.reduce(se)}e.and=X;const de=P(e.operators.OR);function V(...j){return j.reduce(de)}e.or=V;function P(j){return(T,x)=>T===t.nil?x:x===t.nil?T:(0,t._)`${Z(T)} ${j} ${Z(x)}`}function Z(j){return j instanceof t.Name?j:(0,t._)`(${j})`}})(vl)),vl}var ve={},lm;function Ce(){if(lm)return ve;lm=1,Object.defineProperty(ve,"__esModule",{value:!0}),ve.checkStrictMode=ve.getErrorPath=ve.Type=ve.useFunc=ve.setEvaluated=ve.evaluatedPropsToName=ve.mergeEvaluated=ve.eachItem=ve.unescapeJsonPointer=ve.escapeJsonPointer=ve.escapeFragment=ve.unescapeFragment=ve.schemaRefOrVal=ve.schemaHasRulesButRef=ve.schemaHasRules=ve.checkUnknownRules=ve.alwaysValidSchema=ve.toHash=void 0;const e=ye(),t=us();function r(S){const k={};for(const C of S)k[C]=!0;return k}ve.toHash=r;function n(S,k){return typeof k=="boolean"?k:Object.keys(k).length===0?!0:(o(S,k),!s(k,S.self.RULES.all))}ve.alwaysValidSchema=n;function o(S,k=S.schema){const{opts:C,self:I}=S;if(!C.strictSchema||typeof k=="boolean")return;const R=I.RULES.keywords;for(const L in k)R[L]||b(S,`unknown keyword: "${L}"`)}ve.checkUnknownRules=o;function s(S,k){if(typeof S=="boolean")return!S;for(const C in S)if(k[C])return!0;return!1}ve.schemaHasRules=s;function i(S,k){if(typeof S=="boolean")return!S;for(const C in S)if(C!=="$ref"&&k.all[C])return!0;return!1}ve.schemaHasRulesButRef=i;function a({topSchemaRef:S,schemaPath:k},C,I,R){if(!R){if(typeof C=="number"||typeof C=="boolean")return C;if(typeof C=="string")return(0,e._)`${C}`}return(0,e._)`${S}${k}${(0,e.getProperty)(I)}`}ve.schemaRefOrVal=a;function l(S){return _(decodeURIComponent(S))}ve.unescapeFragment=l;function c(S){return encodeURIComponent(u(S))}ve.escapeFragment=c;function u(S){return typeof S=="number"?`${S}`:S.replace(/~/g,"~0").replace(/\//g,"~1")}ve.escapeJsonPointer=u;function _(S){return S.replace(/~1/g,"/").replace(/~0/g,"~")}ve.unescapeJsonPointer=_;function f(S,k){if(Array.isArray(S))for(const C of S)k(C);else k(S)}ve.eachItem=f;function d({mergeNames:S,mergeToName:k,mergeValues:C,resultToName:I}){return(R,L,O,U)=>{const D=O===void 0?L:O instanceof e.Name?(L instanceof e.Name?S(R,L,O):k(R,L,O),O):L instanceof e.Name?(k(R,O,L),L):C(L,O);return U===e.Name&&!(D instanceof e.Name)?I(R,D):D}}ve.mergeEvaluated={props:d({mergeNames:(S,k,C)=>S.if((0,e._)`${C} !== true && ${k} !== undefined`,()=>{S.if((0,e._)`${k} === true`,()=>S.assign(C,!0),()=>S.assign(C,(0,e._)`${C} || {}`).code((0,e._)`Object.assign(${C}, ${k})`))}),mergeToName:(S,k,C)=>S.if((0,e._)`${C} !== true`,()=>{k===!0?S.assign(C,!0):(S.assign(C,(0,e._)`${C} || {}`),v(S,C,k))}),mergeValues:(S,k)=>S===!0?!0:{...S,...k},resultToName:p}),items:d({mergeNames:(S,k,C)=>S.if((0,e._)`${C} !== true && ${k} !== undefined`,()=>S.assign(C,(0,e._)`${k} === true ? true : ${C} > ${k} ? ${C} : ${k}`)),mergeToName:(S,k,C)=>S.if((0,e._)`${C} !== true`,()=>S.assign(C,k===!0?!0:(0,e._)`${C} > ${k} ? ${C} : ${k}`)),mergeValues:(S,k)=>S===!0?!0:Math.max(S,k),resultToName:(S,k)=>S.var("items",k)})};function p(S,k){if(k===!0)return S.var("props",!0);const C=S.var("props",(0,e._)`{}`);return k!==void 0&&v(S,C,k),C}ve.evaluatedPropsToName=p;function v(S,k,C){Object.keys(C).forEach(I=>S.assign((0,e._)`${k}${(0,e.getProperty)(I)}`,!0))}ve.setEvaluated=v;const m={};function w(S,k){return S.scopeValue("func",{ref:k,code:m[k.code]||(m[k.code]=new t._Code(k.code))})}ve.useFunc=w;var g;(function(S){S[S.Num=0]="Num",S[S.Str=1]="Str"})(g||(ve.Type=g={}));function y(S,k,C){if(S instanceof e.Name){const I=k===g.Num;return C?I?(0,e._)`"[" + ${S} + "]"`:(0,e._)`"['" + ${S} + "']"`:I?(0,e._)`"/" + ${S}`:(0,e._)`"/" + ${S}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return C?(0,e.getProperty)(S).toString():"/"+u(S)}ve.getErrorPath=y;function b(S,k,C=S.opts.strictSchema){if(C){if(k=`strict mode: ${k}`,C===!0)throw new Error(k);S.self.logger.warn(k)}}return ve.checkStrictMode=b,ve}var ds={},cm;function fr(){if(cm)return ds;cm=1,Object.defineProperty(ds,"__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 ds.default=t,ds}var um;function ps(){return um||(um=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=Ce(),n=fr();e.keywordError={message:({keyword:m})=>(0,t.str)`must pass "${m}" keyword validation`},e.keyword$DataError={message:({keyword:m,schemaType:w})=>w?(0,t.str)`"${m}" keyword must be ${w} ($data)`:(0,t.str)`"${m}" keyword is invalid ($data)`};function o(m,w=e.keywordError,g,y){const{it:b}=m,{gen:S,compositeRule:k,allErrors:C}=b,I=_(m,w,g);y??(k||C)?l(S,I):c(b,(0,t._)`[${I}]`)}e.reportError=o;function s(m,w=e.keywordError,g){const{it:y}=m,{gen:b,compositeRule:S,allErrors:k}=y,C=_(m,w,g);l(b,C),S||k||c(y,n.default.vErrors)}e.reportExtraError=s;function i(m,w){m.assign(n.default.errors,w),m.if((0,t._)`${n.default.vErrors} !== null`,()=>m.if(w,()=>m.assign((0,t._)`${n.default.vErrors}.length`,w),()=>m.assign(n.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:m,keyword:w,schemaValue:g,data:y,errsCount:b,it:S}){if(b===void 0)throw new Error("ajv implementation error");const k=m.name("err");m.forRange("i",b,n.default.errors,C=>{m.const(k,(0,t._)`${n.default.vErrors}[${C}]`),m.if((0,t._)`${k}.instancePath === undefined`,()=>m.assign((0,t._)`${k}.instancePath`,(0,t.strConcat)(n.default.instancePath,S.errorPath))),m.assign((0,t._)`${k}.schemaPath`,(0,t.str)`${S.errSchemaPath}/${w}`),S.opts.verbose&&(m.assign((0,t._)`${k}.schema`,g),m.assign((0,t._)`${k}.data`,y))})}e.extendErrors=a;function l(m,w){const g=m.const("err",w);m.if((0,t._)`${n.default.vErrors} === null`,()=>m.assign(n.default.vErrors,(0,t._)`[${g}]`),(0,t._)`${n.default.vErrors}.push(${g})`),m.code((0,t._)`${n.default.errors}++`)}function c(m,w){const{gen:g,validateName:y,schemaEnv:b}=m;b.$async?g.throw((0,t._)`new ${m.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}=m.it;return y===!1?(0,t._)`{}`:f(m,w,g)}function f(m,w,g={}){const{gen:y,it:b}=m,S=[d(b,g),p(m,g)];return v(m,w,S),y.object(...S)}function d({errorPath:m},{instancePath:w}){const g=w?(0,t.str)`${m}${(0,r.getErrorPath)(w,r.Type.Str)}`:m;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,g)]}function p({keyword:m,it:{errSchemaPath:w}},{schemaPath:g,parentSchema:y}){let b=y?w:(0,t.str)`${w}/${m}`;return g&&(b=(0,t.str)`${b}${(0,r.getErrorPath)(g,r.Type.Str)}`),[u.schemaPath,b]}function v(m,{params:w,message:g},y){const{keyword:b,data:S,schemaValue:k,it:C}=m,{opts:I,propertyName:R,topSchemaRef:L,schemaPath:O}=C;y.push([u.keyword,b],[u.params,typeof w=="function"?w(m):w||(0,t._)`{}`]),I.messages&&y.push([u.message,typeof g=="function"?g(m):g]),I.verbose&&y.push([u.schema,k],[u.parentSchema,(0,t._)`${L}${O}`],[n.default.data,S]),R&&y.push([u.propertyName,R])}})(yl)),yl}var dm;function _k(){if(dm)return Ar;dm=1,Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.boolOrEmptySchema=Ar.topBoolOrEmptySchema=void 0;const e=ps(),t=ye(),r=fr(),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))}Ar.topBoolOrEmptySchema=o;function s(a,l){const{gen:c,schema:u}=a;u===!1?(c.var(l,!1),i(a)):c.var(l,!0)}Ar.boolOrEmptySchema=s;function i(a,l){const{gen:c,data:u}=a,_={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(_,n,void 0,l)}return Ar}var Ke={},qr={},pm;function fm(){if(pm)return qr;pm=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.getRules=qr.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)}qr.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 qr.getRules=n,qr}var Yt={},hm;function mm(){if(hm)return Yt;hm=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.shouldUseRule=Yt.shouldUseGroup=Yt.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(n,i)}Yt.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Yt.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 Yt.shouldUseRule=r,Yt}var gm;function fs(){if(gm)return Ke;gm=1,Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.reportTypeError=Ke.checkDataTypes=Ke.checkDataType=Ke.coerceAndCheckDataType=Ke.getJSONTypes=Ke.getSchemaTypes=Ke.DataType=void 0;const e=fm(),t=mm(),r=ps(),n=ye(),o=Ce();var s;(function(g){g[g.Correct=0]="Correct",g[g.Wrong=1]="Wrong"})(s||(Ke.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}Ke.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(","))}Ke.getJSONTypes=a;function l(g,y){const{gen:b,data:S,opts:k}=g,C=u(y,k.coerceTypes),I=y.length>0&&!(C.length===0&&y.length===1&&(0,t.schemaHasRulesForType)(g,y[0]));if(I){const R=p(y,S,k.strictNumbers,s.Wrong);b.if(R,()=>{C.length?_(g,y,C):m(g)})}return I}Ke.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 _(g,y,b){const{gen:S,data:k,opts:C}=g,I=S.let("dataType",(0,n._)`typeof ${k}`),R=S.let("coerced",(0,n._)`undefined`);C.coerceTypes==="array"&&S.if((0,n._)`${I} == 'object' && Array.isArray(${k}) && ${k}.length == 1`,()=>S.assign(k,(0,n._)`${k}[0]`).assign(I,(0,n._)`typeof ${k}`).if(p(y,k,C.strictNumbers),()=>S.assign(R,k))),S.if((0,n._)`${R} !== undefined`);for(const O of b)(c.has(O)||O==="array"&&C.coerceTypes==="array")&&L(O);S.else(),m(g),S.endIf(),S.if((0,n._)`${R} !== undefined`,()=>{S.assign(k,R),f(g,R)});function L(O){switch(O){case"string":S.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(R,(0,n._)`"" + ${k}`).elseIf((0,n._)`${k} === null`).assign(R,(0,n._)`""`);return;case"number":S.elseIf((0,n._)`${I} == "boolean" || ${k} === null
75
- || (${I} == "string" && ${k} && ${k} == +${k})`).assign(R,(0,n._)`+${k}`);return;case"integer":S.elseIf((0,n._)`${I} === "boolean" || ${k} === null
76
- || (${I} === "string" && ${k} && ${k} == +${k} && !(${k} % 1))`).assign(R,(0,n._)`+${k}`);return;case"boolean":S.elseIf((0,n._)`${k} === "false" || ${k} === 0 || ${k} === null`).assign(R,!1).elseIf((0,n._)`${k} === "true" || ${k} === 1`).assign(R,!0);return;case"null":S.elseIf((0,n._)`${k} === "" || ${k} === 0 || ${k} === false`),S.assign(R,null);return;case"array":S.elseIf((0,n._)`${I} === "string" || ${I} === "number"
77
- || ${I} === "boolean" || ${k} === null`).assign(R,(0,n._)`[${k}]`)}}}function f({gen:g,parentData:y,parentDataProperty:b},S){g.if((0,n._)`${y} !== undefined`,()=>g.assign((0,n._)`${y}[${b}]`,S))}function d(g,y,b,S=s.Correct){const k=S===s.Correct?n.operators.EQ:n.operators.NEQ;let C;switch(g){case"null":return(0,n._)`${y} ${k} null`;case"array":C=(0,n._)`Array.isArray(${y})`;break;case"object":C=(0,n._)`${y} && typeof ${y} == "object" && !Array.isArray(${y})`;break;case"integer":C=I((0,n._)`!(${y} % 1) && !isNaN(${y})`);break;case"number":C=I();break;default:return(0,n._)`typeof ${y} ${k} ${g}`}return S===s.Correct?C:(0,n.not)(C);function I(R=n.nil){return(0,n.and)((0,n._)`typeof ${y} == "number"`,R,b?(0,n._)`isFinite(${y})`:n.nil)}}Ke.checkDataType=d;function p(g,y,b,S){if(g.length===1)return d(g[0],y,b,S);let k;const C=(0,o.toHash)(g);if(C.array&&C.object){const I=(0,n._)`typeof ${y} != "object"`;k=C.null?I:(0,n._)`!${y} || ${I}`,delete C.null,delete C.array,delete C.object}else k=n.nil;C.number&&delete C.integer;for(const I in C)k=(0,n.and)(k,d(I,y,b,S));return k}Ke.checkDataTypes=p;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 m(g){const y=w(g);(0,r.reportError)(y,v)}Ke.reportTypeError=m;function w(g){const{gen:y,data:b,schema:S}=g,k=(0,o.schemaRefOrVal)(g,S,"type");return{gen:y,keyword:"type",data:b,schema:S.type,schemaCode:k,schemaValue:k,parentSchema:S,params:{},it:g}}return Ke}var eo={},_m;function yk(){if(_m)return eo;_m=1,Object.defineProperty(eo,"__esModule",{value:!0}),eo.assignDefaults=void 0;const e=ye(),t=Ce();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))}eo.assignDefaults=r;function n(o,s,i){const{gen:a,compositeRule:l,data:c,opts:u}=o;if(i===void 0)return;const _=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${_}`);return}let f=(0,e._)`${_} === undefined`;u.useDefaults==="empty"&&(f=(0,e._)`${f} || ${_} === null || ${_} === ""`),a.if(f,(0,e._)`${_} = ${(0,e.stringify)(i)}`)}return eo}var Pt={},Re={},ym;function Ot(){if(ym)return Re;ym=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=Ce(),r=fr(),n=Ce();function o(g,y){const{gen:b,data:S,it:k}=g;b.if(u(b,S,y,k.opts.ownProperties),()=>{g.setParams({missingProperty:(0,e._)`${y}`},!0),g.error()})}Re.checkReportMissingProp=o;function s({gen:g,data:y,it:{opts:b}},S,k){return(0,e.or)(...S.map(C=>(0,e.and)(u(g,y,C,b.ownProperties),(0,e._)`${k} = ${C}`)))}Re.checkMissingProp=s;function i(g,y){g.setParams({missingProperty:y},!0),g.error()}Re.reportMissingProp=i;function a(g){return g.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Re.hasPropFunc=a;function l(g,y,b){return(0,e._)`${a(g)}.call(${y}, ${b})`}Re.isOwnProperty=l;function c(g,y,b,S){const k=(0,e._)`${y}${(0,e.getProperty)(b)} !== undefined`;return S?(0,e._)`${k} && ${l(g,y,b)}`:k}Re.propertyInData=c;function u(g,y,b,S){const k=(0,e._)`${y}${(0,e.getProperty)(b)} === undefined`;return S?(0,e.or)(k,(0,e.not)(l(g,y,b))):k}Re.noPropertyInData=u;function _(g){return g?Object.keys(g).filter(y=>y!=="__proto__"):[]}Re.allSchemaProperties=_;function f(g,y){return _(y).filter(b=>!(0,t.alwaysValidSchema)(g,y[b]))}Re.schemaProperties=f;function d({schemaCode:g,data:y,it:{gen:b,topSchemaRef:S,schemaPath:k,errorPath:C},it:I},R,L,O){const U=O?(0,e._)`${g}, ${y}, ${S}${k}`:y,D=[[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&&D.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const F=(0,e._)`${U}, ${b.object(...D)}`;return L!==e.nil?(0,e._)`${R}.call(${L}, ${F})`:(0,e._)`${R}(${F})`}Re.callValidateCode=d;const p=(0,e._)`new RegExp`;function v({gen:g,it:{opts:y}},b){const S=y.unicodeRegExp?"u":"",{regExp:k}=y.code,C=k(b,S);return g.scopeValue("pattern",{key:C.toString(),ref:C,code:(0,e._)`${k.code==="new RegExp"?p:(0,n.useFunc)(g,k)}(${b}, ${S})`})}Re.usePattern=v;function m(g){const{gen:y,data:b,keyword:S,it:k}=g,C=y.name("valid");if(k.allErrors){const R=y.let("valid",!0);return I(()=>y.assign(R,!1)),R}return y.var(C,!0),I(()=>y.break()),C;function I(R){const L=y.const("len",(0,e._)`${b}.length`);y.forRange("i",0,L,O=>{g.subschema({keyword:S,dataProp:O,dataPropType:t.Type.Num},C),y.if((0,e.not)(C),R)})}}Re.validateArray=m;function w(g){const{gen:y,schema:b,keyword:S,it:k}=g;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(L=>(0,t.alwaysValidSchema)(k,L))&&!k.opts.unevaluated)return;const I=y.let("valid",!1),R=y.name("_valid");y.block(()=>b.forEach((L,O)=>{const U=g.subschema({keyword:S,schemaProp:O,compositeRule:!0},R);y.assign(I,(0,e._)`${I} || ${R}`),g.mergeValidEvaluated(U,R)||y.if((0,e.not)(I))})),g.result(I,()=>g.reset(),()=>g.error(!0))}return Re.validateUnion=w,Re}var vm;function vk(){if(vm)return Pt;vm=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;const e=ye(),t=fr(),r=Ot(),n=ps();function o(f,d){const{gen:p,keyword:v,schema:m,parentSchema:w,it:g}=f,y=d.macro.call(g.self,m,w,g),b=c(p,v,y);g.opts.validateSchema!==!1&&g.self.validateSchema(y,!0);const S=p.name("valid");f.subschema({schema:y,schemaPath:e.nil,errSchemaPath:`${g.errSchemaPath}/${v}`,topSchemaRef:b,compositeRule:!0},S),f.pass(S,()=>f.error(!0))}Pt.macroKeywordCode=o;function s(f,d){var p;const{gen:v,keyword:m,schema:w,parentSchema:g,$data:y,it:b}=f;l(b,d);const S=!y&&d.compile?d.compile.call(b.self,w,g,b):d.validate,k=c(v,m,S),C=v.let("valid");f.block$data(C,I),f.ok((p=d.valid)!==null&&p!==void 0?p:C);function I(){if(d.errors===!1)O(),d.modifying&&i(f),U(()=>f.error());else{const D=d.async?R():L();d.modifying&&i(f),U(()=>a(f,D))}}function R(){const D=v.let("ruleErrs",null);return v.try(()=>O((0,e._)`await `),F=>v.assign(C,!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._)`${k}.errors`;return v.assign(D,null),O(e.nil),D}function O(D=d.async?(0,e._)`await `:e.nil){const F=b.opts.passContext?t.default.this:t.default.self,ee=!("compile"in d&&!y||d.schema===!1);v.assign(C,(0,e._)`${D}${(0,r.callValidateCode)(f,k,F,ee)}`,d.modifying)}function U(D){var F;v.if((0,e.not)((F=d.valid)!==null&&F!==void 0?F:C),D)}}Pt.funcKeywordCode=s;function i(f){const{gen:d,data:p,it:v}=f;d.if(v.parentData,()=>d.assign(p,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function a(f,d){const{gen:p}=f;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)(f)},()=>f.error())}function l({schemaEnv:f},d){if(d.async&&!f.$async)throw new Error("async keyword in sync schema")}function c(f,d,p){if(p===void 0)throw new Error(`keyword "${d}" failed to compile`);return f.scopeValue("keyword",typeof p=="function"?{ref:p}:{ref:p,code:(0,e.stringify)(p)})}function u(f,d,p=!1){return!d.length||d.some(v=>v==="array"?Array.isArray(f):v==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==v||p&&typeof f>"u")}Pt.validSchemaType=u;function _({schema:f,opts:d,self:p,errSchemaPath:v},m,w){if(Array.isArray(m.keyword)?!m.keyword.includes(w):m.keyword!==w)throw new Error("ajv implementation error");const g=m.dependencies;if(g?.some(y=>!Object.prototype.hasOwnProperty.call(f,y)))throw new Error(`parent schema must have dependencies of ${w}: ${g.join(",")}`);if(m.validateSchema&&!m.validateSchema(f[w])){const b=`keyword "${w}" value is invalid at path "${v}": `+p.errorsText(m.validateSchema.errors);if(d.validateSchema==="log")p.logger.error(b);else throw new Error(b)}}return Pt.validateKeywordUsage=_,Pt}var Qt={},wm;function wk(){if(wm)return Qt;wm=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.extendSubschemaMode=Qt.extendSubschemaData=Qt.getSubschema=void 0;const e=ye(),t=Ce();function r(s,{keyword:i,schemaProp:a,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:_}){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||_===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:_,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Qt.getSubschema=r;function n(s,i,{dataProp:a,dataPropType:l,data:c,dataTypes:u,propertyName:_}){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:p,dataPathArr:v,opts:m}=i,w=f.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);d(w),s.errorPath=(0,e.str)`${p}${(0,t.getErrorPath)(a,l,m.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,s.dataPathArr=[...v,s.parentDataProperty]}if(c!==void 0){const p=c instanceof e.Name?c:f.let("data",c,!0);d(p),_!==void 0&&(s.propertyName=_)}u&&(s.dataTypes=u);function d(p){s.data=p,s.dataLevel=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,p]}}Qt.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 Qt.extendSubschemaMode=o,Qt}var st={},Sl,bm;function Sm(){return bm||(bm=1,Sl=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}),Sl}var kl={exports:{}},km;function bk(){if(km)return kl.exports;km=1;var e=kl.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,_,f){if(i&&typeof i=="object"&&!Array.isArray(i)){o(i,a,l,c,u,_,f);for(var d in i){var p=i[d];if(Array.isArray(p)){if(d in e.arrayKeywords)for(var v=0;v<p.length;v++)t(n,o,s,p[v],a+"/"+d+"/"+v,l,a,d,i,v)}else if(d in e.propsKeywords){if(p&&typeof p=="object")for(var m in p)t(n,o,s,p[m],a+"/"+d+"/"+r(m),l,a,d,i,m)}else(d in e.keywords||n.allKeys&&!(d in e.skipKeywords))&&t(n,o,s,p,a+"/"+d,l,a,d,i)}s(i,a,l,c,u,_,f)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return kl.exports}var Cm;function hs(){if(Cm)return st;Cm=1,Object.defineProperty(st,"__esModule",{value:!0}),st.getSchemaRefs=st.resolveUrl=st.normalizeId=st._getFullPath=st.getFullPath=st.inlineRef=void 0;const e=Ce(),t=Sm(),r=bk(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(v,m=!0){return typeof v=="boolean"?!0:m===!0?!i(v):m?a(v)<=m:!1}st.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(v){for(const m in v){if(s.has(m))return!0;const w=v[m];if(Array.isArray(w)&&w.some(i)||typeof w=="object"&&i(w))return!0}return!1}function a(v){let m=0;for(const w in v){if(w==="$ref")return 1/0;if(m++,!n.has(w)&&(typeof v[w]=="object"&&(0,e.eachItem)(v[w],g=>m+=a(g)),m===1/0))return 1/0}return m}function l(v,m="",w){w!==!1&&(m=_(m));const g=v.parse(m);return c(v,g)}st.getFullPath=l;function c(v,m){return v.serialize(m).split("#")[0]+"#"}st._getFullPath=c;const u=/#\/?$/;function _(v){return v?v.replace(u,""):""}st.normalizeId=_;function f(v,m,w){return w=_(w),v.resolve(m,w)}st.resolveUrl=f;const d=/^[a-z_][-a-z0-9._]*$/i;function p(v,m){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:g}=this.opts,y=_(v[w]||m),b={"":y},S=l(g,y,!1),k={},C=new Set;return r(v,{allKeys:!0},(L,O,U,D)=>{if(D===void 0)return;const F=S+O;let ee=b[D];typeof L[w]=="string"&&(ee=ie.call(this,L[w])),se.call(this,L.$anchor),se.call(this,L.$dynamicAnchor),b[O]=ee;function ie(X){const de=this.opts.uriResolver.resolve;if(X=_(ee?de(ee,X):X),C.has(X))throw R(X);C.add(X);let V=this.refs[X];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?I(L,V.schema,X):X!==_(F)&&(X[0]==="#"?(I(L,k[X],X),k[X]=L):this.refs[X]=F),X}function se(X){if(typeof X=="string"){if(!d.test(X))throw new Error(`invalid anchor "${X}"`);ie.call(this,`#${X}`)}}}),k;function I(L,O,U){if(O!==void 0&&!t(L,O))throw R(U)}function R(L){return new Error(`reference "${L}" resolves to more than one schema`)}}return st.getSchemaRefs=p,st}var $m;function ms(){if($m)return Kt;$m=1,Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.getData=Kt.KeywordCxt=Kt.validateFunctionCode=void 0;const e=_k(),t=fs(),r=mm(),n=fs(),o=yk(),s=vk(),i=wk(),a=ye(),l=fr(),c=hs(),u=Ce(),_=ps();function f(M){if(S(M)&&(C(M),b(M))){m(M);return}d(M,()=>(0,e.topBoolOrEmptySchema)(M))}Kt.validateFunctionCode=f;function d({gen:M,validateName:z,schema:H,schemaEnv:W,opts:K},oe){K.code.es5?M.func(z,(0,a._)`${l.default.data}, ${l.default.valCxt}`,W.$async,()=>{M.code((0,a._)`"use strict"; ${g(H,K)}`),v(M,K),M.code(oe)}):M.func(z,(0,a._)`${l.default.data}, ${p(K)}`,W.$async,()=>M.code(g(H,K)).code(oe))}function p(M){return(0,a._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${M.dynamicRef?(0,a._)`, ${l.default.dynamicAnchors}={}`:a.nil}}={}`}function v(M,z){M.if(l.default.valCxt,()=>{M.var(l.default.instancePath,(0,a._)`${l.default.valCxt}.${l.default.instancePath}`),M.var(l.default.parentData,(0,a._)`${l.default.valCxt}.${l.default.parentData}`),M.var(l.default.parentDataProperty,(0,a._)`${l.default.valCxt}.${l.default.parentDataProperty}`),M.var(l.default.rootData,(0,a._)`${l.default.valCxt}.${l.default.rootData}`),z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,a._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{M.var(l.default.instancePath,(0,a._)`""`),M.var(l.default.parentData,(0,a._)`undefined`),M.var(l.default.parentDataProperty,(0,a._)`undefined`),M.var(l.default.rootData,l.default.data),z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,a._)`{}`)})}function m(M){const{schema:z,opts:H,gen:W}=M;d(M,()=>{H.$comment&&z.$comment&&D(M),L(M),W.let(l.default.vErrors,null),W.let(l.default.errors,0),H.unevaluated&&w(M),I(M),F(M)})}function w(M){const{gen:z,validateName:H}=M;M.evaluated=z.const("evaluated",(0,a._)`${H}.evaluated`),z.if((0,a._)`${M.evaluated}.dynamicProps`,()=>z.assign((0,a._)`${M.evaluated}.props`,(0,a._)`undefined`)),z.if((0,a._)`${M.evaluated}.dynamicItems`,()=>z.assign((0,a._)`${M.evaluated}.items`,(0,a._)`undefined`))}function g(M,z){const H=typeof M=="object"&&M[z.schemaId];return H&&(z.code.source||z.code.process)?(0,a._)`/*# sourceURL=${H} */`:a.nil}function y(M,z){if(S(M)&&(C(M),b(M))){k(M,z);return}(0,e.boolOrEmptySchema)(M,z)}function b({schema:M,self:z}){if(typeof M=="boolean")return!M;for(const H in M)if(z.RULES.all[H])return!0;return!1}function S(M){return typeof M.schema!="boolean"}function k(M,z){const{schema:H,gen:W,opts:K}=M;K.$comment&&H.$comment&&D(M),O(M),U(M);const oe=W.const("_errs",l.default.errors);I(M,oe),W.var(z,(0,a._)`${oe} === ${l.default.errors}`)}function C(M){(0,u.checkUnknownRules)(M),R(M)}function I(M,z){if(M.opts.jtd)return ie(M,[],!1,z);const H=(0,t.getSchemaTypes)(M.schema),W=(0,t.coerceAndCheckDataType)(M,H);ie(M,H,!W,z)}function R(M){const{schema:z,errSchemaPath:H,opts:W,self:K}=M;z.$ref&&W.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(z,K.RULES)&&K.logger.warn(`$ref: keywords ignored in schema at path "${H}"`)}function L(M){const{schema:z,opts:H}=M;z.default!==void 0&&H.useDefaults&&H.strictSchema&&(0,u.checkStrictMode)(M,"default is ignored in the schema root")}function O(M){const z=M.schema[M.opts.schemaId];z&&(M.baseId=(0,c.resolveUrl)(M.opts.uriResolver,M.baseId,z))}function U(M){if(M.schema.$async&&!M.schemaEnv.$async)throw new Error("async schema in sync schema")}function D({gen:M,schemaEnv:z,schema:H,errSchemaPath:W,opts:K}){const oe=H.$comment;if(K.$comment===!0)M.code((0,a._)`${l.default.self}.logger.log(${oe})`);else if(typeof K.$comment=="function"){const le=(0,a.str)`${W}/$comment`,Me=M.scopeValue("root",{ref:z.root});M.code((0,a._)`${l.default.self}.opts.$comment(${oe}, ${le}, ${Me}.schema)`)}}function F(M){const{gen:z,schemaEnv:H,validateName:W,ValidationError:K,opts:oe}=M;H.$async?z.if((0,a._)`${l.default.errors} === 0`,()=>z.return(l.default.data),()=>z.throw((0,a._)`new ${K}(${l.default.vErrors})`)):(z.assign((0,a._)`${W}.errors`,l.default.vErrors),oe.unevaluated&&ee(M),z.return((0,a._)`${l.default.errors} === 0`))}function ee({gen:M,evaluated:z,props:H,items:W}){H instanceof a.Name&&M.assign((0,a._)`${z}.props`,H),W instanceof a.Name&&M.assign((0,a._)`${z}.items`,W)}function ie(M,z,H,W){const{gen:K,schema:oe,data:le,allErrors:Me,opts:Ae,self:Q}=M,{RULES:ge}=Q;if(oe.$ref&&(Ae.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(oe,ge))){K.block(()=>B(M,"$ref",ge.all.$ref.definition));return}Ae.jtd||X(M,z),K.block(()=>{for(const we of ge.rules)at(we);at(ge.post)});function at(we){(0,r.shouldUseGroup)(oe,we)&&(we.type?(K.if((0,n.checkDataType)(we.type,le,Ae.strictNumbers)),se(M,we),z.length===1&&z[0]===we.type&&H&&(K.else(),(0,n.reportTypeError)(M)),K.endIf()):se(M,we),Me||K.if((0,a._)`${l.default.errors} === ${W||0}`))}}function se(M,z){const{gen:H,schema:W,opts:{useDefaults:K}}=M;K&&(0,o.assignDefaults)(M,z.type),H.block(()=>{for(const oe of z.rules)(0,r.shouldUseRule)(W,oe)&&B(M,oe.keyword,oe.definition,z.type)})}function X(M,z){M.schemaEnv.meta||!M.opts.strictTypes||(de(M,z),M.opts.allowUnionTypes||V(M,z),P(M,M.dataTypes))}function de(M,z){if(z.length){if(!M.dataTypes.length){M.dataTypes=z;return}z.forEach(H=>{j(M.dataTypes,H)||x(M,`type "${H}" not allowed by context "${M.dataTypes.join(",")}"`)}),T(M,z)}}function V(M,z){z.length>1&&!(z.length===2&&z.includes("null"))&&x(M,"use allowUnionTypes to allow union type keyword")}function P(M,z){const H=M.self.RULES.all;for(const W in H){const K=H[W];if(typeof K=="object"&&(0,r.shouldUseRule)(M.schema,K)){const{type:oe}=K.definition;oe.length&&!oe.some(le=>Z(z,le))&&x(M,`missing type "${oe.join(",")}" for keyword "${W}"`)}}}function Z(M,z){return M.includes(z)||z==="number"&&M.includes("integer")}function j(M,z){return M.includes(z)||z==="integer"&&M.includes("number")}function T(M,z){const H=[];for(const W of M.dataTypes)j(z,W)?H.push(W):z.includes("integer")&&W==="number"&&H.push("integer");M.dataTypes=H}function x(M,z){const H=M.schemaEnv.baseId+M.errSchemaPath;z+=` at "${H}" (strictTypes)`,(0,u.checkStrictMode)(M,z,M.opts.strictTypes)}class E{constructor(z,H,W){if((0,s.validateKeywordUsage)(z,H,W),this.gen=z.gen,this.allErrors=z.allErrors,this.keyword=W,this.data=z.data,this.schema=z.schema[W],this.$data=H.$data&&z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(z,this.schema,W,this.$data),this.schemaType=H.schemaType,this.parentSchema=z.schema,this.params={},this.it=z,this.def=H,this.$data)this.schemaCode=z.gen.const("vSchema",ae(this.$data,z));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,H.schemaType,H.allowUndefined))throw new Error(`${W} value must be ${JSON.stringify(H.schemaType)}`);("code"in H?H.trackErrors:H.errors!==!1)&&(this.errsCount=z.gen.const("_errs",l.default.errors))}result(z,H,W){this.failResult((0,a.not)(z),H,W)}failResult(z,H,W){this.gen.if(z),W?W():this.error(),H?(this.gen.else(),H(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(z,H){this.failResult((0,a.not)(z),void 0,H)}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:H}=this;this.fail((0,a._)`${H} !== undefined && (${(0,a.or)(this.invalid$data(),z)})`)}error(z,H,W){if(H){this.setParams(H),this._error(z,W),this.setParams({});return}this._error(z,W)}_error(z,H){(z?_.reportExtraError:_.reportError)(this,this.def.error,H)}$dataError(){(0,_.reportError)(this,this.def.$dataError||_.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,_.resetErrorsCount)(this.gen,this.errsCount)}ok(z){this.allErrors||this.gen.if(z)}setParams(z,H){H?Object.assign(this.params,z):this.params=z}block$data(z,H,W=a.nil){this.gen.block(()=>{this.check$data(z,W),H()})}check$data(z=a.nil,H=a.nil){if(!this.$data)return;const{gen:W,schemaCode:K,schemaType:oe,def:le}=this;W.if((0,a.or)((0,a._)`${K} === undefined`,H)),z!==a.nil&&W.assign(z,!0),(oe.length||le.validateSchema)&&(W.elseIf(this.invalid$data()),this.$dataError(),z!==a.nil&&W.assign(z,!1)),W.else()}invalid$data(){const{gen:z,schemaCode:H,schemaType:W,def:K,it:oe}=this;return(0,a.or)(le(),Me());function le(){if(W.length){if(!(H instanceof a.Name))throw new Error("ajv implementation error");const Ae=Array.isArray(W)?W:[W];return(0,a._)`${(0,n.checkDataTypes)(Ae,H,oe.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}function Me(){if(K.validateSchema){const Ae=z.scopeValue("validate$data",{ref:K.validateSchema});return(0,a._)`!${Ae}(${H})`}return a.nil}}subschema(z,H){const W=(0,i.getSubschema)(this.it,z);(0,i.extendSubschemaData)(W,this.it,z),(0,i.extendSubschemaMode)(W,z);const K={...this.it,...W,items:void 0,props:void 0};return y(K,H),K}mergeEvaluated(z,H){const{it:W,gen:K}=this;W.opts.unevaluated&&(W.props!==!0&&z.props!==void 0&&(W.props=u.mergeEvaluated.props(K,z.props,W.props,H)),W.items!==!0&&z.items!==void 0&&(W.items=u.mergeEvaluated.items(K,z.items,W.items,H)))}mergeValidEvaluated(z,H){const{it:W,gen:K}=this;if(W.opts.unevaluated&&(W.props!==!0||W.items!==!0))return K.if(H,()=>this.mergeEvaluated(z,a.Name)),!0}}Kt.KeywordCxt=E;function B(M,z,H,W){const K=new E(M,H,z);"code"in H?H.code(K,W):K.$data&&H.validate?(0,s.funcKeywordCode)(K,H):"macro"in H?(0,s.macroKeywordCode)(K,H):(H.compile||H.validate)&&(0,s.funcKeywordCode)(K,H)}const G=/^\/(?:[^~]|~0|~1)*$/,pe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ae(M,{dataLevel:z,dataNames:H,dataPathArr:W}){let K,oe;if(M==="")return l.default.rootData;if(M[0]==="/"){if(!G.test(M))throw new Error(`Invalid JSON-pointer: ${M}`);K=M,oe=l.default.rootData}else{const Q=pe.exec(M);if(!Q)throw new Error(`Invalid JSON-pointer: ${M}`);const ge=+Q[1];if(K=Q[2],K==="#"){if(ge>=z)throw new Error(Ae("property/index",ge));return W[z-ge]}if(ge>z)throw new Error(Ae("data",ge));if(oe=H[z-ge],!K)return oe}let le=oe;const Me=K.split("/");for(const Q of Me)Q&&(oe=(0,a._)`${oe}${(0,a.getProperty)((0,u.unescapeJsonPointer)(Q))}`,le=(0,a._)`${le} && ${oe}`);return le;function Ae(Q,ge){return`Cannot access ${Q} ${ge} levels up, current level is ${z}`}}return Kt.getData=ae,Kt}var gs={},Em;function Cl(){if(Em)return gs;Em=1,Object.defineProperty(gs,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return gs.default=e,gs}var _s={},Tm;function ys(){if(Tm)return _s;Tm=1,Object.defineProperty(_s,"__esModule",{value:!0});const e=hs();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 _s.default=t,_s}var yt={},Im;function $l(){if(Im)return yt;Im=1,Object.defineProperty(yt,"__esModule",{value:!0}),yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;const e=ye(),t=Cl(),r=fr(),n=hs(),o=Ce(),s=ms();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={}}}yt.SchemaEnv=i;function a(m){const w=u.call(this,m);if(w)return w;const g=(0,n.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:y,lines:b}=this.opts.code,{ownProperties:S}=this.opts,k=new e.CodeGen(this.scope,{es5:y,lines:b,ownProperties:S});let C;m.$async&&(C=k.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=k.scopeName("validate");m.validateName=I;const R={gen:k,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:k.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:g,baseId:m.baseId||g,schemaPath:e.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let L;try{this._compilations.add(m),(0,s.validateFunctionCode)(R),k.optimize(this.opts.code.optimize);const O=k.toString();L=`${k.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(L=this.opts.code.process(L,m));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=m.schema,D.schemaEnv=m,m.$async&&(D.$async=!0),this.opts.code.source===!0&&(D.source={validateName:I,validateCode:O,scopeValues:k._values}),this.opts.unevaluated){const{props:F,items:ee}=R;D.evaluated={props:F instanceof e.Name?void 0:F,items:ee instanceof e.Name?void 0:ee,dynamicProps:F instanceof e.Name,dynamicItems:ee instanceof e.Name},D.source&&(D.source.evaluated=(0,e.stringify)(D.evaluated))}return m.validate=D,m}catch(O){throw delete m.validate,delete m.validateName,L&&this.logger.error("Error compiling schema, function code:",L),O}finally{this._compilations.delete(m)}}yt.compileSchema=a;function l(m,w,g){var y;g=(0,n.resolveUrl)(this.opts.uriResolver,w,g);const b=m.refs[g];if(b)return b;let S=f.call(this,m,g);if(S===void 0){const k=(y=m.localRefs)===null||y===void 0?void 0:y[g],{schemaId:C}=this.opts;k&&(S=new i({schema:k,schemaId:C,root:m,baseId:w}))}if(S!==void 0)return m.refs[g]=c.call(this,S)}yt.resolveRef=l;function c(m){return(0,n.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:a.call(this,m)}function u(m){for(const w of this._compilations)if(_(w,m))return w}yt.getCompilingSchema=u;function _(m,w){return m.schema===w.schema&&m.root===w.root&&m.baseId===w.baseId}function f(m,w){let g;for(;typeof(g=this.refs[w])=="string";)w=g;return g||this.schemas[w]||d.call(this,m,w)}function d(m,w){const g=this.opts.uriResolver.parse(w),y=(0,n._getFullPath)(this.opts.uriResolver,g);let b=(0,n.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&y===b)return v.call(this,g,m);const S=(0,n.normalizeId)(y),k=this.refs[S]||this.schemas[S];if(typeof k=="string"){const C=d.call(this,m,k);return typeof C?.schema!="object"?void 0:v.call(this,g,C)}if(typeof k?.schema=="object"){if(k.validate||a.call(this,k),S===(0,n.normalizeId)(w)){const{schema:C}=k,{schemaId:I}=this.opts,R=C[I];return R&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,R)),new i({schema:C,schemaId:I,root:m,baseId:b})}return v.call(this,g,k)}}yt.resolveSchema=d;const p=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(m,{baseId:w,schema:g,root:y}){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 g=="boolean")return;const I=g[(0,o.unescapeFragment)(C)];if(I===void 0)return;g=I;const R=typeof g=="object"&&g[this.opts.schemaId];!p.has(C)&&R&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,R))}let S;if(typeof g!="boolean"&&g.$ref&&!(0,o.schemaHasRulesButRef)(g,this.RULES)){const C=(0,n.resolveUrl)(this.opts.uriResolver,w,g.$ref);S=d.call(this,y,C)}const{schemaId:k}=this.opts;if(S=S||new i({schema:g,schemaId:k,root:y,baseId:w}),S.schema!==S.root.schema)return S}return yt}const Sk={$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={},to={exports:{}},El,xm;function Rm(){if(xm)return El;xm=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 d="",p=0,v=0;for(v=0;v<f.length;v++)if(p=f[v].charCodeAt(0),p!==48){if(!(p>=48&&p<=57||p>=65&&p<=70||p>=97&&p<=102))return"";d+=f[v];break}for(v+=1;v<f.length;v++){if(p=f[v].charCodeAt(0),!(p>=48&&p<=57||p>=65&&p<=70||p>=97&&p<=102))return"";d+=f[v]}return d}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(f){return f.length=0,!0}function s(f,d,p){if(f.length){const v=r(f);if(v!=="")d.push(v);else return p.error=!0,!1;f.length=0}return!0}function i(f){let d=0;const p={error:!1,address:"",zone:""},v=[],m=[];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(m,v,p))break;if(++d>7){p.error=!0;break}b>0&&f[b-1]===":"&&(w=!0),v.push(":");continue}else if(S==="%"){if(!y(m,v,p))break;y=o}else{m.push(S);continue}}return m.length&&(y===o?p.zone=m.join(""):g?v.push(m.join("")):v.push(r(m))),p.address=v.join(""),p}function a(f){if(l(f,":")<2)return{host:f,isIPV6:!1};const d=i(f);if(d.error)return{host:f,isIPV6:!1};{let p=d.address,v=d.address;return d.zone&&(p+="%"+d.zone,v+="%25"+d.zone),{host:p,isIPV6:!0,escapedHost:v}}}function l(f,d){let p=0;for(let v=0;v<f.length;v++)f[v]===d&&p++;return p}function c(f){let d=f;const p=[];let v=-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((v=d.indexOf("/",1))===-1){p.push(d);break}else p.push(d.slice(0,v)),d=d.slice(v)}return p.join("")}function u(f,d){const p=d!==!0?escape:unescape;return f.scheme!==void 0&&(f.scheme=p(f.scheme)),f.userinfo!==void 0&&(f.userinfo=p(f.userinfo)),f.host!==void 0&&(f.host=p(f.host)),f.path!==void 0&&(f.path=p(f.path)),f.query!==void 0&&(f.query=p(f.query)),f.fragment!==void 0&&(f.fragment=p(f.fragment)),f}function _(f){const d=[];if(f.userinfo!==void 0&&(d.push(f.userinfo),d.push("@")),f.host!==void 0){let p=unescape(f.host);if(!t(p)){const v=a(p);v.isIPV6===!0?p=`[${v.escapedHost}]`:p=f.host}d.push(p)}return(typeof f.port=="number"||typeof f.port=="string")&&(d.push(":"),d.push(String(f.port))),d.length?d.join(""):void 0}return El={nonSimpleDomain:n,recomposeAuthority:_,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:r},El}var Tl,Pm;function kk(){if(Pm)return Tl;Pm=1;const{isUUID:e}=Rm(),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 k=String(S.scheme).toLowerCase()==="https";return(S.port===(k?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,C]=S.resourceName.split("?");S.path=k&&k!=="/"?k:void 0,S.query=C,S.resourceName=void 0}return S.fragment=void 0,S}function c(S,k){if(!S.path)return S.error="URN can not be parsed",S;const C=S.path.match(t);if(C){const I=k.scheme||S.scheme||"urn";S.nid=C[1].toLowerCase(),S.nss=C[2];const R=`${I}:${k.nid||S.nid}`,L=b(R);S.path=void 0,L&&(S=L.parse(S,k))}else S.error=S.error||"URN can not be parsed.";return S}function u(S,k){if(S.nid===void 0)throw new Error("URN without nid cannot be serialized");const C=k.scheme||S.scheme||"urn",I=S.nid.toLowerCase(),R=`${C}:${k.nid||I}`,L=b(R);L&&(S=L.serialize(S,k));const O=S,U=S.nss;return O.path=`${I||k.nid}:${U}`,k.skipEscape=!0,O}function _(S,k){const C=S;return C.uuid=C.nss,C.nss=void 0,!k.tolerant&&(!C.uuid||!e(C.uuid))&&(C.error=C.error||"UUID is not valid."),C}function f(S){const k=S;return k.nss=(S.uuid||"").toLowerCase(),k}const d={scheme:"http",domainHost:!0,parse:s,serialize:i},p={scheme:"https",domainHost:d.domainHost,parse:s,serialize:i},v={scheme:"ws",domainHost:!0,parse:a,serialize:l},m={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},y={http:d,https:p,ws:v,wss:m,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:_,serialize:f,skipNormalize:!0}};Object.setPrototypeOf(y,null);function b(S){return S&&(y[S]||y[S.toLowerCase()])||void 0}return Tl={wsIsSecure:o,SCHEMES:y,isValidSchemeName:n,getSchemeHandler:b},Tl}var Om;function Ck(){if(Om)return to.exports;Om=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Rm(),{SCHEMES:i,getSchemeHandler:a}=kk();function l(m,w){return typeof m=="string"?m=f(p(m,w),w):typeof m=="object"&&(m=p(f(m,w),w)),m}function c(m,w,g){const y=g?Object.assign({scheme:"null"},g):{scheme:"null"},b=u(p(m,y),p(w,y),y,!0);return y.skipEscape=!0,f(b,y)}function u(m,w,g,y){const b={};return y||(m=p(f(m,g),g),w=p(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):((m.userinfo!==void 0||m.host!==void 0||m.port!==void 0)&&!m.path?b.path="/"+w.path:m.path?b.path=m.path.slice(0,m.path.lastIndexOf("/")+1)+w.path:b.path=w.path,b.path=t(b.path)),b.query=w.query):(b.path=m.path,w.query!==void 0?b.query=w.query:b.query=m.query),b.userinfo=m.userinfo,b.host=m.host,b.port=m.port),b.scheme=m.scheme),b.fragment=w.fragment,b}function _(m,w,g){return typeof m=="string"?(m=unescape(m),m=f(n(p(m,g),!0),{...g,skipEscape:!0})):typeof m=="object"&&(m=f(n(m,!0),{...g,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=f(n(p(w,g),!0),{...g,skipEscape:!0})):typeof w=="object"&&(w=f(n(w,!0),{...g,skipEscape:!0})),m.toLowerCase()===w.toLowerCase()}function f(m,w){const g={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:""},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 k=r(g);if(k!==void 0&&(y.reference!=="suffix"&&b.push("//"),b.push(k),g.path&&g.path[0]!=="/"&&b.push("/")),g.path!==void 0){let C=g.path;!y.absolutePath&&(!S||!S.absolutePath)&&(C=t(C)),k===void 0&&C[0]==="/"&&C[1]==="/"&&(C="/%2F"+C.slice(2)),b.push(C)}return g.query!==void 0&&b.push("?",g.query),g.fragment!==void 0&&b.push("#",g.fragment),b.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function p(m,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?m=g.scheme+":"+m:m="//"+m);const S=m.match(d);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 k=a(g.scheme||y.scheme);if(!g.unicodeSupport&&(!k||!k.unicodeSupport)&&y.host&&(g.domainHost||k&&k.domainHost)&&b===!1&&s(y.host))try{y.host=URL.domainToASCII(y.host.toLowerCase())}catch(C){y.error=y.error||"Host's domain name can not be converted to ASCII: "+C}(!k||k&&!k.skipNormalize)&&(m.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)))),k&&k.parse&&k.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:_,serialize:f,parse:p};return to.exports=v,to.exports.default=v,to.exports.fastUri=v,to.exports}var Mm;function $k(){if(Mm)return vs;Mm=1,Object.defineProperty(vs,"__esModule",{value:!0});const e=Ck();return e.code='require("ajv/dist/runtime/uri").default',vs.default=e,vs}var Nm;function Ek(){return Nm||(Nm=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=ms();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=ys(),s=fm(),i=$l(),a=ye(),l=hs(),c=fs(),u=Ce(),_=Sk,f=$k(),d=(V,P)=>new RegExp(V,P);d.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],v=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."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},g=200;function y(V){var P,Z,j,T,x,E,B,G,pe,ae,M,z,H,W,K,oe,le,Me,Ae,Q,ge,at,we,dt,rr;const pt=V.strict,Ye=(P=V.code)===null||P===void 0?void 0:P.optimize,Ct=Ye===!0||Ye===void 0?1:Ye||0,vr=(j=(Z=V.code)===null||Z===void 0?void 0:Z.regExp)!==null&&j!==void 0?j:d,wr=(T=V.uriResolver)!==null&&T!==void 0?T:f.default;return{strictSchema:(E=(x=V.strictSchema)!==null&&x!==void 0?x:pt)!==null&&E!==void 0?E:!0,strictNumbers:(G=(B=V.strictNumbers)!==null&&B!==void 0?B:pt)!==null&&G!==void 0?G:!0,strictTypes:(ae=(pe=V.strictTypes)!==null&&pe!==void 0?pe:pt)!==null&&ae!==void 0?ae:"log",strictTuples:(z=(M=V.strictTuples)!==null&&M!==void 0?M:pt)!==null&&z!==void 0?z:"log",strictRequired:(W=(H=V.strictRequired)!==null&&H!==void 0?H:pt)!==null&&W!==void 0?W:!1,code:V.code?{...V.code,optimize:Ct,regExp:vr}:{optimize:Ct,regExp:vr},loopRequired:(K=V.loopRequired)!==null&&K!==void 0?K:g,loopEnum:(oe=V.loopEnum)!==null&&oe!==void 0?oe:g,meta:(le=V.meta)!==null&&le!==void 0?le:!0,messages:(Me=V.messages)!==null&&Me!==void 0?Me:!0,inlineRefs:(Ae=V.inlineRefs)!==null&&Ae!==void 0?Ae:!0,schemaId:(Q=V.schemaId)!==null&&Q!==void 0?Q:"$id",addUsedSchema:(ge=V.addUsedSchema)!==null&&ge!==void 0?ge:!0,validateSchema:(at=V.validateSchema)!==null&&at!==void 0?at:!0,validateFormats:(we=V.validateFormats)!==null&&we!==void 0?we:!0,unicodeRegExp:(dt=V.unicodeRegExp)!==null&&dt!==void 0?dt:!0,int32range:(rr=V.int32range)!==null&&rr!==void 0?rr:!0,uriResolver:wr}}class b{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,...y(P)};const{es5:Z,lines:j}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:Z,lines:j}),this.logger=U(P.logger);const T=P.validateFormats;P.validateFormats=!1,this.RULES=(0,s.getRules)(),S.call(this,m,P,"NOT SUPPORTED"),S.call(this,w,P,"DEPRECATED","warn"),this._metaOpts=L.call(this),P.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&R.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),C.call(this),P.validateFormats=T}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:P,meta:Z,schemaId:j}=this.opts;let T=_;j==="id"&&(T={..._},T.id=T.$id,delete T.$id),Z&&P&&this.addMetaSchema(T,T[j],!1)}defaultMeta(){const{meta:P,schemaId:Z}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[Z]||P:void 0}validate(P,Z){let j;if(typeof P=="string"){if(j=this.getSchema(P),!j)throw new Error(`no schema with key or ref "${P}"`)}else j=this.compile(P);const T=j(Z);return"$async"in j||(this.errors=j.errors),T}compile(P,Z){const j=this._addSchema(P,Z);return j.validate||this._compileSchemaEnv(j)}compileAsync(P,Z){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:j}=this.opts;return T.call(this,P,Z);async function T(ae,M){await x.call(this,ae.$schema);const z=this._addSchema(ae,M);return z.validate||E.call(this,z)}async function x(ae){ae&&!this.getSchema(ae)&&await T.call(this,{$ref:ae},!0)}async function E(ae){try{return this._compileSchemaEnv(ae)}catch(M){if(!(M instanceof o.default))throw M;return B.call(this,M),await G.call(this,M.missingSchema),E.call(this,ae)}}function B({missingSchema:ae,missingRef:M}){if(this.refs[ae])throw new Error(`AnySchema ${ae} is loaded but ${M} cannot be resolved`)}async function G(ae){const M=await pe.call(this,ae);this.refs[ae]||await x.call(this,M.$schema),this.refs[ae]||this.addSchema(M,ae,Z)}async function pe(ae){const M=this._loading[ae];if(M)return M;try{return await(this._loading[ae]=j(ae))}finally{delete this._loading[ae]}}}addSchema(P,Z,j,T=this.opts.validateSchema){if(Array.isArray(P)){for(const E of P)this.addSchema(E,void 0,j,T);return this}let x;if(typeof P=="object"){const{schemaId:E}=this.opts;if(x=P[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(P,j,Z,T,!0),this}addMetaSchema(P,Z,j=this.opts.validateSchema){return this.addSchema(P,Z,!0,j),this}validateSchema(P,Z){if(typeof P=="boolean")return!0;let j;if(j=P.$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 T=this.validate(j,P);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(P){let Z;for(;typeof(Z=k.call(this,P))=="string";)P=Z;if(Z===void 0){const{schemaId:j}=this.opts,T=new i.SchemaEnv({schema:{},schemaId:j});if(Z=i.resolveSchema.call(this,T,P),!Z)return;this.refs[P]=Z}return Z.validate||this._compileSchemaEnv(Z)}removeSchema(P){if(P instanceof RegExp)return this._removeAllSchemas(this.schemas,P),this._removeAllSchemas(this.refs,P),this;switch(typeof P){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const Z=k.call(this,P);return typeof Z=="object"&&this._cache.delete(Z.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{const Z=P;this._cache.delete(Z);let j=P[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(P){for(const Z of P)this.addKeyword(Z);return this}addKeyword(P,Z){let j;if(typeof P=="string")j=P,typeof Z=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Z.keyword=j);else if(typeof P=="object"&&Z===void 0){if(Z=P,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,x=>ee.call(this,x)),this;se.call(this,Z);const T={...Z,type:(0,c.getJSONTypes)(Z.type),schemaType:(0,c.getJSONTypes)(Z.schemaType)};return(0,u.eachItem)(j,T.type.length===0?x=>ee.call(this,x,T):x=>T.type.forEach(E=>ee.call(this,x,T,E))),this}getKeyword(P){const Z=this.RULES.all[P];return typeof Z=="object"?Z.definition:!!Z}removeKeyword(P){const{RULES:Z}=this;delete Z.keywords[P],delete Z.all[P];for(const j of Z.rules){const T=j.rules.findIndex(x=>x.keyword===P);T>=0&&j.rules.splice(T,1)}return this}addFormat(P,Z){return typeof Z=="string"&&(Z=new RegExp(Z)),this.formats[P]=Z,this}errorsText(P=this.errors,{separator:Z=", ",dataVar:j="data"}={}){return!P||P.length===0?"No errors":P.map(T=>`${j}${T.instancePath} ${T.message}`).reduce((T,x)=>T+Z+x)}$dataMetaSchema(P,Z){const j=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(const T of Z){const x=T.split("/").slice(1);let E=P;for(const B of x)E=E[B];for(const B in j){const G=j[B];if(typeof G!="object")continue;const{$data:pe}=G.definition,ae=E[B];pe&&ae&&(E[B]=de(ae))}}return P}_removeAllSchemas(P,Z){for(const j in P){const T=P[j];(!Z||Z.test(j))&&(typeof T=="string"?delete P[j]:T&&!T.meta&&(this._cache.delete(T.schema),delete P[j]))}}_addSchema(P,Z,j,T=this.opts.validateSchema,x=this.opts.addUsedSchema){let E;const{schemaId:B}=this.opts;if(typeof P=="object")E=P[B];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof P!="boolean")throw new Error("schema must be object or boolean")}let G=this._cache.get(P);if(G!==void 0)return G;j=(0,l.normalizeId)(E||j);const pe=l.getSchemaRefs.call(this,P,j);return G=new i.SchemaEnv({schema:P,schemaId:B,meta:Z,baseId:j,localRefs:pe}),this._cache.set(G.schema,G),x&&!j.startsWith("#")&&(j&&this._checkUnique(j),this.refs[j]=G),T&&this.validateSchema(P,!0),G}_checkUnique(P){if(this.schemas[P]||this.refs[P])throw new Error(`schema with key or id "${P}" already exists`)}_compileSchemaEnv(P){if(P.meta?this._compileMetaSchema(P):i.compileSchema.call(this,P),!P.validate)throw new Error("ajv implementation error");return P.validate}_compileMetaSchema(P){const Z=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,P)}finally{this.opts=Z}}}b.ValidationError=n.default,b.MissingRefError=o.default,e.default=b;function S(V,P,Z,j="error"){for(const T in V){const x=T;x in P&&this.logger[j](`${Z}: option ${T}. ${V[x]}`)}}function k(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 P in V)this.addSchema(V[P],P)}function I(){for(const V in this.opts.formats){const P=this.opts.formats[V];P&&this.addFormat(V,P)}}function R(V){if(Array.isArray(V)){this.addVocabulary(V);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const P in V){const Z=V[P];Z.keyword||(Z.keyword=P),this.addKeyword(Z)}}function L(){const V={...this.opts};for(const P of p)delete V[P];return V}const O={log(){},warn(){},error(){}};function U(V){if(V===!1)return O;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,P){const{RULES:Z}=this;if((0,u.eachItem)(V,j=>{if(Z.keywords[j])throw new Error(`Keyword ${j} is already defined`);if(!D.test(j))throw new Error(`Keyword ${j} has invalid name`)}),!!P&&P.$data&&!("code"in P||"validate"in P))throw new Error('$data keyword must have "code" or "validate" function')}function ee(V,P,Z){var j;const T=P?.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:G})=>G===Z);if(E||(E={type:Z,rules:[]},x.rules.push(E)),x.keywords[V]=!0,!P)return;const B={keyword:V,definition:{...P,type:(0,c.getJSONTypes)(P.type),schemaType:(0,c.getJSONTypes)(P.schemaType)}};P.before?ie.call(this,E,B,P.before):E.rules.push(B),x.all[V]=B,(j=P.implements)===null||j===void 0||j.forEach(G=>this.addKeyword(G))}function ie(V,P,Z){const j=V.rules.findIndex(T=>T.keyword===Z);j>=0?V.rules.splice(j,0,P):(V.rules.push(P),this.logger.warn(`rule ${Z} is not defined`))}function se(V){let{metaSchema:P}=V;P!==void 0&&(V.$data&&this.opts.$data&&(P=de(P)),V.validateSchema=this.compile(P,!0))}const X={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function de(V){return{anyOf:[V,X]}}})(_l)),_l}var ws={},bs={},Ss={},Am;function Tk(){if(Am)return Ss;Am=1,Object.defineProperty(Ss,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Ss.default=e,Ss}var hr={},qm;function Ik(){if(qm)return hr;qm=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.callRef=hr.getValidate=void 0;const e=ys(),t=Ot(),r=ye(),n=fr(),o=$l(),s=Ce(),i={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:_,it:f}=c,{baseId:d,schemaEnv:p,validateName:v,opts:m,self:w}=f,{root:g}=p;if((_==="#"||_==="#/")&&d===g.baseId)return b();const y=o.resolveRef.call(w,g,d,_);if(y===void 0)throw new e.default(f.opts.uriResolver,d,_);if(y instanceof o.SchemaEnv)return S(y);return k(y);function b(){if(p===g)return l(c,v,p,p.$async);const C=u.scopeValue("root",{ref:g});return l(c,(0,r._)`${C}.validate`,g,g.$async)}function S(C){const I=a(c,C);l(c,I,C,C.$async)}function k(C){const I=u.scopeValue("schema",m.code.source===!0?{ref:C,code:(0,r.stringify)(C)}:{ref:C}),R=u.name("valid"),L=c.subschema({schema:C,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:_},R);c.mergeEvaluated(L),c.ok(R)}}};function a(c,u){const{gen:_}=c;return u.validate?_.scopeValue("validate",{ref:u.validate}):(0,r._)`${_.scopeValue("wrapper",{ref:u})}.validate`}hr.getValidate=a;function l(c,u,_,f){const{gen:d,it:p}=c,{allErrors:v,schemaEnv:m,opts:w}=p,g=w.passContext?n.default.this:r.nil;f?y():b();function y(){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,g)}`),k(u),v||d.assign(C,!0)},I=>{d.if((0,r._)`!(${I} instanceof ${p.ValidationError})`,()=>d.throw(I)),S(I),v||d.assign(C,!1)}),c.ok(C)}function b(){c.result((0,t.callValidateCode)(c,u,g),()=>k(u),()=>S(u))}function S(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 k(C){var I;if(!p.opts.unevaluated)return;const R=(I=_?.validate)===null||I===void 0?void 0:I.evaluated;if(p.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(p.props=s.mergeEvaluated.props(d,R.props,p.props));else{const L=d.var("props",(0,r._)`${C}.evaluated.props`);p.props=s.mergeEvaluated.props(d,L,p.props,r.Name)}if(p.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(p.items=s.mergeEvaluated.items(d,R.items,p.items));else{const L=d.var("items",(0,r._)`${C}.evaluated.items`);p.items=s.mergeEvaluated.items(d,L,p.items,r.Name)}}}return hr.callRef=l,hr.default=i,hr}var Lm;function xk(){if(Lm)return bs;Lm=1,Object.defineProperty(bs,"__esModule",{value:!0});const e=Tk(),t=Ik(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return bs.default=r,bs}var ks={},Cs={},jm;function Rk(){if(jm)return Cs;jm=1,Object.defineProperty(Cs,"__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: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 Cs.default=o,Cs}var $s={},Um;function Pk(){if(Um)return $s;Um=1,Object.defineProperty($s,"__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: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 $s.default=r,$s}var Es={},Ts={},Dm;function Ok(){if(Dm)return Ts;Dm=1,Object.defineProperty(Ts,"__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 Ts.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Ts}var zm;function Mk(){if(zm)return Es;zm=1,Object.defineProperty(Es,"__esModule",{value:!0});const e=ye(),t=Ce(),r=Ok(),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,_=c.opts.unicode===!1?(0,e._)`${a}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${a})`;s.fail$data((0,e._)`${_} ${u} ${l}`)}};return Es.default=o,Es}var Is={},Zm;function Nk(){if(Zm)return Is;Zm=1,Object.defineProperty(Is,"__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:i,schema:a,schemaCode:l,it:c}=o,u=c.opts.unicodeRegExp?"u":"",_=i?(0,t._)`(new RegExp(${l}, ${u}))`:(0,e.usePattern)(o,a);o.fail$data((0,t._)`!${_}.test(${s})`)}};return Is.default=n,Is}var xs={},Fm;function Ak(){if(Fm)return xs;Fm=1,Object.defineProperty(xs,"__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:i}=n,a=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${a} ${i}`)}};return xs.default=r,xs}var Rs={},Vm;function qk(){if(Vm)return Rs;Vm=1,Object.defineProperty(Rs,"__esModule",{value:!0});const e=Ot(),t=ye(),r=Ce(),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:_}=s,{opts:f}=_;if(!u&&a.length===0)return;const d=a.length>=f.loopRequired;if(_.allErrors?p():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=_.schemaEnv.baseId+_.errSchemaPath,k=`required property "${b}" is not defined at "${S}" (strictRequired)`;(0,r.checkStrictMode)(_,k,_.opts.strictRequired)}}function p(){if(d||u)s.block$data(t.nil,m);else for(const g of a)(0,e.checkReportMissingProp)(s,g)}function v(){const g=i.let("missing");if(d||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 m(){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 Rs.default=o,Rs}var Ps={},Bm;function Lk(){if(Bm)return Ps;Bm=1,Object.defineProperty(Ps,"__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:i}=n,a=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${a} ${i}`)}};return Ps.default=r,Ps}var Os={},Ms={},Hm;function Il(){if(Hm)return Ms;Hm=1,Object.defineProperty(Ms,"__esModule",{value:!0});const e=Sm();return e.code='require("ajv/dist/runtime/equal").default',Ms.default=e,Ms}var Jm;function jk(){if(Jm)return Os;Jm=1,Object.defineProperty(Os,"__esModule",{value:!0});const e=fs(),t=ye(),r=Ce(),n=Il(),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:_,schemaCode:f,it:d}=i;if(!c&&!u)return;const p=a.let("valid"),v=_.items?(0,e.getSchemaTypes)(_.items):[];i.block$data(p,m,(0,t._)`${f} === false`),i.ok(p);function m(){const b=a.let("i",(0,t._)`${l}.length`),S=a.let("j");i.setParams({i:b,j:S}),a.assign(p,!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 k=a.name("item"),C=(0,e.checkDataTypes)(v,k,d.opts.strictNumbers,e.DataType.Wrong),I=a.const("indices",(0,t._)`{}`);a.for((0,t._)`;${b}--;`,()=>{a.let(k,(0,t._)`${l}[${b}]`),a.if(C,(0,t._)`continue`),v.length>1&&a.if((0,t._)`typeof ${k} == "string"`,(0,t._)`${k} += "_"`),a.if((0,t._)`typeof ${I}[${k}] == "number"`,()=>{a.assign(S,(0,t._)`${I}[${k}]`),i.error(),a.assign(p,!1).break()}).code((0,t._)`${I}[${k}] = ${b}`)})}function y(b,S){const k=(0,r.useFunc)(a,n.default),C=a.name("outer");a.label(C).for((0,t._)`;${b}--;`,()=>a.for((0,t._)`${S} = ${b}; ${S}--;`,()=>a.if((0,t._)`${k}(${l}[${b}], ${l}[${S}])`,()=>{i.error(),a.assign(p,!1).break(C)})))}}};return Os.default=s,Os}var Ns={},Gm;function Uk(){if(Gm)return Ns;Gm=1,Object.defineProperty(Ns,"__esModule",{value:!0});const e=ye(),t=Ce(),r=Il(),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 Ns.default=o,Ns}var As={},Wm;function Dk(){if(Wm)return As;Wm=1,Object.defineProperty(As,"__esModule",{value:!0});const e=ye(),t=Ce(),r=Il(),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:_}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const f=c.length>=_.opts.loopEnum;let d;const p=()=>d??(d=(0,t.useFunc)(i,r.default));let v;if(f||l)v=i.let("valid"),s.block$data(v,m);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 m(){i.assign(v,!1),i.forOf("v",u,g=>i.if((0,e._)`${p()}(${a}, ${g})`,()=>i.assign(v,!0).break()))}function w(g,y){const b=c[y];return typeof b=="object"&&b!==null?(0,e._)`${p()}(${a}, ${g}[${y}])`:(0,e._)`${a} === ${b}`}}};return As.default=o,As}var Km;function zk(){if(Km)return ks;Km=1,Object.defineProperty(ks,"__esModule",{value:!0});const e=Rk(),t=Pk(),r=Mk(),n=Nk(),o=Ak(),s=qk(),i=Lk(),a=jk(),l=Uk(),c=Dk(),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 ks.default=u,ks}var qs={},ln={},Ym;function Qm(){if(Ym)return ln;Ym=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.validateAdditionalItems=void 0;const e=ye(),t=Ce(),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:_}=s;_.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)(_,l)){const p=a.var("valid",(0,e._)`${f} <= ${i.length}`);a.if((0,e.not)(p),()=>d(p)),s.ok(p)}function d(p){a.forRange("i",i.length,f,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},p),_.allErrors||a.if((0,e.not)(p),()=>a.break())})}}return ln.validateAdditionalItems=o,ln.default=n,ln}var Ls={},cn={},Xm;function e2(){if(Xm)return cn;Xm=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.validateTuple=void 0;const e=ye(),t=Ce(),r=Ot(),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:_,it:f}=s;v(c),f.opts.unevaluated&&a.length&&f.items!==!0&&(f.items=t.mergeEvaluated.items(l,a.length,f.items));const d=l.name("valid"),p=l.const("len",(0,e._)`${u}.length`);a.forEach((m,w)=>{(0,t.alwaysValidSchema)(f,m)||(l.if((0,e._)`${p} > ${w}`,()=>s.subschema({keyword:_,schemaProp:w,dataProp:w},d)),s.ok(d))});function v(m){const{opts:w,errSchemaPath:g}=f,y=a.length,b=y===m.minItems&&(y===m.maxItems||m[i]===!1);if(w.strictTuples&&!b){const S=`"${_}" is ${y}-tuple, but minItems or maxItems/${i} are not specified or different at path "${g}"`;(0,t.checkStrictMode)(f,S,w.strictTuples)}}}return cn.validateTuple=o,cn.default=n,cn}var t2;function Zk(){if(t2)return Ls;t2=1,Object.defineProperty(Ls,"__esModule",{value:!0});const e=e2(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return Ls.default=t,Ls}var js={},r2;function Fk(){if(r2)return js;r2=1,Object.defineProperty(js,"__esModule",{value:!0});const e=ye(),t=Ce(),r=Ot(),n=Qm(),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 js.default=s,js}var Us={},n2;function Vk(){if(n2)return Us;n2=1,Object.defineProperty(Us,"__esModule",{value:!0});const e=ye(),t=Ce(),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,_;const{minContains:f,maxContains:d}=a;c.opts.next?(u=f===void 0?1:f,_=d):u=1;const p=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:_}),_===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(_!==void 0&&u>_){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,i)){let y=(0,e._)`${p} >= ${u}`;_!==void 0&&(y=(0,e._)`${y} && ${p} <= ${_}`),o.pass(y);return}c.items=!0;const v=s.name("valid");_===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),_!==void 0&&s.if((0,e._)`${l}.length > 0`,m)):(s.let(v,!1),m()),o.result(v,()=>o.reset());function m(){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,p,S=>{o.subschema({keyword:"contains",dataProp:S,dataPropType:t.Type.Num,compositeRule:!0},y),b()})}function g(y){s.code((0,e._)`${y}++`),_===void 0?s.if((0,e._)`${y} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${y} > ${_}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${y} >= ${u}`,()=>s.assign(v,!0)))}}};return Us.default=n,Us}var xl={},o2;function Bk(){return o2||(o2=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=ye(),r=Ce(),n=Ot();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const _=c===1?"property":"properties";return(0,t.str)`must have ${_} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:_}})=>(0,t._)`{property: ${l},
78
- missingProperty: ${_},
79
+ ${t}:`]}}function c2({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 u2(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var BS=be(()=>we(T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d(),logprobs:T({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ge(d(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),HS=be(()=>we(oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d().nullish(),index:j(),logprobs:T({tokens:q(d()),token_logprobs:q(j()),top_logprobs:q(ge(d(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),jc]))),d2=be(()=>we(T({echo:fe().optional(),logitBias:ge(d(),j()).optional(),suffix:d().optional(),user:d().optional(),logprobs:oe([fe(),j()]).optional()}))),JS=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:m,providerOptions:p}){const f=[],g={...await Pr({provider:"openai",providerOptions:p,schema:d2}),...await Pr({provider:this.providerOptionsName,providerOptions:p,schema:d2})};o!=null&&f.push({type:"unsupported",feature:"topK"}),c?.length&&f.push({type:"unsupported",feature:"tools"}),u!=null&&f.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&f.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:y}=ZS({prompt:e}),w=[...y??[],...i??[]];return{args:{model:this.modelId,echo:g.echo,logit_bias:g.logitBias,logprobs:g?.logprobs===!0?0:g?.logprobs===!1?void 0:g?.logprobs,suffix:g.suffix,user:g.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:m,prompt:v,stop:w.length>0?w:void 0},warnings:f}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:a}=await Dt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Pt(this.config.headers(),e.headers),body:r,failedResponseHandler:cr,successfulResponseHandler:Xt(BS),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=s.choices[0],l={openai:{}};return i.logprobs!=null&&(l.openai.logprobs=i.logprobs),{content:[{type:"text",text:i.text}],usage:l2(s.usage),finishReason:{unified:u2(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...c2(s),headers:o,body:a},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await Dt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Pt(this.config.headers(),e.headers),body:n,failedResponseHandler:cr,successfulResponseHandler:Zs(HS),abortSignal:e.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,m){if(e.includeRawChunks&&m.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},m.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},m.enqueue({type:"error",error:p.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",...c2(p)}),m.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const f=p.choices[0];f?.finish_reason!=null&&(a={unified:u2(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(i.openai.logprobs=f.logprobs),f?.text!=null&&f.text.length>0&&m.enqueue({type:"text-delta",id:"0",delta:f.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l2(l)})}})),request:{body:n},response:{headers:o}}}},GS=be(()=>we(T({dimensions:j().optional(),user:d().optional()}))),WS=be(()=>we(T({data:q(T({embedding:q(j())})),usage:T({prompt_tokens:j()}).nullish()}))),KS=class{constructor(e,t){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new lv({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Pr({provider:"openai",providerOptions:n,schema:GS}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await Dt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Pt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:cr,successfulResponseHandler:Xt(WS),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},p2=be(()=>we(T({created:j().nullish(),data:q(T({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:T({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:T({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),YS={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},QS=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function XS(e){return QS.some(t=>e.startsWith(t))}var eI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=YS[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:s,seed:a,providerOptions:i,headers:l,abortSignal:c}){var u,m,p,f,g,v,y,w,_,h,S;const k=[];s!=null&&k.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&k.push({type:"unsupported",feature:"seed"});const C=(p=(m=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:m.call(u))!=null?p:new Date;if(t!=null){const{value:I,responseHeaders:L}=await Pf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Pt(this.config.headers(),l),formData:q3({model:this.modelId,prompt:e,image:await Promise.all(t.map(M=>M.type==="file"?new Blob([M.data instanceof Uint8Array?new Blob([M.data],{type:M.mediaType}):new Blob([Gn(M.data)],{type:M.mediaType})],{type:M.mediaType}):_f(M.url))),mask:r!=null?await tI(r):void 0,n,size:o,...(f=i.openai)!=null?f:{}}),failedResponseHandler:cr,successfulResponseHandler:Xt(p2),abortSignal:c,fetch:this.config.fetch});return{images:I.data.map(M=>M.b64_json),warnings:k,usage:I.usage!=null?{inputTokens:(g=I.usage.input_tokens)!=null?g:void 0,outputTokens:(v=I.usage.output_tokens)!=null?v:void 0,totalTokens:(y=I.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:L},providerMetadata:{openai:{images:I.data.map((M,A)=>{var O,U,G,H,le,ee;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(O=I.created)!=null?O:void 0,size:(U=I.size)!=null?U:void 0,quality:(G=I.quality)!=null?G:void 0,background:(H=I.background)!=null?H:void 0,outputFormat:(le=I.output_format)!=null?le:void 0,...f2((ee=I.usage)==null?void 0:ee.input_tokens_details,A,I.data.length)}})}}}}const{value:b,responseHeaders:E}=await Dt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Pt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=i.openai)!=null?w:{},...XS(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:cr,successfulResponseHandler:Xt(p2),abortSignal:c,fetch:this.config.fetch});return{images:b.data.map(I=>I.b64_json),warnings:k,usage:b.usage!=null?{inputTokens:(_=b.usage.input_tokens)!=null?_:void 0,outputTokens:(h=b.usage.output_tokens)!=null?h:void 0,totalTokens:(S=b.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:C,modelId:this.modelId,headers:E},providerMetadata:{openai:{images:b.data.map((I,L)=>{var M,A,O,U,G,H;return{...I.revised_prompt?{revisedPrompt:I.revised_prompt}:{},created:(M=b.created)!=null?M:void 0,size:(A=b.size)!=null?A:void 0,quality:(O=b.quality)!=null?O:void 0,background:(U=b.background)!=null?U:void 0,outputFormat:(G=b.output_format)!=null?G:void 0,...f2((H=b.usage)==null?void 0:H.input_tokens_details,L,b.data.length)}})}}}}};function f2(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),s=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),s=e.text_tokens-o*(r-1);n.textTokens=t===r-1?s:o}return n}async function tI(e){if(!e)return;if(e.type==="url")return _f(e.url);const t=e.data instanceof Uint8Array?e.data:Gn(e.data);return new Blob([t],{type:e.mediaType})}var h2=be(()=>we(T({callId:d(),operation:De("type",[T({type:$("create_file"),path:d(),diff:d()}),T({type:$("delete_file"),path:d()}),T({type:$("update_file"),path:d(),diff:d()})])}))),m2=be(()=>we(T({status:_e(["completed","failed"]),output:d().optional()}))),rI=ir({id:"openai.apply_patch",inputSchema:h2,outputSchema:m2}),nI=rI,oI=be(()=>we(T({code:d().nullish(),containerId:d()}))),sI=be(()=>we(T({outputs:q(De("type",[T({type:$("logs"),logs:d()}),T({type:$("image"),url:d()})])).nullish()}))),aI=be(()=>we(T({container:oe([d(),T({fileIds:q(d()).optional()})]).optional()}))),iI=ir({id:"openai.code_interpreter",inputSchema:oI,outputSchema:sI}),lI=(e={})=>iI(e),g2=T({key:d(),type:_e(["eq","ne","gt","gte","lt","lte","in","nin"]),value:oe([d(),j(),fe(),q(d())])}),y2=T({type:_e(["and","or"]),filters:q(oe([g2,Yi(()=>y2)]))}),cI=be(()=>we(T({vectorStoreIds:q(d()),maxNumResults:j().optional(),ranking:T({ranker:d().optional(),scoreThreshold:j().optional()}).optional(),filters:oe([g2,y2]).optional()}))),uI=be(()=>we(T({queries:q(d()),results:q(T({attributes:ge(d(),$e()),fileId:d(),filename:d(),score:j(),text:d()})).nullable()}))),dI=ir({id:"openai.file_search",inputSchema:T({}),outputSchema:uI}),pI=be(()=>we(T({background:_e(["auto","opaque","transparent"]).optional(),inputFidelity:_e(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:_e(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:_e(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:_e(["auto","low","medium","high"]).optional(),size:_e(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),fI=be(()=>we(T({}))),hI=be(()=>we(T({result:d()}))),mI=ir({id:"openai.image_generation",inputSchema:fI,outputSchema:hI}),gI=(e={})=>mI(e),_2=be(()=>we(T({action:T({type:$("exec"),command:q(d()),timeoutMs:j().optional(),user:d().optional(),workingDirectory:d().optional(),env:ge(d(),d()).optional()})}))),v2=be(()=>we(T({output:d()}))),yI=ir({id:"openai.local_shell",inputSchema:_2,outputSchema:v2}),w2=be(()=>we(T({action:T({commands:q(d()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),Uc=be(()=>we(T({output:q(T({stdout:d(),stderr:d(),outcome:De("type",[T({type:$("timeout")}),T({type:$("exit"),exitCode:j()})])}))}))),_I=q(De("type",[T({type:$("skillReference"),skillId:d(),version:d().optional()}),T({type:$("inline"),name:d(),description:d(),source:T({type:$("base64"),mediaType:$("application/zip"),data:d()})})])).optional(),vI=be(()=>we(T({environment:oe([T({type:$("containerAuto"),fileIds:q(d()).optional(),memoryLimit:_e(["1g","4g","16g","64g"]).optional(),networkPolicy:De("type",[T({type:$("disabled")}),T({type:$("allowlist"),allowedDomains:q(d()),domainSecrets:q(T({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:_I}),T({type:$("containerReference"),containerId:d()}),T({type:$("local").optional(),skills:q(T({name:d(),description:d(),path:d()})).optional()})]).optional()}))),wI=ir({id:"openai.shell",inputSchema:w2,outputSchema:Uc}),bI=be(()=>we(T({externalWebAccess:fe().optional(),filters:T({allowedDomains:q(d()).optional()}).optional(),searchContextSize:_e(["low","medium","high"]).optional(),userLocation:T({type:$("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),kI=be(()=>we(T({}))),CI=be(()=>we(T({action:De("type",[T({type:$("search"),query:d().optional()}),T({type:$("openPage"),url:d().nullish()}),T({type:$("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(De("type",[T({type:$("url"),url:d()}),T({type:$("api"),name:d()})])).optional()}))),TI=ir({id:"openai.web_search",inputSchema:kI,outputSchema:CI}),SI=(e={})=>TI(e),II=be(()=>we(T({searchContextSize:_e(["low","medium","high"]).optional(),userLocation:T({type:$("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),xI=be(()=>we(T({}))),EI=be(()=>we(T({action:De("type",[T({type:$("search"),query:d().optional()}),T({type:$("openPage"),url:d().nullish()}),T({type:$("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),$I=ir({id:"openai.web_search_preview",inputSchema:xI,outputSchema:EI}),zc=Yi(()=>oe([d(),j(),fe(),qs(),q(zc),ge(d(),zc)])),RI=be(()=>we(T({serverLabel:d(),allowedTools:oe([q(d()),T({readOnly:fe().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ge(d(),d()).optional(),requireApproval:oe([_e(["always","never"]),T({never:T({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),PI=be(()=>we(T({}))),NI=be(()=>we(T({type:$("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:oe([d(),zc]).optional()}))),MI=ir({id:"openai.mcp",inputSchema:PI,outputSchema:NI}),OI=e=>MI(e),AI={applyPatch:nI,codeInterpreter:lI,fileSearch:dI,imageGeneration:gI,localShell:yI,shell:wI,webSearchPreview:$I,webSearch:SI,mcp:OI};function b2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,i=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-i,cacheRead:i,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}function k2(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function qI({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var u,m,p,f,g,v,y,w,_,h,S,k,C;const b=[],E=[],I=new Set;for(const{role:L,content:M}of e)switch(L){case"system":{switch(r){case"system":{b.push({role:"system",content:M});break}case"developer":{b.push({role:"developer",content:M});break}case"remove":{E.push({type:"other",message:"system messages are removed for this model"});break}default:{const A=r;throw new Error(`Unsupported system message mode: ${A}`)}}break}case"user":{b.push({role:"user",content:M.map((A,O)=>{var U,G,H;switch(A.type){case"text":return{type:"input_text",text:A.text};case"file":if(A.mediaType.startsWith("image/")){const le=A.mediaType==="image/*"?"image/jpeg":A.mediaType;return{type:"input_image",...A.data instanceof URL?{image_url:A.data.toString()}:typeof A.data=="string"&&k2(A.data,o)?{file_id:A.data}:{image_url:`data:${le};base64,${Kn(A.data)}`},detail:(G=(U=A.providerOptions)==null?void 0:U[n])==null?void 0:G.imageDetail}}else{if(A.mediaType==="application/pdf")return A.data instanceof URL?{type:"input_file",file_url:A.data.toString()}:{type:"input_file",...typeof A.data=="string"&&k2(A.data,o)?{file_id:A.data}:{filename:(H=A.filename)!=null?H:`part-${O}.pdf`,file_data:`data:application/pdf;base64,${Kn(A.data)}`}};throw new vr({functionality:`file part media type ${A.mediaType}`})}}})});break}case"assistant":{const A={};for(const O of M)switch(O.type){case"text":{const U=(m=(u=O.providerOptions)==null?void 0:u[n])==null?void 0:m.itemId;if(a&&U!=null)break;if(s&&U!=null){b.push({type:"item_reference",id:U});break}b.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:U});break}case"tool-call":{const U=(y=(f=(p=O.providerOptions)==null?void 0:p[n])==null?void 0:f.itemId)!=null?y:(v=(g=O.providerMetadata)==null?void 0:g[n])==null?void 0:v.itemId;if(a&&U!=null)break;if(O.providerExecuted){s&&U!=null&&b.push({type:"item_reference",id:U});break}if(s&&U!=null){b.push({type:"item_reference",id:U});break}const G=t.toProviderToolName(O.toolName);if(i&&G==="local_shell"){const H=await Tt({value:O.input,schema:_2});b.push({type:"local_shell_call",call_id:O.toolCallId,id:U,action:{type:"exec",command:H.action.command,timeout_ms:H.action.timeoutMs,user:H.action.user,working_directory:H.action.workingDirectory,env:H.action.env}});break}if(l&&G==="shell"){const H=await Tt({value:O.input,schema:w2});b.push({type:"shell_call",call_id:O.toolCallId,id:U,status:"completed",action:{commands:H.action.commands,timeout_ms:H.action.timeoutMs,max_output_length:H.action.maxOutputLength}});break}if(c&&G==="apply_patch"){const H=await Tt({value:O.input,schema:h2});b.push({type:"apply_patch_call",call_id:H.callId,id:U,status:"completed",operation:H.operation});break}b.push({type:"function_call",call_id:O.toolCallId,name:G,arguments:JSON.stringify(O.input),id:U});break}case"tool-result":{if(O.output.type==="execution-denied"||O.output.type==="json"&&typeof O.output.value=="object"&&O.output.value!=null&&"type"in O.output.value&&O.output.value.type==="execution-denied"||a)break;const U=t.toProviderToolName(O.toolName);if(l&&U==="shell"){if(O.output.type==="json"){const G=await Tt({value:O.output.value,schema:Uc});b.push({type:"shell_call_output",call_id:O.toolCallId,output:G.output.map(H=>({stdout:H.stdout,stderr:H.stderr,outcome:H.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:H.outcome.exitCode}}))})}break}if(s){const G=(h=(_=(w=O.providerOptions)==null?void 0:w[n])==null?void 0:_.itemId)!=null?h:O.toolCallId;b.push({type:"item_reference",id:G})}else E.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const U=await Pr({provider:n,providerOptions:O.providerOptions,schema:LI}),G=U?.itemId;if(a&&G!=null)break;if(G!=null){const H=A[G];if(s)H===void 0&&(b.push({type:"item_reference",id:G}),A[G]={type:"reasoning",id:G,summary:[]});else{const le=[];O.text.length>0?le.push({type:"summary_text",text:O.text}):H!==void 0&&E.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),H===void 0?(A[G]={type:"reasoning",id:G,encrypted_content:U?.reasoningEncryptedContent,summary:le},b.push(A[G])):(H.summary.push(...le),U?.reasoningEncryptedContent!=null&&(H.encrypted_content=U.reasoningEncryptedContent))}}else E.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(O)}.`});break}}break}case"tool":{for(const A of M){if(A.type==="tool-approval-response"){const H=A;if(I.has(H.approvalId))continue;I.add(H.approvalId),s&&b.push({type:"item_reference",id:H.approvalId}),b.push({type:"mcp_approval_response",approval_request_id:H.approvalId,approve:H.approved});continue}const O=A.output;if(O.type==="execution-denied"&&((k=(S=O.providerOptions)==null?void 0:S.openai)==null?void 0:k.approvalId))continue;const U=t.toProviderToolName(A.toolName);if(i&&U==="local_shell"&&O.type==="json"){const H=await Tt({value:O.value,schema:v2});b.push({type:"local_shell_call_output",call_id:A.toolCallId,output:H.output});continue}if(l&&U==="shell"&&O.type==="json"){const H=await Tt({value:O.value,schema:Uc});b.push({type:"shell_call_output",call_id:A.toolCallId,output:H.output.map(le=>({stdout:le.stdout,stderr:le.stderr,outcome:le.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:le.outcome.exitCode}}))});continue}if(c&&A.toolName==="apply_patch"&&O.type==="json"){const H=await Tt({value:O.value,schema:m2});b.push({type:"apply_patch_call_output",call_id:A.toolCallId,status:H.status,output:H.output});continue}let G;switch(O.type){case"text":case"error-text":G=O.value;break;case"execution-denied":G=(C=O.reason)!=null?C:"Tool execution denied.";break;case"json":case"error-json":G=JSON.stringify(O.value);break;case"content":G=O.value.map(H=>{var le;switch(H.type){case"text":return{type:"input_text",text:H.text};case"image-data":return{type:"input_image",image_url:`data:${H.mediaType};base64,${H.data}`};case"image-url":return{type:"input_image",image_url:H.url};case"file-data":return{type:"input_file",filename:(le=H.filename)!=null?le:"data",file_data:`data:${H.mediaType};base64,${H.data}`};default:{E.push({type:"other",message:`unsupported tool content part type: ${H.type}`});return}}}).filter(V3);break}b.push({type:"function_call_output",call_id:A.toolCallId,output:G})}break}default:{const A=L;throw new Error(`Unsupported role: ${A}`)}}return{input:b,warnings:E}}var LI=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function C2({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var jI=be(()=>we(oe([T({type:$("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish()}),T({type:_e(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:$("response.created"),response:T({id:d(),created_at:j(),model:d(),service_tier:d().nullish()})}),T({type:$("response.output_item.added"),output_index:j(),item:De("type",[T({type:$("message"),id:d()}),T({type:$("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:$("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),T({type:$("web_search_call"),id:d(),status:d()}),T({type:$("computer_call"),id:d(),status:d()}),T({type:$("file_search_call"),id:d()}),T({type:$("image_generation_call"),id:d()}),T({type:$("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(De("type",[T({type:$("logs"),logs:d()}),T({type:$("image"),url:d()})])).nullable(),status:d()}),T({type:$("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),T({type:$("mcp_list_tools"),id:d()}),T({type:$("mcp_approval_request"),id:d()}),T({type:$("apply_patch_call"),id:d(),call_id:d(),status:_e(["in_progress","completed"]),operation:De("type",[T({type:$("create_file"),path:d(),diff:d()}),T({type:$("delete_file"),path:d()}),T({type:$("update_file"),path:d(),diff:d()})])}),T({type:$("shell_call"),id:d(),call_id:d(),status:_e(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:$("shell_call_output"),id:d(),call_id:d(),status:_e(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:De("type",[T({type:$("timeout")}),T({type:$("exit"),exit_code:j()})])}))})])}),T({type:$("response.output_item.done"),output_index:j(),item:De("type",[T({type:$("message"),id:d()}),T({type:$("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:$("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:$("completed")}),T({type:$("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(De("type",[T({type:$("logs"),logs:d()}),T({type:$("image"),url:d()})])).nullable()}),T({type:$("image_generation_call"),id:d(),result:d()}),T({type:$("web_search_call"),id:d(),status:d(),action:De("type",[T({type:$("search"),query:d().nullish(),sources:q(De("type",[T({type:$("url"),url:d()}),T({type:$("api"),name:d()})])).nullish()}),T({type:$("open_page"),url:d().nullish()}),T({type:$("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:$("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:ge(d(),oe([d(),j(),fe()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),T({type:$("local_shell_call"),id:d(),call_id:d(),action:T({type:$("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ge(d(),d()).optional()})}),T({type:$("computer_call"),id:d(),status:$("completed")}),T({type:$("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:$("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:vt(),annotations:ge(d(),$e()).optional()})),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:$("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:$("apply_patch_call"),id:d(),call_id:d(),status:_e(["in_progress","completed"]),operation:De("type",[T({type:$("create_file"),path:d(),diff:d()}),T({type:$("delete_file"),path:d()}),T({type:$("update_file"),path:d(),diff:d()})])}),T({type:$("shell_call"),id:d(),call_id:d(),status:_e(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:$("shell_call_output"),id:d(),call_id:d(),status:_e(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:De("type",[T({type:$("timeout")}),T({type:$("exit"),exit_code:j()})])}))})])}),T({type:$("response.function_call_arguments.delta"),item_id:d(),output_index:j(),delta:d()}),T({type:$("response.image_generation_call.partial_image"),item_id:d(),output_index:j(),partial_image_b64:d()}),T({type:$("response.code_interpreter_call_code.delta"),item_id:d(),output_index:j(),delta:d()}),T({type:$("response.code_interpreter_call_code.done"),item_id:d(),output_index:j(),code:d()}),T({type:$("response.output_text.annotation.added"),annotation:De("type",[T({type:$("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),T({type:$("file_citation"),file_id:d(),filename:d(),index:j()}),T({type:$("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),T({type:$("file_path"),file_id:d(),index:j()})])}),T({type:$("response.reasoning_summary_part.added"),item_id:d(),summary_index:j()}),T({type:$("response.reasoning_summary_text.delta"),item_id:d(),summary_index:j(),delta:d()}),T({type:$("response.reasoning_summary_part.done"),item_id:d(),summary_index:j()}),T({type:$("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:j(),delta:d(),obfuscation:d().nullish()}),T({type:$("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:j(),diff:d()}),T({type:$("error"),sequence_number:j(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),DI=be(()=>we(T({id:d().optional(),created_at:j().optional(),error:T({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(De("type",[T({type:$("message"),role:$("assistant"),id:d(),content:q(T({type:$("output_text"),text:d(),logprobs:q(T({token:d(),logprob:j(),top_logprobs:q(T({token:d(),logprob:j()}))})).nullish(),annotations:q(De("type",[T({type:$("url_citation"),start_index:j(),end_index:j(),url:d(),title:d()}),T({type:$("file_citation"),file_id:d(),filename:d(),index:j()}),T({type:$("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:j(),end_index:j()}),T({type:$("file_path"),file_id:d(),index:j()})]))}))}),T({type:$("web_search_call"),id:d(),status:d(),action:De("type",[T({type:$("search"),query:d().nullish(),sources:q(De("type",[T({type:$("url"),url:d()}),T({type:$("api"),name:d()})])).nullish()}),T({type:$("open_page"),url:d().nullish()}),T({type:$("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:$("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:ge(d(),oe([d(),j(),fe()])),file_id:d(),filename:d(),score:j(),text:d()})).nullish()}),T({type:$("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(De("type",[T({type:$("logs"),logs:d()}),T({type:$("image"),url:d()})])).nullable()}),T({type:$("image_generation_call"),id:d(),result:d()}),T({type:$("local_shell_call"),id:d(),call_id:d(),action:T({type:$("exec"),command:q(d()),timeout_ms:j().optional(),user:d().optional(),working_directory:d().optional(),env:ge(d(),d()).optional()})}),T({type:$("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),T({type:$("computer_call"),id:d(),status:d().optional()}),T({type:$("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(T({type:$("summary_text"),text:d()}))}),T({type:$("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:$("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:vt(),annotations:ge(d(),$e()).optional()})),error:oe([d(),T({type:d().optional(),code:oe([j(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:$("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:$("apply_patch_call"),id:d(),call_id:d(),status:_e(["in_progress","completed"]),operation:De("type",[T({type:$("create_file"),path:d(),diff:d()}),T({type:$("delete_file"),path:d()}),T({type:$("update_file"),path:d(),diff:d()})])}),T({type:$("shell_call"),id:d(),call_id:d(),status:_e(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:$("shell_call_output"),id:d(),call_id:d(),status:_e(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:De("type",[T({type:$("timeout")}),T({type:$("exit"),exit_code:j()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}).optional()}))),T2=20,S2=be(()=>we(T({conversation:d().nullish(),include:q(_e(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:oe([fe(),j().min(1).max(T2)]).optional(),maxToolCalls:j().nullish(),metadata:vt().nullish(),parallelToolCalls:fe().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:fe().nullish(),strictJsonSchema:fe().nullish(),textVerbosity:_e(["low","medium","high"]).nullish(),truncation:_e(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:_e(["system","developer","remove"]).optional(),forceReasoning:fe().optional()})));async function UI({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await Tt({value:s.args,schema:cI});n.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{n.push({type:"local_shell"});break}case"openai.shell":{const a=await Tt({value:s.args,schema:vI});n.push({type:"shell",...a.environment&&{environment:zI(a.environment)}});break}case"openai.apply_patch":{n.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await Tt({value:s.args,schema:II});n.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await Tt({value:s.args,schema:bI});n.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await Tt({value:s.args,schema:aI});n.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await Tt({value:s.args,schema:pI});n.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await Tt({value:s.args,schema:RI}),i=u=>({tool_names:u.toolNames}),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:i(l.never)}:void 0;n.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:r.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const s=o;throw new vr({functionality:`tool choice type: ${s}`})}}}function zI(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const r=e;return{type:"container_auto",file_ids:r.fileIds,memory_limit:r.memoryLimit,network_policy:r.networkPolicy==null?void 0:r.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:r.networkPolicy.allowedDomains,domain_secrets:r.networkPolicy.domainSecrets},skills:FI(r.skills)}}return{type:"local",skills:e.skills}}function FI(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function I2(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;a!=null&&(n[a]=s.toolCallId)}return n}var VI=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:m,responseFormat:p}){var f,g,v,y,w,_,h,S,k;const C=[],b=s2(this.modelId);o!=null&&C.push({type:"unsupported",feature:"topK"}),i!=null&&C.push({type:"unsupported",feature:"seed"}),s!=null&&C.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&C.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&C.push({type:"unsupported",feature:"stopSequences"});const E=this.config.provider.includes("azure")?"azure":"openai";let I=await Pr({provider:E,providerOptions:c,schema:S2});I==null&&E!=="openai"&&(I=await Pr({provider:"openai",providerOptions:c,schema:S2}));const L=(f=I?.forceReasoning)!=null?f:b.isReasoningModel;I?.conversation&&I?.previousResponseId&&C.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const M=N3({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:A,warnings:O}=await qI({prompt:l,toolNameMapping:M,systemMessageMode:(g=I?.systemMessageMode)!=null?g:L?"developer":b.systemMessageMode,providerOptionsName:E,fileIdPrefixes:this.config.fileIdPrefixes,store:(v=I?.store)!=null?v:!0,hasConversation:I?.conversation!=null,hasLocalShellTool:le("openai.local_shell"),hasShellTool:le("openai.shell"),hasApplyPatchTool:le("openai.apply_patch")});C.push(...O);const U=(y=I?.strictJsonSchema)!=null?y:!0;let G=I?.include;function H(W){G==null?G=[W]:G.includes(W)||(G=[...G,W])}function le(W){return u?.find(re=>re.type==="provider"&&re.id===W)!=null}const ee=typeof I?.logprobs=="number"?I?.logprobs:I?.logprobs===!0?T2:void 0;ee&&H("message.output_text.logprobs");const he=(w=u?.find(W=>W.type==="provider"&&(W.id==="openai.web_search"||W.id==="openai.web_search_preview")))==null?void 0:w.name;he&&H("web_search_call.action.sources"),le("openai.code_interpreter")&&H("code_interpreter_call.outputs");const Z=I?.store;Z===!1&&L&&H("reasoning.encrypted_content");const R={model:this.modelId,input:A,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||I?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:U,name:(_=p.name)!=null?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...I?.textVerbosity&&{verbosity:I.textVerbosity}}},conversation:I?.conversation,max_tool_calls:I?.maxToolCalls,metadata:I?.metadata,parallel_tool_calls:I?.parallelToolCalls,previous_response_id:I?.previousResponseId,store:Z,user:I?.user,instructions:I?.instructions,service_tier:I?.serviceTier,include:G,prompt_cache_key:I?.promptCacheKey,prompt_cache_retention:I?.promptCacheRetention,safety_identifier:I?.safetyIdentifier,top_logprobs:ee,truncation:I?.truncation,...L&&(I?.reasoningEffort!=null||I?.reasoningSummary!=null)&&{reasoning:{...I?.reasoningEffort!=null&&{effort:I.reasoningEffort},...I?.reasoningSummary!=null&&{summary:I.reasoningSummary}}}};L?I?.reasoningEffort==="none"&&b.supportsNonReasoningParameters||(R.temperature!=null&&(R.temperature=void 0,C.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),R.top_p!=null&&(R.top_p=void 0,C.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(I?.reasoningEffort!=null&&C.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),I?.reasoningSummary!=null&&C.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),I?.serviceTier==="flex"&&!b.supportsFlexProcessing&&(C.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete R.service_tier),I?.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(C.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete R.service_tier);const{tools:B,toolChoice:F,toolWarnings:x}=await UI({tools:u,toolChoice:m}),N=(k=(S=(h=u?.find(W=>W.type==="provider"&&W.id==="openai.shell"))==null?void 0:h.args)==null?void 0:S.environment)==null?void 0:k.type,D=N==="containerAuto"||N==="containerReference";return{webSearchToolName:he,args:{...R,tools:B,tool_choice:F},warnings:[...C,...x],store:Z,toolNameMapping:M,providerOptionsName:E,isShellProviderExecuted:D}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,m,p,f,g,v,y,w,_,h,S,k,C,b,E,I;const{args:L,warnings:M,webSearchToolName:A,toolNameMapping:O,providerOptionsName:U,isShellProviderExecuted:G}=await this.getArgs(e),H=this.config.url({path:"/responses",modelId:this.modelId}),le=I2(e.prompt),{responseHeaders:ee,value:he,rawValue:Z}=await Dt({url:H,headers:Pt(this.config.headers(),e.headers),body:L,failedResponseHandler:cr,successfulResponseHandler:Xt(DI),abortSignal:e.abortSignal,fetch:this.config.fetch});if(he.error)throw new st({message:he.error.message,url:H,requestBodyValues:L,statusCode:400,responseHeaders:ee,responseBody:Z,isRetryable:!1});const R=[],B=[];let F=!1;for(const D of he.output)switch(D.type){case"reasoning":{D.summary.length===0&&D.summary.push({type:"summary_text",text:""});for(const W of D.summary)R.push({type:"reasoning",text:W.text,providerMetadata:{[U]:{itemId:D.id,reasoningEncryptedContent:(t=D.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:O.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:O.toCustomToolName("image_generation"),result:{result:D.result}});break}case"local_shell_call":{R.push({type:"tool-call",toolCallId:D.call_id,toolName:O.toCustomToolName("local_shell"),input:JSON.stringify({action:D.action}),providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call":{R.push({type:"tool-call",toolCallId:D.call_id,toolName:O.toCustomToolName("shell"),input:JSON.stringify({action:{commands:D.action.commands}}),...G&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:D.id}}});break}case"shell_call_output":{R.push({type:"tool-result",toolCallId:D.call_id,toolName:O.toCustomToolName("shell"),result:{output:D.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="exit"?{type:"exit",exitCode:W.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const W of D.content){(n=(r=e.providerOptions)==null?void 0:r[U])!=null&&n.logprobs&&W.logprobs&&B.push(W.logprobs);const re={itemId:D.id,...W.annotations.length>0&&{annotations:W.annotations}};R.push({type:"text",text:W.text,providerMetadata:{[U]:re}});for(const se of W.annotations)se.type==="url_citation"?R.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:Ot(),url:se.url,title:se.title}):se.type==="file_citation"?R.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:Ot(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[U]:{type:se.type,fileId:se.file_id,index:se.index}}}):se.type==="container_file_citation"?R.push({type:"source",sourceType:"document",id:(p=(m=(u=this.config).generateId)==null?void 0:m.call(u))!=null?p:Ot(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[U]:{type:se.type,fileId:se.file_id,containerId:se.container_id}}}):se.type==="file_path"&&R.push({type:"source",sourceType:"document",id:(v=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?v:Ot(),mediaType:"application/octet-stream",title:se.file_id,filename:se.file_id,providerMetadata:{[U]:{type:se.type,fileId:se.file_id,index:se.index}}})}break}case"function_call":{F=!0,R.push({type:"tool-call",toolCallId:D.call_id,toolName:D.name,input:D.arguments,providerMetadata:{[U]:{itemId:D.id}}});break}case"web_search_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:O.toCustomToolName(A??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:O.toCustomToolName(A??"web_search"),result:E2(D.action)});break}case"mcp_call":{const W=D.approval_request_id!=null&&(y=le[D.approval_request_id])!=null?y:D.id,re=`mcp.${D.name}`;R.push({type:"tool-call",toolCallId:W,toolName:re,input:D.arguments,providerExecuted:!0,dynamic:!0}),R.push({type:"tool-result",toolCallId:W,toolName:re,result:{type:"call",serverLabel:D.server_label,name:D.name,arguments:D.arguments,...D.output!=null?{output:D.output}:{},...D.error!=null?{error:D.error}:{}},providerMetadata:{[U]:{itemId:D.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const W=(w=D.approval_request_id)!=null?w:D.id,re=(S=(h=(_=this.config).generateId)==null?void 0:h.call(_))!=null?S:Ot(),se=`mcp.${D.name}`;R.push({type:"tool-call",toolCallId:re,toolName:se,input:D.arguments,providerExecuted:!0,dynamic:!0}),R.push({type:"tool-approval-request",approvalId:W,toolCallId:re});break}case"computer_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:O.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:O.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:D.status||"completed"}});break}case"file_search_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:O.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:O.toCustomToolName("file_search"),result:{queries:D.queries,results:(C=(k=D.results)==null?void 0:k.map(W=>({attributes:W.attributes,fileId:W.file_id,filename:W.filename,score:W.score,text:W.text})))!=null?C:null}});break}case"code_interpreter_call":{R.push({type:"tool-call",toolCallId:D.id,toolName:O.toCustomToolName("code_interpreter"),input:JSON.stringify({code:D.code,containerId:D.container_id}),providerExecuted:!0}),R.push({type:"tool-result",toolCallId:D.id,toolName:O.toCustomToolName("code_interpreter"),result:{outputs:D.outputs}});break}case"apply_patch_call":{R.push({type:"tool-call",toolCallId:D.call_id,toolName:O.toCustomToolName("apply_patch"),input:JSON.stringify({callId:D.call_id,operation:D.operation}),providerMetadata:{[U]:{itemId:D.id}}});break}}const x={[U]:{responseId:he.id,...B.length>0?{logprobs:B}:{},...typeof he.service_tier=="string"?{serviceTier:he.service_tier}:{}}},N=he.usage;return{content:R,finishReason:{unified:C2({finishReason:(b=he.incomplete_details)==null?void 0:b.reason,hasFunctionCall:F}),raw:(I=(E=he.incomplete_details)==null?void 0:E.reason)!=null?I:void 0},usage:b2(N),request:{body:L},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:ee,body:Z},providerMetadata:x,warnings:M}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a,isShellProviderExecuted:i}=await this.getArgs(e),{responseHeaders:l,value:c}=await Dt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Pt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:cr,successfulResponseHandler:Zs(jI),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,m=I2(e.prompt),p=new Map;let f={unified:"other",raw:void 0},g;const v=[];let y=null;const w={},_=[];let h=!1;const S={};let k;return{stream:c.pipeThrough(new TransformStream({start(C){C.enqueue({type:"stream-start",warnings:r})},transform(C,b){var E,I,L,M,A,O,U,G,H,le,ee,he,Z,R,B,F,x,N,D,W,re,se,Te,z,V,K,Q,ie,ve,Qe;if(e.includeRawChunks&&b.enqueue({type:"raw",rawValue:C.rawValue}),!C.success){f={unified:"error",raw:void 0},b.enqueue({type:"error",error:C.error});return}const P=C.value;if(x2(P)){if(P.item.type==="function_call")w[P.output_index]={toolName:P.item.name,toolCallId:P.item.call_id},b.enqueue({type:"tool-input-start",id:P.item.call_id,toolName:P.item.name});else if(P.item.type==="web_search_call")w[P.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:P.item.id},b.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),b.enqueue({type:"tool-input-end",id:P.item.id}),b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(P.item.type==="computer_call")w[P.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:P.item.id},b.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if(P.item.type==="code_interpreter_call")w[P.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:P.item.id,codeInterpreter:{containerId:P.item.container_id}},b.enqueue({type:"tool-input-start",id:P.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),b.enqueue({type:"tool-input-delta",id:P.item.id,delta:`{"containerId":"${P.item.container_id}","code":"`});else if(P.item.type==="file_search_call")b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(P.item.type==="image_generation_call")b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(P.item.type==="mcp_call"||P.item.type==="mcp_list_tools"||P.item.type==="mcp_approval_request"))if(P.item.type==="apply_patch_call"){const{call_id:X,operation:Re}=P.item;if(w[P.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:X,applyPatch:{hasDiff:Re.type==="delete_file",endEmitted:Re.type==="delete_file"}},b.enqueue({type:"tool-input-start",id:X,toolName:o.toCustomToolName("apply_patch")}),Re.type==="delete_file"){const qe=JSON.stringify({callId:X,operation:Re});b.enqueue({type:"tool-input-delta",id:X,delta:qe}),b.enqueue({type:"tool-input-end",id:X})}else b.enqueue({type:"tool-input-delta",id:X,delta:`{"callId":"${Pn(X)}","operation":{"type":"${Pn(Re.type)}","path":"${Pn(Re.path)}","diff":"`})}else P.item.type==="shell_call"?w[P.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:P.item.call_id}:P.item.type==="shell_call_output"||(P.item.type==="message"?(_.splice(0,_.length),b.enqueue({type:"text-start",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id}}})):x2(P)&&P.item.type==="reasoning"&&(S[P.item.id]={encryptedContent:P.item.encrypted_content,summaryParts:{0:"active"}},b.enqueue({type:"reasoning-start",id:`${P.item.id}:0`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(E=P.item.encrypted_content)!=null?E:null}}})))}else if(BI(P)){if(P.item.type==="message")b.enqueue({type:"text-end",id:P.item.id,providerMetadata:{[a]:{itemId:P.item.id,..._.length>0&&{annotations:_}}}});else if(P.item.type==="function_call")w[P.output_index]=void 0,h=!0,b.enqueue({type:"tool-input-end",id:P.item.call_id}),b.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:P.item.name,input:P.item.arguments,providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="web_search_call")w[P.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName(n??"web_search"),result:E2(P.item.action)});else if(P.item.type==="computer_call")w[P.output_index]=void 0,b.enqueue({type:"tool-input-end",id:P.item.id}),b.enqueue({type:"tool-call",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:P.item.status||"completed"}});else if(P.item.type==="file_search_call")w[P.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:P.item.queries,results:(L=(I=P.item.results)==null?void 0:I.map(X=>({attributes:X.attributes,fileId:X.file_id,filename:X.filename,score:X.score,text:X.text})))!=null?L:null}});else if(P.item.type==="code_interpreter_call")w[P.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:P.item.outputs}});else if(P.item.type==="image_generation_call")b.enqueue({type:"tool-result",toolCallId:P.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:P.item.result}});else if(P.item.type==="mcp_call"){w[P.output_index]=void 0;const X=(M=P.item.approval_request_id)!=null?M:void 0,Re=X!=null&&(O=(A=p.get(X))!=null?A:m[X])!=null?O:P.item.id,qe=`mcp.${P.item.name}`;b.enqueue({type:"tool-call",toolCallId:Re,toolName:qe,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),b.enqueue({type:"tool-result",toolCallId:Re,toolName:qe,result:{type:"call",serverLabel:P.item.server_label,name:P.item.name,arguments:P.item.arguments,...P.item.output!=null?{output:P.item.output}:{},...P.item.error!=null?{error:P.item.error}:{}},providerMetadata:{[a]:{itemId:P.item.id}}})}else if(P.item.type==="mcp_list_tools")w[P.output_index]=void 0;else if(P.item.type==="apply_patch_call"){const X=w[P.output_index];X?.applyPatch&&!X.applyPatch.endEmitted&&P.item.operation.type!=="delete_file"&&(X.applyPatch.hasDiff||b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Pn(P.item.operation.diff)}),b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}}'}),b.enqueue({type:"tool-input-end",id:X.toolCallId}),X.applyPatch.endEmitted=!0),X&&P.item.status==="completed"&&b.enqueue({type:"tool-call",toolCallId:X.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:P.item.call_id,operation:P.item.operation}),providerMetadata:{[a]:{itemId:P.item.id}}}),w[P.output_index]=void 0}else if(P.item.type==="mcp_approval_request"){w[P.output_index]=void 0;const X=(H=(G=(U=u.config).generateId)==null?void 0:G.call(U))!=null?H:Ot(),Re=(le=P.item.approval_request_id)!=null?le:P.item.id;p.set(Re,X);const qe=`mcp.${P.item.name}`;b.enqueue({type:"tool-call",toolCallId:X,toolName:qe,input:P.item.arguments,providerExecuted:!0,dynamic:!0}),b.enqueue({type:"tool-approval-request",approvalId:Re,toolCallId:X})}else if(P.item.type==="local_shell_call")w[P.output_index]=void 0,b.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:P.item.action.command,timeoutMs:P.item.action.timeout_ms,user:P.item.action.user,workingDirectory:P.item.action.working_directory,env:P.item.action.env}}),providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="shell_call")w[P.output_index]=void 0,b.enqueue({type:"tool-call",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:P.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[a]:{itemId:P.item.id}}});else if(P.item.type==="shell_call_output")b.enqueue({type:"tool-result",toolCallId:P.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:P.item.output.map(X=>({stdout:X.stdout,stderr:X.stderr,outcome:X.outcome.type==="exit"?{type:"exit",exitCode:X.outcome.exit_code}:{type:"timeout"}}))}});else if(P.item.type==="reasoning"){const X=S[P.item.id],Re=Object.entries(X.summaryParts).filter(([qe,Vt])=>Vt==="active"||Vt==="can-conclude").map(([qe])=>qe);for(const qe of Re)b.enqueue({type:"reasoning-end",id:`${P.item.id}:${qe}`,providerMetadata:{[a]:{itemId:P.item.id,reasoningEncryptedContent:(ee=P.item.encrypted_content)!=null?ee:null}}});delete S[P.item.id]}}else if(GI(P)){const X=w[P.output_index];X!=null&&b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:P.delta})}else if(QI(P)){const X=w[P.output_index];X?.applyPatch&&(b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Pn(P.delta)}),X.applyPatch.hasDiff=!0)}else if(XI(P)){const X=w[P.output_index];X?.applyPatch&&!X.applyPatch.endEmitted&&(X.applyPatch.hasDiff||(b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Pn(P.diff)}),X.applyPatch.hasDiff=!0),b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}}'}),b.enqueue({type:"tool-input-end",id:X.toolCallId}),X.applyPatch.endEmitted=!0)}else if(WI(P))b.enqueue({type:"tool-result",toolCallId:P.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:P.partial_image_b64},preliminary:!0});else if(KI(P)){const X=w[P.output_index];X!=null&&b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:Pn(P.delta)})}else if(YI(P)){const X=w[P.output_index];X!=null&&(b.enqueue({type:"tool-input-delta",id:X.toolCallId,delta:'"}'}),b.enqueue({type:"tool-input-end",id:X.toolCallId}),b.enqueue({type:"tool-call",toolCallId:X.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:P.code,containerId:X.codeInterpreter.containerId}),providerExecuted:!0}))}else if(JI(P))y=P.response.id,b.enqueue({type:"response-metadata",id:P.response.id,timestamp:new Date(P.response.created_at*1e3),modelId:P.response.model});else if(ZI(P))b.enqueue({type:"text-delta",id:P.item_id,delta:P.delta}),(Z=(he=e.providerOptions)==null?void 0:he[a])!=null&&Z.logprobs&&P.logprobs&&v.push(P.logprobs);else if(P.type==="response.reasoning_summary_part.added"){if(P.summary_index>0){const X=S[P.item_id];X.summaryParts[P.summary_index]="active";for(const Re of Object.keys(X.summaryParts))X.summaryParts[Re]==="can-conclude"&&(b.enqueue({type:"reasoning-end",id:`${P.item_id}:${Re}`,providerMetadata:{[a]:{itemId:P.item_id}}}),X.summaryParts[Re]="concluded");b.enqueue({type:"reasoning-start",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id,reasoningEncryptedContent:(B=(R=S[P.item_id])==null?void 0:R.encryptedContent)!=null?B:null}}})}}else P.type==="response.reasoning_summary_text.delta"?b.enqueue({type:"reasoning-delta",id:`${P.item_id}:${P.summary_index}`,delta:P.delta,providerMetadata:{[a]:{itemId:P.item_id}}}):P.type==="response.reasoning_summary_part.done"?s?(b.enqueue({type:"reasoning-end",id:`${P.item_id}:${P.summary_index}`,providerMetadata:{[a]:{itemId:P.item_id}}}),S[P.item_id].summaryParts[P.summary_index]="concluded"):S[P.item_id].summaryParts[P.summary_index]="can-conclude":HI(P)?(f={unified:C2({finishReason:(F=P.response.incomplete_details)==null?void 0:F.reason,hasFunctionCall:h}),raw:(N=(x=P.response.incomplete_details)==null?void 0:x.reason)!=null?N:void 0},g=P.response.usage,typeof P.response.service_tier=="string"&&(k=P.response.service_tier)):e8(P)?(_.push(P.annotation),P.annotation.type==="url_citation"?b.enqueue({type:"source",sourceType:"url",id:(re=(W=(D=u.config).generateId)==null?void 0:W.call(D))!=null?re:Ot(),url:P.annotation.url,title:P.annotation.title}):P.annotation.type==="file_citation"?b.enqueue({type:"source",sourceType:"document",id:(z=(Te=(se=u.config).generateId)==null?void 0:Te.call(se))!=null?z:Ot(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}}):P.annotation.type==="container_file_citation"?b.enqueue({type:"source",sourceType:"document",id:(Q=(K=(V=u.config).generateId)==null?void 0:K.call(V))!=null?Q:Ot(),mediaType:"text/plain",title:P.annotation.filename,filename:P.annotation.filename,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,containerId:P.annotation.container_id}}}):P.annotation.type==="file_path"&&b.enqueue({type:"source",sourceType:"document",id:(Qe=(ve=(ie=u.config).generateId)==null?void 0:ve.call(ie))!=null?Qe:Ot(),mediaType:"application/octet-stream",title:P.annotation.file_id,filename:P.annotation.file_id,providerMetadata:{[a]:{type:P.annotation.type,fileId:P.annotation.file_id,index:P.annotation.index}}})):t8(P)&&b.enqueue({type:"error",error:P})},flush(C){const b={[a]:{responseId:y,...v.length>0?{logprobs:v}:{},...k!==void 0?{serviceTier:k}:{}}};C.enqueue({type:"finish",finishReason:f,usage:b2(g),providerMetadata:b})}})),request:{body:t},response:{headers:l}}}};function ZI(e){return e.type==="response.output_text.delta"}function BI(e){return e.type==="response.output_item.done"}function HI(e){return e.type==="response.completed"||e.type==="response.incomplete"}function JI(e){return e.type==="response.created"}function GI(e){return e.type==="response.function_call_arguments.delta"}function WI(e){return e.type==="response.image_generation_call.partial_image"}function KI(e){return e.type==="response.code_interpreter_call_code.delta"}function YI(e){return e.type==="response.code_interpreter_call_code.done"}function QI(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function XI(e){return e.type==="response.apply_patch_call_operation_diff.done"}function x2(e){return e.type==="response.output_item.added"}function e8(e){return e.type==="response.output_text.annotation.added"}function t8(e){return e.type==="error"}function E2(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function Pn(e){return JSON.stringify(e).slice(1,-1)}var r8=be(()=>we(T({instructions:d().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),n8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await Pr({provider:"openai",providerOptions:a,schema:r8}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const m in u){const p=u[m];p!==void 0&&(c[m]=p)}}return s&&i.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await Dt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Pt(this.config.headers(),e.headers),body:s,failedResponseHandler:cr,successfulResponseHandler:V9(),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}}}},o8=be(()=>we(T({text:d(),language:d().nullish(),duration:j().nullish(),words:q(T({word:d(),start:j(),end:j()})).nullish(),segments:q(T({id:j(),seek:j(),start:j(),end:j(),text:d(),tokens:q(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),s8=be(()=>we(T({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:q(_e(["word","segment"])).default(["segment"]).optional()}))),$2={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"},a8=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await Pr({provider:"openai",providerOptions:r,schema:s8}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Gn(e)]);s.append("model",this.modelId);const i=H3(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const m of u)s.append(`${c}[]`,String(m));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,a,i,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:m}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:g}=await Pf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Pt(this.config.headers(),e.headers),formData:u,failedResponseHandler:cr,successfulResponseHandler:Xt(o8),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in $2?$2[p.language]:void 0;return{text:p.text,segments:(i=(a=(o=p.segments)==null?void 0:o.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?a:(s=p.words)==null?void 0:s.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?i:[],language:v,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:m,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},i8="3.0.33";function R2(e={}){var t,r;const n=(t=Of(Yn({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>tn({Authorization:`Bearer ${B3({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${i8}`),a=v=>new VS(v,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),i=v=>new JS(v,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=v=>new KS(v,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=v=>new eI(v,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=v=>new a8(v,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),m=v=>new n8(v,{provider:`${o}.speech`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),p=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return f(v)},f=v=>new VI(v,{provider:`${o}.responses`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),g=function(v){return p(v)};return g.specificationVersion="v3",g.languageModel=p,g.chat=a,g.completion=i,g.responses=f,g.embedding=l,g.embeddingModel=l,g.textEmbedding=l,g.textEmbeddingModel=l,g.image=c,g.imageModel=c,g.transcription=u,g.transcriptionModel=u,g.speech=m,g.speechModel=m,g.tools=AI,g}R2();var P2="vercel.ai.error",l8=Symbol.for(P2),N2,c8=class Y_ extends Error{constructor({name:t,message:r,cause:n}){super(r),this[N2]=!0,this.name=t,this.cause=n}static isInstance(t){return Y_.hasMarker(t,P2)}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}};N2=l8;var bt=c8,M2="AI_APICallError",O2=`vercel.ai.error.${M2}`,u8=Symbol.for(O2),A2,Or=class extends bt{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:M2,message:e,cause:a}),this[A2]=!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 bt.hasMarker(e,O2)}};A2=u8;var q2="AI_EmptyResponseBodyError",L2=`vercel.ai.error.${q2}`,d8=Symbol.for(L2),j2,p8=class extends bt{constructor({message:e="Empty response body"}={}){super({name:q2,message:e}),this[j2]=!0}static isInstance(e){return bt.hasMarker(e,L2)}};j2=d8;function D2(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var U2="AI_InvalidArgumentError",z2=`vercel.ai.error.${U2}`,f8=Symbol.for(z2),F2,V2=class extends bt{constructor({message:e,cause:t,argument:r}){super({name:U2,message:e,cause:t}),this[F2]=!0,this.argument=r}static isInstance(e){return bt.hasMarker(e,z2)}};F2=f8;var Z2="AI_InvalidResponseDataError",B2=`vercel.ai.error.${Z2}`,h8=Symbol.for(B2),H2,J2=class extends bt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Z2,message:t}),this[H2]=!0,this.data=e}static isInstance(e){return bt.hasMarker(e,B2)}};H2=h8;var G2="AI_JSONParseError",W2=`vercel.ai.error.${G2}`,m8=Symbol.for(W2),K2,ba=class extends bt{constructor({text:e,cause:t}){super({name:G2,message:`JSON parsing failed: Text: ${e}.
80
+ Error message: ${D2(t)}`,cause:t}),this[K2]=!0,this.text=e}static isInstance(e){return bt.hasMarker(e,W2)}};K2=m8;var Y2="AI_LoadAPIKeyError",Q2=`vercel.ai.error.${Y2}`,g8=Symbol.for(Q2),X2,ka=class extends bt{constructor({message:e}){super({name:Y2,message:e}),this[X2]=!0}static isInstance(e){return bt.hasMarker(e,Q2)}};X2=g8;var eg="AI_NoSuchModelError",tg=`vercel.ai.error.${eg}`,y8=Symbol.for(tg),rg,ng=class extends bt{constructor({errorName:e=eg,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[rg]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return bt.hasMarker(e,tg)}};rg=y8;var og="AI_TypeValidationError",sg=`vercel.ai.error.${og}`,_8=Symbol.for(sg),ag,v8=class Yu extends bt{constructor({value:t,cause:r}){super({name:og,message:`Type validation failed: Value: ${JSON.stringify(t)}.
81
+ Error message: ${D2(r)}`,cause:r}),this[ag]=!0,this.value=t}static isInstance(t){return bt.hasMarker(t,sg)}static wrap({value:t,cause:r}){return Yu.isInstance(r)&&r.value===t?r:new Yu({value:t,cause:r})}};ag=_8;var rs=v8,ig="AI_UnsupportedFunctionalityError",lg=`vercel.ai.error.${ig}`,w8=Symbol.for(lg),cg,ug=class extends bt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:ig,message:t}),this[cg]=!0,this.functionality=e}static isInstance(e){return bt.hasMarker(e,lg)}};cg=w8;function dg(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Ca(e){return Object.fromEntries([...e.headers])}var b8=({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 V2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Ta=b8();function Fc(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var k8=["fetch failed","failed to fetch"];function C8({error:e,url:t,requestBodyValues:r}){if(Fc(e))return e;if(e instanceof TypeError&&k8.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Or({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function T8(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 S8(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 pg(e,...t){const r=new Headers(S8(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var I8="3.0.18";function x8({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new ka({message:`${n} API key must be a string.`});if(typeof process>"u")throw new ka({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 ka({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ka({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var E8=/"__proto__"\s*:/,$8=/"constructor"\s*:/;function fg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||E8.test(e)===!1&&$8.test(e)===!1?t:R8(t)}function R8(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 Vc(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return fg(e)}try{return fg(e)}finally{Error.stackTraceLimit=t}}var Zc=Symbol.for("vercel.ai.validator");function P8(e){return{[Zc]:!0,validate:e}}function N8(e){return typeof e=="object"&&e!==null&&Zc in e&&e[Zc]===!0&&"validate"in e}function M8(e){return N8(e)?e:typeof e=="function"?e():O8(e)}function O8(e){return P8(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new rs({value:t,cause:r.issues})}})}async function A8({value:e,schema:t}){const r=await ns({value:e,schema:t});if(!r.success)throw rs.wrap({value:e,cause:r.error});return r.value}async function ns({value:e,schema:t}){const r=M8(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:rs.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:rs.wrap({value:e,cause:n}),rawValue:e}}}async function q8({text:e,schema:t}){try{const r=Vc(e);return t==null?r:A8({value:r,schema:t})}catch(r){throw ba.isInstance(r)||rs.isInstance(r)?r:new ba({text:e,cause:r})}}async function hg({text:e,schema:t}){try{const r=Vc(e);return t==null?{success:!0,value:r,rawValue:r}:await ns({value:r,schema:t})}catch(r){return{success:!1,error:ba.isInstance(r)?r:new ba({text:e,cause:r}),rawValue:void 0}}}function mg(e){try{return Vc(e),!0}catch{return!1}}function L8({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await hg({text:r,schema:t}))}}))}async function gg({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await ns({value:t[e],schema:r});if(!n.success)throw new V2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var j8=()=>globalThis.fetch,yg=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>D8({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),D8=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=j8()})=>{try{const i=await a(e,{method:"POST",headers:pg(t,`ai-sdk/provider-utils/${I8}`,T8()),body:r.content,signal:s}),l=Ca(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Fc(u)||Or.isInstance(u)?u:new Or({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&&(Fc(c)||Or.isInstance(c))?c:new Or({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw C8({error:i,url:e,requestBodyValues:r.values})}},U8=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Ca(n);if(a.trim()==="")return{responseHeaders:i,value:new Or({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await q8({text:a,schema:e});return{responseHeaders:i,value:new Or({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 Or({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},z8=e=>async({response:t})=>{const r=Ca(t);if(t.body==null)throw new p8({});return{responseHeaders:r,value:L8({stream:t.body,schema:e})}},F8=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await hg({text:o,schema:e}),a=Ca(t);if(!s.success)throw new Or({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:V8}=globalThis;function Z8(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return V8(t)}function B8(e){return e instanceof Uint8Array?Z8(e):e}function H8(e){return e?.replace(/\/$/,"")}function os(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function J8(e){const t=[];for(const{role:r,content:n,...o}of e){const s=os({...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,...os(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=os(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,${B8(a.data)}`},...i}}else throw new ug({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=os(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=os(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 _g({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 vg(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 Bc=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),G8=T({error:T({message:d(),type:d().nullish(),param:vt().nullish(),code:oe([d(),j()]).nullish()})}),W8={errorSchema:G8,errorToMessage:e=>e.error.message};function K8({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 ug({functionality:`tool choice type: ${s}`})}}}var Y8=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:W8;this.chunkSchema=X8(o.errorSchema),this.failedResponseHandler=U8(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:m,tools:p}){var f,g,v,y;const w=[],_=Object.assign((f=await gg({provider:"openai-compatible",providerOptions:i,schema:Bc}))!=null?f:{},(g=await gg({provider:this.providerOptionsName,providerOptions:i,schema:Bc}))!=null?g:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:h,toolChoice:S,toolWarnings:k}=K8({tools:p,toolChoice:m});return{args:{model:this.modelId,user:_.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([C])=>!Object.keys(Bc.shape).includes(C))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:J8(e),tools:h,tool_choice:S},warnings:[...w,...k]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,m,p,f,g,v,y,w;const{args:_,warnings:h}=await this.getArgs({...e}),S=JSON.stringify(_),{responseHeaders:k,value:C,rawValue:b}=await yg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dg(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:F8(Q8),abortSignal:e.abortSignal,fetch:this.config.fetch}),E=C.choices[0],I=[],L=E.message.content;L!=null&&L.length>0&&I.push({type:"text",text:L});const M=(t=E.message.reasoning_content)!=null?t:E.message.reasoning;if(M!=null&&M.length>0&&I.push({type:"reasoning",text:M}),E.message.tool_calls!=null)for(const U of E.message.tool_calls)I.push({type:"tool-call",toolCallId:(r=U.id)!=null?r:Ta(),toolName:U.function.name,input:U.function.arguments});const A={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:b}))},O=(s=C.usage)==null?void 0:s.completion_tokens_details;return O?.accepted_prediction_tokens!=null&&(A[this.providerOptionsName].acceptedPredictionTokens=O?.accepted_prediction_tokens),O?.rejected_prediction_tokens!=null&&(A[this.providerOptionsName].rejectedPredictionTokens=O?.rejected_prediction_tokens),{content:I,finishReason:vg(E.finish_reason),usage:{inputTokens:(i=(a=C.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=C.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(m=(u=C.usage)==null?void 0:u.total_tokens)!=null?m:void 0,reasoningTokens:(g=(f=(p=C.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(y=(v=C.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:A,request:{body:S},response:{..._g(C),headers:k,body:b},warnings:h}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await yg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dg(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:z8(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let m=!0;const p=this.providerOptionsName;let f=!1,g=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,y){var w,_,h,S,k,C,b,E,I,L,M,A,O;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",y.enqueue({type:"error",error:v.error});return}const U=v.value;if(s?.processChunk(v.rawValue),"error"in U){c="error",y.enqueue({type:"error",error:U.error.message});return}if(m&&(m=!1,y.enqueue({type:"response-metadata",..._g(U)})),U.usage!=null){const{prompt_tokens:ee,completion_tokens:he,total_tokens:Z,prompt_tokens_details:R,completion_tokens_details:B}=U.usage;u.promptTokens=ee??void 0,u.completionTokens=he??void 0,u.totalTokens=Z??void 0,B?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=B?.reasoning_tokens),B?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=B?.rejected_prediction_tokens),R?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=R?.cached_tokens)}const G=U.choices[0];if(G?.finish_reason!=null&&(c=vg(G.finish_reason)),G?.delta==null)return;const H=G.delta,le=(w=H.reasoning_content)!=null?w:H.reasoning;if(le&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:le})),H.content&&(g||(y.enqueue({type:"text-start",id:"txt-0"}),g=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:H.content})),H.tool_calls!=null)for(const ee of H.tool_calls){const he=ee.index;if(l[he]==null){if(ee.id==null)throw new J2({data:ee,message:"Expected 'id' to be a string."});if(((_=ee.function)==null?void 0:_.name)==null)throw new J2({data:ee,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:ee.id,toolName:ee.function.name}),l[he]={id:ee.id,type:"function",function:{name:ee.function.name,arguments:(h=ee.function.arguments)!=null?h:""},hasFinished:!1};const R=l[he];((S=R.function)==null?void 0:S.name)!=null&&((k=R.function)==null?void 0:k.arguments)!=null&&(R.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:R.id,delta:R.function.arguments}),mg(R.function.arguments)&&(y.enqueue({type:"tool-input-end",id:R.id}),y.enqueue({type:"tool-call",toolCallId:(C=R.id)!=null?C:Ta(),toolName:R.function.name,input:R.function.arguments}),R.hasFinished=!0));continue}const Z=l[he];Z.hasFinished||(((b=ee.function)==null?void 0:b.arguments)!=null&&(Z.function.arguments+=(I=(E=ee.function)==null?void 0:E.arguments)!=null?I:""),y.enqueue({type:"tool-input-delta",id:Z.id,delta:(L=ee.function.arguments)!=null?L:""}),((M=Z.function)==null?void 0:M.name)!=null&&((A=Z.function)==null?void 0:A.arguments)!=null&&mg(Z.function.arguments)&&(y.enqueue({type:"tool-input-end",id:Z.id}),y.enqueue({type:"tool-call",toolCallId:(O=Z.id)!=null?O:Ta(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}},flush(v){var y,w,_,h,S,k;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const b of l.filter(E=>!E.hasFinished))v.enqueue({type:"tool-input-end",id:b.id}),v.enqueue({type:"tool-call",toolCallId:(y=b.id)!=null?y:Ta(),toolName:b.function.name,input:b.function.arguments});const C={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(C[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(C[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(h=u.totalTokens)!=null?h:void 0,reasoningTokens:(S=u.completionTokensDetails.reasoningTokens)!=null?S:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:C})}})),request:{body:o},response:{headers:a}}}},wg=T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),Q8=T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({message:T({role:$("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({id:d().nullish(),function:T({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:wg}),X8=e=>oe([T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({delta:T({role:_e(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({index:j(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:wg}),e]);T({echo:fe().optional(),logitBias:ge(d(),j()).optional(),suffix:d().optional(),user:d().optional()});var ex=T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});T({id:d().nullish(),created:j().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d()})),usage:ex.nullish()}),T({dimensions:j().optional(),user:d().optional()}),T({data:q(T({embedding:q(j())})),usage:T({prompt_tokens:j()}).nullish(),providerMetadata:ge(d(),ge(d(),vt())).optional()}),T({data:q(T({b64_json:d()}))});var bg=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}}},tx={extractMetadata:async({parsedBody:e})=>{const t=await ns({value:e,schema:rx});return!t.success||t.value.usage==null?void 0:bg(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await ns({value:t,schema:nx});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:()=>bg(e)}}},kg=T({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),rx=T({usage:kg.nullish()}),nx=T({choices:q(T({finish_reason:d().nullish()})).nullish(),usage:kg.nullish()}),ox="1.0.30";function Cg(e={}){var t;const r=H8((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>pg({Authorization:`Bearer ${x8({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${ox}`);class o extends Y8{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:tx}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new ng({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new ng({modelId:i,modelType:"imageModel"})},a}Cg();const sx=(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})},ax=(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 ix{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=ax("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=En.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];sx("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 Sa(e){return!!e._zod}function on(e,t){return Sa(e)?Wd(e,t):e.safeParse(t)}function Tg(e){if(!e)return;let t;if(Sa(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function lx(e){if(Sa(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 Nn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Sg(e){const r=Tg(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=lx(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ig(e,t){const r=on(e,t);if(!r.success)throw r.error;return r.data}const cx=6e4;class ux{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(Xl,r=>{this._oncancel(r)}),this.setNotificationHandler(tc,r=>{this._onprogress(r)}),this.setRequestHandler(ec,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(rc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke(Ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(oc,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(i.type==="response"||i.type==="error"){const l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{const m=l,p=new ke(m.error.code,m.error.message,m.error.data);u(p)}else{const m=i.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new ke(Ee.InvalidParams,`Task not found: ${s}`);if(!Nn(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Nn(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[xn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(sc,async(r,n)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new ke(Ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ic,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ke(Ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nn(o.status))throw new ke(Ee.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ke(Ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ke?o:new ke(Ee.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),ke.fromError(Ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),Go(s)||jC(s)?this._onresponse(s):Kl(s)?this._onrequest(s,a):LC(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=ke.fromError(Ee.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[xn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:Ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):o?.send(u).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=qC(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const m={relatedRequestId:t.id};s&&(m.relatedTask={taskId:s}),await this.notification(u,m)},sendRequest:async(u,m,p)=>{const f={...p,relatedRequestId:t.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});const g=f.relatedTask?.taskId??s;return g&&l&&await l.updateTaskStatus(g,"input_required"),await this.request(u,m,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const m={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)},async u=>{if(a.signal.aborted)return;const m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:Ee.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Go(t))n(t);else{const a=new ke(t.error.code,t.error.message,t.error.data);n(a)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Go(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),Go(t))o(t);else{const a=ke.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof ke?a:new ke(Ee.InternalError,String(a))}}return}let s;try{const a=await this.request(t,Xo,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ke(Ee.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},Nn(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new ke(Ee.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new ke(Ee.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof ke?a:new ke(Ee.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const m=_=>{u(_)};if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(_){m(_);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(f.params={...f.params,task:i}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[xn]:l}});const g=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));const h=_ instanceof ke?_:new ke(Ee.RequestTimeout,String(_));u(h)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{const h=on(r,_.result);h.success?c(h.data):u(h.error)}catch(h){u(h)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});const v=n?.timeout??cx,y=()=>g(ke.fromError(Ee.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(p,v,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const _=h=>{const S=this._responseHandlers.get(p);S?S(h):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(h=>{this._cleanupTimeout(p),u(h)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(_=>{this._cleanupTimeout(p),u(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},nc,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},ac,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},tT,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const i={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[xn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[xn]:r.relatedTask}}}),this._transport?.send(i,r).catch(l=>this._onerror(l))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[xn]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=Sg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=Ig(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=Sg(t);this._notificationHandlers.set(n,o=>{const s=Ig(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"&&Kl(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new ke(Ee.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new ke(Ee.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ke(Ee.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new ke(Ee.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=pa.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Nn(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,a)=>{const i=await n.getTask(o,r);if(!i)throw new ke(Ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Nn(i.status))throw new ke(Ee.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=pa.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Nn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function xg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dx(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];xg(a)&&xg(s)?r[o]={...a,...s}:r[o]=s}return r}var Ia={exports:{}},Hc={},Ar={},Mn={},Jc={},Gc={},Wc={},Eg;function xa(){return Eg||(Eg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((h,S)=>`${h}${S}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((h,S)=>(S instanceof r&&(h[S.str]=(h[S.str]||0)+1),h),{})}}e._Code=n,e.nil=new n("");function o(w,..._){const h=[w[0]];let S=0;for(;S<_.length;)i(h,_[S]),h.push(w[++S]);return new n(h)}e._=o;const s=new n("+");function a(w,..._){const h=[f(w[0])];let S=0;for(;S<_.length;)h.push(s),i(h,_[S]),h.push(s,f(w[++S]));return l(h),new n(h)}e.str=a;function i(w,_){_ instanceof n?w.push(..._._items):_ instanceof r?w.push(_):w.push(m(_))}e.addCodeArg=i;function l(w){let _=1;for(;_<w.length-1;){if(w[_]===s){const h=c(w[_-1],w[_+1]);if(h!==void 0){w.splice(_-1,3,h);continue}w[_++]="+"}_++}}function c(w,_){if(_==='""')return w;if(w==='""')return _;if(typeof w=="string")return _ instanceof r||w[w.length-1]!=='"'?void 0:typeof _!="string"?`${w.slice(0,-1)}${_}"`:_[0]==='"'?w.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(w instanceof r))return`"${w}${_.slice(1)}`}function u(w,_){return _.emptyStr()?w:w.emptyStr()?_:a`${w}${_}`}e.strConcat=u;function m(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:f(Array.isArray(w)?w.join(","):w)}function p(w){return new n(f(w))}e.stringify=p;function f(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function g(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=g;function v(w){if(typeof w=="string"&&e.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}e.getEsmExportName=v;function y(w){return new n(w.toString())}e.regexpCode=y})(Wc)),Wc}var Kc={},$g;function Rg(){return $g||($g=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=xa();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,m;if(!((m=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||m===void 0)&&m.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:m}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${m}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var m;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:f}=p,g=(m=u.key)!==null&&m!==void 0?m:u.ref;let v=this._values[f];if(v){const _=v.get(g);if(_)return _}else v=this._values[f]=new Map;v.set(g,p);const y=this._scope[f]||(this._scope[f]=[]),w=y.length;return y[w]=u.ref,p.setValue(u,{property:f,itemIndex:w}),p}getValue(c,u){const m=this._values[c];if(m)return m.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,m=>{if(m.scopePath===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return(0,t._)`${c}${m.scopePath}`})}scopeCode(c=this._values,u,m){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,m)}_reduceValues(c,u,m={},p){let f=t.nil;for(const g in c){const v=c[g];if(!v)continue;const y=m[g]=m[g]||new Map;v.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let _=u(w);if(_){const h=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${h} ${w} = ${_};${this.opts._n}`}else if(_=p?.(w))f=(0,t._)`${f}${_}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return f}}e.ValueScope=i})(Kc)),Kc}var Pg;function Ne(){return Pg||(Pg=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=xa(),r=Rg();var n=xa();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=Rg();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(x,N){return this}}class a extends s{constructor(x,N,D){super(),this.varKind=x,this.name=N,this.rhs=D}render({es5:x,_n:N}){const D=x?r.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${D} ${this.name}${W};`+N}optimizeNames(x,N){if(x[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,x,N)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(x,N,D){super(),this.lhs=x,this.rhs=N,this.sideEffects=D}render({_n:x}){return`${this.lhs} = ${this.rhs};`+x}optimizeNames(x,N){if(!(this.lhs instanceof t.Name&&!x[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,x,N),this}get names(){const x=this.lhs instanceof t.Name?{}:{...this.lhs.names};return O(x,this.rhs)}}class l extends i{constructor(x,N,D,W){super(x,D,W),this.op=N}render({_n:x}){return`${this.lhs} ${this.op}= ${this.rhs};`+x}}class c extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`${this.label}:`+x}}class u extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`break${this.label?` ${this.label}`:""};`+x}}class m extends s{constructor(x){super(),this.error=x}render({_n:x}){return`throw ${this.error};`+x}get names(){return this.error.names}}class p extends s{constructor(x){super(),this.code=x}render({_n:x}){return`${this.code};`+x}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(x,N){return this.code=U(this.code,x,N),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(x=[]){super(),this.nodes=x}render(x){return this.nodes.reduce((N,D)=>N+D.render(x),"")}optimizeNodes(){const{nodes:x}=this;let N=x.length;for(;N--;){const D=x[N].optimizeNodes();Array.isArray(D)?x.splice(N,1,...D):D?x[N]=D:x.splice(N,1)}return x.length>0?this:void 0}optimizeNames(x,N){const{nodes:D}=this;let W=D.length;for(;W--;){const re=D[W];re.optimizeNames(x,N)||(G(x,re.names),D.splice(W,1))}return D.length>0?this:void 0}get names(){return this.nodes.reduce((x,N)=>A(x,N.names),{})}}class g extends f{render(x){return"{"+x._n+super.render(x)+"}"+x._n}}class v extends f{}class y extends g{}y.kind="else";class w extends g{constructor(x,N){super(N),this.condition=x}render(x){let N=`if(${this.condition})`+super.render(x);return this.else&&(N+="else "+this.else.render(x)),N}optimizeNodes(){super.optimizeNodes();const x=this.condition;if(x===!0)return this.nodes;let N=this.else;if(N){const D=N.optimizeNodes();N=this.else=Array.isArray(D)?new y(D):D}if(N)return x===!1?N instanceof w?N:N.nodes:this.nodes.length?this:new w(H(x),N instanceof w?[N]:N.nodes);if(!(x===!1||!this.nodes.length))return this}optimizeNames(x,N){var D;if(this.else=(D=this.else)===null||D===void 0?void 0:D.optimizeNames(x,N),!!(super.optimizeNames(x,N)||this.else))return this.condition=U(this.condition,x,N),this}get names(){const x=super.names;return O(x,this.condition),this.else&&A(x,this.else.names),x}}w.kind="if";class _ extends g{}_.kind="for";class h extends _{constructor(x){super(),this.iteration=x}render(x){return`for(${this.iteration})`+super.render(x)}optimizeNames(x,N){if(super.optimizeNames(x,N))return this.iteration=U(this.iteration,x,N),this}get names(){return A(super.names,this.iteration.names)}}class S extends _{constructor(x,N,D,W){super(),this.varKind=x,this.name=N,this.from=D,this.to=W}render(x){const N=x.es5?r.varKinds.var:this.varKind,{name:D,from:W,to:re}=this;return`for(${N} ${D}=${W}; ${D}<${re}; ${D}++)`+super.render(x)}get names(){const x=O(super.names,this.from);return O(x,this.to)}}class k extends _{constructor(x,N,D,W){super(),this.loop=x,this.varKind=N,this.name=D,this.iterable=W}render(x){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(x)}optimizeNames(x,N){if(super.optimizeNames(x,N))return this.iterable=U(this.iterable,x,N),this}get names(){return A(super.names,this.iterable.names)}}class C extends g{constructor(x,N,D){super(),this.name=x,this.args=N,this.async=D}render(x){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(x)}}C.kind="func";class b extends f{render(x){return"return "+super.render(x)}}b.kind="return";class E extends g{render(x){let N="try"+super.render(x);return this.catch&&(N+=this.catch.render(x)),this.finally&&(N+=this.finally.render(x)),N}optimizeNodes(){var x,N;return super.optimizeNodes(),(x=this.catch)===null||x===void 0||x.optimizeNodes(),(N=this.finally)===null||N===void 0||N.optimizeNodes(),this}optimizeNames(x,N){var D,W;return super.optimizeNames(x,N),(D=this.catch)===null||D===void 0||D.optimizeNames(x,N),(W=this.finally)===null||W===void 0||W.optimizeNames(x,N),this}get names(){const x=super.names;return this.catch&&A(x,this.catch.names),this.finally&&A(x,this.finally.names),x}}class I extends g{constructor(x){super(),this.error=x}render(x){return`catch(${this.error})`+super.render(x)}}I.kind="catch";class L extends g{render(x){return"finally"+super.render(x)}}L.kind="finally";class M{constructor(x,N={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...N,_n:N.lines?`
82
+ `:""},this._extScope=x,this._scope=new r.Scope({parent:x}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(x){return this._scope.name(x)}scopeName(x){return this._extScope.name(x)}scopeValue(x,N){const D=this._extScope.value(x,N);return(this._values[D.prefix]||(this._values[D.prefix]=new Set)).add(D),D}getScopeValue(x,N){return this._extScope.getValue(x,N)}scopeRefs(x){return this._extScope.scopeRefs(x,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(x,N,D,W){const re=this._scope.toName(N);return D!==void 0&&W&&(this._constants[re.str]=D),this._leafNode(new a(x,re,D)),re}const(x,N,D){return this._def(r.varKinds.const,x,N,D)}let(x,N,D){return this._def(r.varKinds.let,x,N,D)}var(x,N,D){return this._def(r.varKinds.var,x,N,D)}assign(x,N,D){return this._leafNode(new i(x,N,D))}add(x,N){return this._leafNode(new l(x,e.operators.ADD,N))}code(x){return typeof x=="function"?x():x!==t.nil&&this._leafNode(new p(x)),this}object(...x){const N=["{"];for(const[D,W]of x)N.length>1&&N.push(","),N.push(D),(D!==W||this.opts.es5)&&(N.push(":"),(0,t.addCodeArg)(N,W));return N.push("}"),new t._Code(N)}if(x,N,D){if(this._blockNode(new w(x)),N&&D)this.code(N).else().code(D).endIf();else if(N)this.code(N).endIf();else if(D)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(x){return this._elseNode(new w(x))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(x,N){return this._blockNode(x),N&&this.code(N).endFor(),this}for(x,N){return this._for(new h(x),N)}forRange(x,N,D,W,re=this.opts.es5?r.varKinds.var:r.varKinds.let){const se=this._scope.toName(x);return this._for(new S(re,se,N,D),()=>W(se))}forOf(x,N,D,W=r.varKinds.const){const re=this._scope.toName(x);if(this.opts.es5){const se=N instanceof t.Name?N:this.var("_arr",N);return this.forRange("_i",0,(0,t._)`${se}.length`,Te=>{this.var(re,(0,t._)`${se}[${Te}]`),D(re)})}return this._for(new k("of",W,re,N),()=>D(re))}forIn(x,N,D,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,(0,t._)`Object.keys(${N})`,D);const re=this._scope.toName(x);return this._for(new k("in",W,re,N),()=>D(re))}endFor(){return this._endBlockNode(_)}label(x){return this._leafNode(new c(x))}break(x){return this._leafNode(new u(x))}return(x){const N=new b;if(this._blockNode(N),this.code(x),N.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(b)}try(x,N,D){if(!N&&!D)throw new Error('CodeGen: "try" without "catch" and "finally"');const W=new E;if(this._blockNode(W),this.code(x),N){const re=this.name("e");this._currNode=W.catch=new I(re),N(re)}return D&&(this._currNode=W.finally=new L,this.code(D)),this._endBlockNode(I,L)}throw(x){return this._leafNode(new m(x))}block(x,N){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(N),this}endBlock(x){const N=this._blockStarts.pop();if(N===void 0)throw new Error("CodeGen: not in self-balancing block");const D=this._nodes.length-N;if(D<0||x!==void 0&&D!==x)throw new Error(`CodeGen: wrong number of nodes: ${D} vs ${x} expected`);return this._nodes.length=N,this}func(x,N=t.nil,D,W){return this._blockNode(new C(x,N,D)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(C)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,N){const D=this._currNode;if(D instanceof x||N&&D instanceof N)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${N?`${x.kind}/${N.kind}`:x.kind}"`)}_elseNode(x){const N=this._currNode;if(!(N instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=N.else=x,this}get _root(){return this._nodes[0]}get _currNode(){const x=this._nodes;return x[x.length-1]}set _currNode(x){const N=this._nodes;N[N.length-1]=x}}e.CodeGen=M;function A(F,x){for(const N in x)F[N]=(F[N]||0)+(x[N]||0);return F}function O(F,x){return x instanceof t._CodeOrName?A(F,x.names):F}function U(F,x,N){if(F instanceof t.Name)return D(F);if(!W(F))return F;return new t._Code(F._items.reduce((re,se)=>(se instanceof t.Name&&(se=D(se)),se instanceof t._Code?re.push(...se._items):re.push(se),re),[]));function D(re){const se=N[re.str];return se===void 0||x[re.str]!==1?re:(delete x[re.str],se)}function W(re){return re instanceof t._Code&&re._items.some(se=>se instanceof t.Name&&x[se.str]===1&&N[se.str]!==void 0)}}function G(F,x){for(const N in x)F[N]=(F[N]||0)-(x[N]||0)}function H(F){return typeof F=="boolean"||typeof F=="number"||F===null?!F:(0,t._)`!${B(F)}`}e.not=H;const le=R(e.operators.AND);function ee(...F){return F.reduce(le)}e.and=ee;const he=R(e.operators.OR);function Z(...F){return F.reduce(he)}e.or=Z;function R(F){return(x,N)=>x===t.nil?N:N===t.nil?x:(0,t._)`${B(x)} ${F} ${B(N)}`}function B(F){return F instanceof t.Name?F:(0,t._)`(${F})`}})(Gc)),Gc}var Me={},Ng;function je(){if(Ng)return Me;Ng=1,Object.defineProperty(Me,"__esModule",{value:!0}),Me.checkStrictMode=Me.getErrorPath=Me.Type=Me.useFunc=Me.setEvaluated=Me.evaluatedPropsToName=Me.mergeEvaluated=Me.eachItem=Me.unescapeJsonPointer=Me.escapeJsonPointer=Me.escapeFragment=Me.unescapeFragment=Me.schemaRefOrVal=Me.schemaHasRulesButRef=Me.schemaHasRules=Me.checkUnknownRules=Me.alwaysValidSchema=Me.toHash=void 0;const e=Ne(),t=xa();function r(k){const C={};for(const b of k)C[b]=!0;return C}Me.toHash=r;function n(k,C){return typeof C=="boolean"?C:Object.keys(C).length===0?!0:(o(k,C),!s(C,k.self.RULES.all))}Me.alwaysValidSchema=n;function o(k,C=k.schema){const{opts:b,self:E}=k;if(!b.strictSchema||typeof C=="boolean")return;const I=E.RULES.keywords;for(const L in C)I[L]||S(k,`unknown keyword: "${L}"`)}Me.checkUnknownRules=o;function s(k,C){if(typeof k=="boolean")return!k;for(const b in k)if(C[b])return!0;return!1}Me.schemaHasRules=s;function a(k,C){if(typeof k=="boolean")return!k;for(const b in k)if(b!=="$ref"&&C.all[b])return!0;return!1}Me.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:C},b,E,I){if(!I){if(typeof b=="number"||typeof b=="boolean")return b;if(typeof b=="string")return(0,e._)`${b}`}return(0,e._)`${k}${C}${(0,e.getProperty)(E)}`}Me.schemaRefOrVal=i;function l(k){return m(decodeURIComponent(k))}Me.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}Me.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}Me.escapeJsonPointer=u;function m(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}Me.unescapeJsonPointer=m;function p(k,C){if(Array.isArray(k))for(const b of k)C(b);else C(k)}Me.eachItem=p;function f({mergeNames:k,mergeToName:C,mergeValues:b,resultToName:E}){return(I,L,M,A)=>{const O=M===void 0?L:M instanceof e.Name?(L instanceof e.Name?k(I,L,M):C(I,L,M),M):L instanceof e.Name?(C(I,M,L),L):b(L,M);return A===e.Name&&!(O instanceof e.Name)?E(I,O):O}}Me.mergeEvaluated={props:f({mergeNames:(k,C,b)=>k.if((0,e._)`${b} !== true && ${C} !== undefined`,()=>{k.if((0,e._)`${C} === true`,()=>k.assign(b,!0),()=>k.assign(b,(0,e._)`${b} || {}`).code((0,e._)`Object.assign(${b}, ${C})`))}),mergeToName:(k,C,b)=>k.if((0,e._)`${b} !== true`,()=>{C===!0?k.assign(b,!0):(k.assign(b,(0,e._)`${b} || {}`),v(k,b,C))}),mergeValues:(k,C)=>k===!0?!0:{...k,...C},resultToName:g}),items:f({mergeNames:(k,C,b)=>k.if((0,e._)`${b} !== true && ${C} !== undefined`,()=>k.assign(b,(0,e._)`${C} === true ? true : ${b} > ${C} ? ${b} : ${C}`)),mergeToName:(k,C,b)=>k.if((0,e._)`${b} !== true`,()=>k.assign(b,C===!0?!0:(0,e._)`${b} > ${C} ? ${b} : ${C}`)),mergeValues:(k,C)=>k===!0?!0:Math.max(k,C),resultToName:(k,C)=>k.var("items",C)})};function g(k,C){if(C===!0)return k.var("props",!0);const b=k.var("props",(0,e._)`{}`);return C!==void 0&&v(k,b,C),b}Me.evaluatedPropsToName=g;function v(k,C,b){Object.keys(b).forEach(E=>k.assign((0,e._)`${C}${(0,e.getProperty)(E)}`,!0))}Me.setEvaluated=v;const y={};function w(k,C){return k.scopeValue("func",{ref:C,code:y[C.code]||(y[C.code]=new t._Code(C.code))})}Me.useFunc=w;var _;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(_||(Me.Type=_={}));function h(k,C,b){if(k instanceof e.Name){const E=C===_.Num;return b?E?(0,e._)`"[" + ${k} + "]"`:(0,e._)`"['" + ${k} + "']"`:E?(0,e._)`"/" + ${k}`:(0,e._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return b?(0,e.getProperty)(k).toString():"/"+u(k)}Me.getErrorPath=h;function S(k,C,b=k.opts.strictSchema){if(b){if(C=`strict mode: ${C}`,b===!0)throw new Error(C);k.self.logger.warn(C)}}return Me.checkStrictMode=S,Me}var Ea={},Mg;function sn(){if(Mg)return Ea;Mg=1,Object.defineProperty(Ea,"__esModule",{value:!0});const e=Ne(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Ea.default=t,Ea}var Og;function $a(){return Og||(Og=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Ne(),r=je(),n=sn();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,t.str)`"${y}" keyword must be ${w} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,w=e.keywordError,_,h){const{it:S}=y,{gen:k,compositeRule:C,allErrors:b}=S,E=m(y,w,_);h??(C||b)?l(k,E):c(S,(0,t._)`[${E}]`)}e.reportError=o;function s(y,w=e.keywordError,_){const{it:h}=y,{gen:S,compositeRule:k,allErrors:C}=h,b=m(y,w,_);l(S,b),k||C||c(h,n.default.vErrors)}e.reportExtraError=s;function a(y,w){y.assign(n.default.errors,w),y.if((0,t._)`${n.default.vErrors} !== null`,()=>y.if(w,()=>y.assign((0,t._)`${n.default.vErrors}.length`,w),()=>y.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:y,keyword:w,schemaValue:_,data:h,errsCount:S,it:k}){if(S===void 0)throw new Error("ajv implementation error");const C=y.name("err");y.forRange("i",S,n.default.errors,b=>{y.const(C,(0,t._)`${n.default.vErrors}[${b}]`),y.if((0,t._)`${C}.instancePath === undefined`,()=>y.assign((0,t._)`${C}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),y.assign((0,t._)`${C}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${w}`),k.opts.verbose&&(y.assign((0,t._)`${C}.schema`,_),y.assign((0,t._)`${C}.data`,h))})}e.extendErrors=i;function l(y,w){const _=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:_,validateName:h,schemaEnv:S}=y;S.$async?_.throw((0,t._)`new ${y.ValidationError}(${w})`):(_.assign((0,t._)`${h}.errors`,w),_.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function m(y,w,_){const{createErrors:h}=y.it;return h===!1?(0,t._)`{}`:p(y,w,_)}function p(y,w,_={}){const{gen:h,it:S}=y,k=[f(S,_),g(y,_)];return v(y,w,k),h.object(...k)}function f({errorPath:y},{instancePath:w}){const _=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function g({keyword:y,it:{errSchemaPath:w}},{schemaPath:_,parentSchema:h}){let S=h?w:(0,t.str)`${w}/${y}`;return _&&(S=(0,t.str)`${S}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,S]}function v(y,{params:w,message:_},h){const{keyword:S,data:k,schemaValue:C,it:b}=y,{opts:E,propertyName:I,topSchemaRef:L,schemaPath:M}=b;h.push([u.keyword,S],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),E.messages&&h.push([u.message,typeof _=="function"?_(y):_]),E.verbose&&h.push([u.schema,C],[u.parentSchema,(0,t._)`${L}${M}`],[n.default.data,k]),I&&h.push([u.propertyName,I])}})(Jc)),Jc}var Ag;function px(){if(Ag)return Mn;Ag=1,Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.boolOrEmptySchema=Mn.topBoolOrEmptySchema=void 0;const e=$a(),t=Ne(),r=sn(),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))}Mn.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}Mn.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,m={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(m,n,void 0,l)}return Mn}var $t={},On={},qg;function Lg(){if(qg)return On;qg=1,Object.defineProperty(On,"__esModule",{value:!0}),On.getRules=On.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)}On.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 On.getRules=n,On}var qr={},jg;function Dg(){if(jg)return qr;jg=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.shouldUseRule=qr.shouldUseGroup=qr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}qr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}qr.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 qr.shouldUseRule=r,qr}var Ug;function Ra(){if(Ug)return $t;Ug=1,Object.defineProperty($t,"__esModule",{value:!0}),$t.reportTypeError=$t.checkDataTypes=$t.checkDataType=$t.coerceAndCheckDataType=$t.getJSONTypes=$t.getSchemaTypes=$t.DataType=void 0;const e=Lg(),t=Dg(),r=$a(),n=Ne(),o=je();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||($t.DataType=s={}));function a(_){const h=i(_.type);if(h.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!h.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&h.push("null")}return h}$t.getSchemaTypes=a;function i(_){const h=Array.isArray(_)?_:_?[_]:[];if(h.every(e.isJSONType))return h;throw new Error("type must be JSONType or JSONType[]: "+h.join(","))}$t.getJSONTypes=i;function l(_,h){const{gen:S,data:k,opts:C}=_,b=u(h,C.coerceTypes),E=h.length>0&&!(b.length===0&&h.length===1&&(0,t.schemaHasRulesForType)(_,h[0]));if(E){const I=g(h,k,C.strictNumbers,s.Wrong);S.if(I,()=>{b.length?m(_,h,b):y(_)})}return E}$t.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,h){return h?_.filter(S=>c.has(S)||h==="array"&&S==="array"):[]}function m(_,h,S){const{gen:k,data:C,opts:b}=_,E=k.let("dataType",(0,n._)`typeof ${C}`),I=k.let("coerced",(0,n._)`undefined`);b.coerceTypes==="array"&&k.if((0,n._)`${E} == 'object' && Array.isArray(${C}) && ${C}.length == 1`,()=>k.assign(C,(0,n._)`${C}[0]`).assign(E,(0,n._)`typeof ${C}`).if(g(h,C,b.strictNumbers),()=>k.assign(I,C))),k.if((0,n._)`${I} !== undefined`);for(const M of S)(c.has(M)||M==="array"&&b.coerceTypes==="array")&&L(M);k.else(),y(_),k.endIf(),k.if((0,n._)`${I} !== undefined`,()=>{k.assign(C,I),p(_,I)});function L(M){switch(M){case"string":k.elseIf((0,n._)`${E} == "number" || ${E} == "boolean"`).assign(I,(0,n._)`"" + ${C}`).elseIf((0,n._)`${C} === null`).assign(I,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${E} == "boolean" || ${C} === null
83
+ || (${E} == "string" && ${C} && ${C} == +${C})`).assign(I,(0,n._)`+${C}`);return;case"integer":k.elseIf((0,n._)`${E} === "boolean" || ${C} === null
84
+ || (${E} === "string" && ${C} && ${C} == +${C} && !(${C} % 1))`).assign(I,(0,n._)`+${C}`);return;case"boolean":k.elseIf((0,n._)`${C} === "false" || ${C} === 0 || ${C} === null`).assign(I,!1).elseIf((0,n._)`${C} === "true" || ${C} === 1`).assign(I,!0);return;case"null":k.elseIf((0,n._)`${C} === "" || ${C} === 0 || ${C} === false`),k.assign(I,null);return;case"array":k.elseIf((0,n._)`${E} === "string" || ${E} === "number"
85
+ || ${E} === "boolean" || ${C} === null`).assign(I,(0,n._)`[${C}]`)}}}function p({gen:_,parentData:h,parentDataProperty:S},k){_.if((0,n._)`${h} !== undefined`,()=>_.assign((0,n._)`${h}[${S}]`,k))}function f(_,h,S,k=s.Correct){const C=k===s.Correct?n.operators.EQ:n.operators.NEQ;let b;switch(_){case"null":return(0,n._)`${h} ${C} null`;case"array":b=(0,n._)`Array.isArray(${h})`;break;case"object":b=(0,n._)`${h} && typeof ${h} == "object" && !Array.isArray(${h})`;break;case"integer":b=E((0,n._)`!(${h} % 1) && !isNaN(${h})`);break;case"number":b=E();break;default:return(0,n._)`typeof ${h} ${C} ${_}`}return k===s.Correct?b:(0,n.not)(b);function E(I=n.nil){return(0,n.and)((0,n._)`typeof ${h} == "number"`,I,S?(0,n._)`isFinite(${h})`:n.nil)}}$t.checkDataType=f;function g(_,h,S,k){if(_.length===1)return f(_[0],h,S,k);let C;const b=(0,o.toHash)(_);if(b.array&&b.object){const E=(0,n._)`typeof ${h} != "object"`;C=b.null?E:(0,n._)`!${h} || ${E}`,delete b.null,delete b.array,delete b.object}else C=n.nil;b.number&&delete b.integer;for(const E in b)C=(0,n.and)(C,f(E,h,S,k));return C}$t.checkDataTypes=g;const v={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:h})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${h}}`};function y(_){const h=w(_);(0,r.reportError)(h,v)}$t.reportTypeError=y;function w(_){const{gen:h,data:S,schema:k}=_,C=(0,o.schemaRefOrVal)(_,k,"type");return{gen:h,keyword:"type",data:S,schema:k.type,schemaCode:C,schemaValue:C,parentSchema:k,params:{},it:_}}return $t}var ss={},zg;function fx(){if(zg)return ss;zg=1,Object.defineProperty(ss,"__esModule",{value:!0}),ss.assignDefaults=void 0;const e=Ne(),t=je();function r(o,s){const{properties:a,items:i}=o.schema;if(s==="object"&&a)for(const l in a)n(o,l,a[l].default);else s==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}ss.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const m=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${m}`);return}let p=(0,e._)`${m} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${m} === null || ${m} === ""`),i.if(p,(0,e._)`${m} = ${(0,e.stringify)(a)}`)}return ss}var ur={},Ze={},Fg;function dr(){if(Fg)return Ze;Fg=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.validateUnion=Ze.validateArray=Ze.usePattern=Ze.callValidateCode=Ze.schemaProperties=Ze.allSchemaProperties=Ze.noPropertyInData=Ze.propertyInData=Ze.isOwnProperty=Ze.hasPropFunc=Ze.reportMissingProp=Ze.checkMissingProp=Ze.checkReportMissingProp=void 0;const e=Ne(),t=je(),r=sn(),n=je();function o(_,h){const{gen:S,data:k,it:C}=_;S.if(u(S,k,h,C.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${h}`},!0),_.error()})}Ze.checkReportMissingProp=o;function s({gen:_,data:h,it:{opts:S}},k,C){return(0,e.or)(...k.map(b=>(0,e.and)(u(_,h,b,S.ownProperties),(0,e._)`${C} = ${b}`)))}Ze.checkMissingProp=s;function a(_,h){_.setParams({missingProperty:h},!0),_.error()}Ze.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ze.hasPropFunc=i;function l(_,h,S){return(0,e._)`${i(_)}.call(${h}, ${S})`}Ze.isOwnProperty=l;function c(_,h,S,k){const C=(0,e._)`${h}${(0,e.getProperty)(S)} !== undefined`;return k?(0,e._)`${C} && ${l(_,h,S)}`:C}Ze.propertyInData=c;function u(_,h,S,k){const C=(0,e._)`${h}${(0,e.getProperty)(S)} === undefined`;return k?(0,e.or)(C,(0,e.not)(l(_,h,S))):C}Ze.noPropertyInData=u;function m(_){return _?Object.keys(_).filter(h=>h!=="__proto__"):[]}Ze.allSchemaProperties=m;function p(_,h){return m(h).filter(S=>!(0,t.alwaysValidSchema)(_,h[S]))}Ze.schemaProperties=p;function f({schemaCode:_,data:h,it:{gen:S,topSchemaRef:k,schemaPath:C,errorPath:b},it:E},I,L,M){const A=M?(0,e._)`${_}, ${h}, ${k}${C}`:h,O=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,b)],[r.default.parentData,E.parentData],[r.default.parentDataProperty,E.parentDataProperty],[r.default.rootData,r.default.rootData]];E.opts.dynamicRef&&O.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const U=(0,e._)`${A}, ${S.object(...O)}`;return L!==e.nil?(0,e._)`${I}.call(${L}, ${U})`:(0,e._)`${I}(${U})`}Ze.callValidateCode=f;const g=(0,e._)`new RegExp`;function v({gen:_,it:{opts:h}},S){const k=h.unicodeRegExp?"u":"",{regExp:C}=h.code,b=C(S,k);return _.scopeValue("pattern",{key:b.toString(),ref:b,code:(0,e._)`${C.code==="new RegExp"?g:(0,n.useFunc)(_,C)}(${S}, ${k})`})}Ze.usePattern=v;function y(_){const{gen:h,data:S,keyword:k,it:C}=_,b=h.name("valid");if(C.allErrors){const I=h.let("valid",!0);return E(()=>h.assign(I,!1)),I}return h.var(b,!0),E(()=>h.break()),b;function E(I){const L=h.const("len",(0,e._)`${S}.length`);h.forRange("i",0,L,M=>{_.subschema({keyword:k,dataProp:M,dataPropType:t.Type.Num},b),h.if((0,e.not)(b),I)})}}Ze.validateArray=y;function w(_){const{gen:h,schema:S,keyword:k,it:C}=_;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(L=>(0,t.alwaysValidSchema)(C,L))&&!C.opts.unevaluated)return;const E=h.let("valid",!1),I=h.name("_valid");h.block(()=>S.forEach((L,M)=>{const A=_.subschema({keyword:k,schemaProp:M,compositeRule:!0},I);h.assign(E,(0,e._)`${E} || ${I}`),_.mergeValidEvaluated(A,I)||h.if((0,e.not)(E))})),_.result(E,()=>_.reset(),()=>_.error(!0))}return Ze.validateUnion=w,Ze}var Vg;function hx(){if(Vg)return ur;Vg=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.validateKeywordUsage=ur.validSchemaType=ur.funcKeywordCode=ur.macroKeywordCode=void 0;const e=Ne(),t=sn(),r=dr(),n=$a();function o(p,f){const{gen:g,keyword:v,schema:y,parentSchema:w,it:_}=p,h=f.macro.call(_.self,y,w,_),S=c(g,v,h);_.opts.validateSchema!==!1&&_.self.validateSchema(h,!0);const k=g.name("valid");p.subschema({schema:h,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${v}`,topSchemaRef:S,compositeRule:!0},k),p.pass(k,()=>p.error(!0))}ur.macroKeywordCode=o;function s(p,f){var g;const{gen:v,keyword:y,schema:w,parentSchema:_,$data:h,it:S}=p;l(S,f);const k=!h&&f.compile?f.compile.call(S.self,w,_,S):f.validate,C=c(v,y,k),b=v.let("valid");p.block$data(b,E),p.ok((g=f.valid)!==null&&g!==void 0?g:b);function E(){if(f.errors===!1)M(),f.modifying&&a(p),A(()=>p.error());else{const O=f.async?I():L();f.modifying&&a(p),A(()=>i(p,O))}}function I(){const O=v.let("ruleErrs",null);return v.try(()=>M((0,e._)`await `),U=>v.assign(b,!1).if((0,e._)`${U} instanceof ${S.ValidationError}`,()=>v.assign(O,(0,e._)`${U}.errors`),()=>v.throw(U))),O}function L(){const O=(0,e._)`${C}.errors`;return v.assign(O,null),M(e.nil),O}function M(O=f.async?(0,e._)`await `:e.nil){const U=S.opts.passContext?t.default.this:t.default.self,G=!("compile"in f&&!h||f.schema===!1);v.assign(b,(0,e._)`${O}${(0,r.callValidateCode)(p,C,U,G)}`,f.modifying)}function A(O){var U;v.if((0,e.not)((U=f.valid)!==null&&U!==void 0?U:b),O)}}ur.funcKeywordCode=s;function a(p){const{gen:f,data:g,it:v}=p;f.if(v.parentData,()=>f.assign(g,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function i(p,f){const{gen:g}=p;g.if((0,e._)`Array.isArray(${f})`,()=>{g.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${f} : ${t.default.vErrors}.concat(${f})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},f){if(f.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,f,g){if(g===void 0)throw new Error(`keyword "${f}" failed to compile`);return p.scopeValue("keyword",typeof g=="function"?{ref:g}:{ref:g,code:(0,e.stringify)(g)})}function u(p,f,g=!1){return!f.length||f.some(v=>v==="array"?Array.isArray(p):v==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==v||g&&typeof p>"u")}ur.validSchemaType=u;function m({schema:p,opts:f,self:g,errSchemaPath:v},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const _=y.dependencies;if(_?.some(h=>!Object.prototype.hasOwnProperty.call(p,h)))throw new Error(`parent schema must have dependencies of ${w}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const S=`keyword "${w}" value is invalid at path "${v}": `+g.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")g.logger.error(S);else throw new Error(S)}}return ur.validateKeywordUsage=m,ur}var Lr={},Zg;function mx(){if(Zg)return Lr;Zg=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.extendSubschemaMode=Lr.extendSubschemaData=Lr.getSubschema=void 0;const e=Ne(),t=je();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:m}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const p=s.schema[a];return i===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:p[i],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||m===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:m,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Lr.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:m}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=a;if(i!==void 0){const{errorPath:g,dataPathArr:v,opts:y}=a,w=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);f(w),s.errorPath=(0,e.str)`${g}${(0,t.getErrorPath)(i,l,y.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[...v,s.parentDataProperty]}if(c!==void 0){const g=c instanceof e.Name?c:p.let("data",c,!0);f(g),m!==void 0&&(s.propertyName=m)}u&&(s.dataTypes=u);function f(g){s.data=g,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,g]}}Lr.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 Lr.extendSubschemaMode=o,Lr}var Lt={},Yc,Bg;function Hg(){return Bg||(Bg=1,Yc=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}),Yc}var Qc={exports:{}},Jg;function gx(){if(Jg)return Qc.exports;Jg=1;var e=Qc.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var a=typeof s=="function"?s:s.pre||function(){},i=s.post||function(){};t(o,a,i,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,a,i,l,c,u,m,p){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,m,p);for(var f in a){var g=a[f];if(Array.isArray(g)){if(f in e.arrayKeywords)for(var v=0;v<g.length;v++)t(n,o,s,g[v],i+"/"+f+"/"+v,l,i,f,a,v)}else if(f in e.propsKeywords){if(g&&typeof g=="object")for(var y in g)t(n,o,s,g[y],i+"/"+f+"/"+r(y),l,i,f,a,y)}else(f in e.keywords||n.allKeys&&!(f in e.skipKeywords))&&t(n,o,s,g,i+"/"+f,l,i,f,a)}s(a,i,l,c,u,m,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Qc.exports}var Gg;function Pa(){if(Gg)return Lt;Gg=1,Object.defineProperty(Lt,"__esModule",{value:!0}),Lt.getSchemaRefs=Lt.resolveUrl=Lt.normalizeId=Lt._getFullPath=Lt.getFullPath=Lt.inlineRef=void 0;const e=je(),t=Hg(),r=gx(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(v,y=!0){return typeof v=="boolean"?!0:y===!0?!a(v):y?i(v)<=y:!1}Lt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(v){for(const y in v){if(s.has(y))return!0;const w=v[y];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(v){let y=0;for(const w in v){if(w==="$ref")return 1/0;if(y++,!n.has(w)&&(typeof v[w]=="object"&&(0,e.eachItem)(v[w],_=>y+=i(_)),y===1/0))return 1/0}return y}function l(v,y="",w){w!==!1&&(y=m(y));const _=v.parse(y);return c(v,_)}Lt.getFullPath=l;function c(v,y){return v.serialize(y).split("#")[0]+"#"}Lt._getFullPath=c;const u=/#\/?$/;function m(v){return v?v.replace(u,""):""}Lt.normalizeId=m;function p(v,y,w){return w=m(w),v.resolve(y,w)}Lt.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function g(v,y){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:_}=this.opts,h=m(v[w]||y),S={"":h},k=l(_,h,!1),C={},b=new Set;return r(v,{allKeys:!0},(L,M,A,O)=>{if(O===void 0)return;const U=k+M;let G=S[O];typeof L[w]=="string"&&(G=H.call(this,L[w])),le.call(this,L.$anchor),le.call(this,L.$dynamicAnchor),S[M]=G;function H(ee){const he=this.opts.uriResolver.resolve;if(ee=m(G?he(G,ee):ee),b.has(ee))throw I(ee);b.add(ee);let Z=this.refs[ee];return typeof Z=="string"&&(Z=this.refs[Z]),typeof Z=="object"?E(L,Z.schema,ee):ee!==m(U)&&(ee[0]==="#"?(E(L,C[ee],ee),C[ee]=L):this.refs[ee]=U),ee}function le(ee){if(typeof ee=="string"){if(!f.test(ee))throw new Error(`invalid anchor "${ee}"`);H.call(this,`#${ee}`)}}}),C;function E(L,M,A){if(M!==void 0&&!t(L,M))throw I(A)}function I(L){return new Error(`reference "${L}" resolves to more than one schema`)}}return Lt.getSchemaRefs=g,Lt}var Wg;function Na(){if(Wg)return Ar;Wg=1,Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.getData=Ar.KeywordCxt=Ar.validateFunctionCode=void 0;const e=px(),t=Ra(),r=Dg(),n=Ra(),o=fx(),s=hx(),a=mx(),i=Ne(),l=sn(),c=Pa(),u=je(),m=$a();function p(z){if(k(z)&&(b(z),S(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Ar.validateFunctionCode=p;function f({gen:z,validateName:V,schema:K,schemaEnv:Q,opts:ie},ve){ie.code.es5?z.func(V,(0,i._)`${l.default.data}, ${l.default.valCxt}`,Q.$async,()=>{z.code((0,i._)`"use strict"; ${_(K,ie)}`),v(z,ie),z.code(ve)}):z.func(V,(0,i._)`${l.default.data}, ${g(ie)}`,Q.$async,()=>z.code(_(K,ie)).code(ve))}function g(z){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${z.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function v(z,V){z.if(l.default.valCxt,()=>{z.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),z.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),z.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),z.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{z.var(l.default.instancePath,(0,i._)`""`),z.var(l.default.parentData,(0,i._)`undefined`),z.var(l.default.parentDataProperty,(0,i._)`undefined`),z.var(l.default.rootData,l.default.data),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function y(z){const{schema:V,opts:K,gen:Q}=z;f(z,()=>{K.$comment&&V.$comment&&O(z),L(z),Q.let(l.default.vErrors,null),Q.let(l.default.errors,0),K.unevaluated&&w(z),E(z),U(z)})}function w(z){const{gen:V,validateName:K}=z;z.evaluated=V.const("evaluated",(0,i._)`${K}.evaluated`),V.if((0,i._)`${z.evaluated}.dynamicProps`,()=>V.assign((0,i._)`${z.evaluated}.props`,(0,i._)`undefined`)),V.if((0,i._)`${z.evaluated}.dynamicItems`,()=>V.assign((0,i._)`${z.evaluated}.items`,(0,i._)`undefined`))}function _(z,V){const K=typeof z=="object"&&z[V.schemaId];return K&&(V.code.source||V.code.process)?(0,i._)`/*# sourceURL=${K} */`:i.nil}function h(z,V){if(k(z)&&(b(z),S(z))){C(z,V);return}(0,e.boolOrEmptySchema)(z,V)}function S({schema:z,self:V}){if(typeof z=="boolean")return!z;for(const K in z)if(V.RULES.all[K])return!0;return!1}function k(z){return typeof z.schema!="boolean"}function C(z,V){const{schema:K,gen:Q,opts:ie}=z;ie.$comment&&K.$comment&&O(z),M(z),A(z);const ve=Q.const("_errs",l.default.errors);E(z,ve),Q.var(V,(0,i._)`${ve} === ${l.default.errors}`)}function b(z){(0,u.checkUnknownRules)(z),I(z)}function E(z,V){if(z.opts.jtd)return H(z,[],!1,V);const K=(0,t.getSchemaTypes)(z.schema),Q=(0,t.coerceAndCheckDataType)(z,K);H(z,K,!Q,V)}function I(z){const{schema:V,errSchemaPath:K,opts:Q,self:ie}=z;V.$ref&&Q.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(V,ie.RULES)&&ie.logger.warn(`$ref: keywords ignored in schema at path "${K}"`)}function L(z){const{schema:V,opts:K}=z;V.default!==void 0&&K.useDefaults&&K.strictSchema&&(0,u.checkStrictMode)(z,"default is ignored in the schema root")}function M(z){const V=z.schema[z.opts.schemaId];V&&(z.baseId=(0,c.resolveUrl)(z.opts.uriResolver,z.baseId,V))}function A(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function O({gen:z,schemaEnv:V,schema:K,errSchemaPath:Q,opts:ie}){const ve=K.$comment;if(ie.$comment===!0)z.code((0,i._)`${l.default.self}.logger.log(${ve})`);else if(typeof ie.$comment=="function"){const Qe=(0,i.str)`${Q}/$comment`,P=z.scopeValue("root",{ref:V.root});z.code((0,i._)`${l.default.self}.opts.$comment(${ve}, ${Qe}, ${P}.schema)`)}}function U(z){const{gen:V,schemaEnv:K,validateName:Q,ValidationError:ie,opts:ve}=z;K.$async?V.if((0,i._)`${l.default.errors} === 0`,()=>V.return(l.default.data),()=>V.throw((0,i._)`new ${ie}(${l.default.vErrors})`)):(V.assign((0,i._)`${Q}.errors`,l.default.vErrors),ve.unevaluated&&G(z),V.return((0,i._)`${l.default.errors} === 0`))}function G({gen:z,evaluated:V,props:K,items:Q}){K instanceof i.Name&&z.assign((0,i._)`${V}.props`,K),Q instanceof i.Name&&z.assign((0,i._)`${V}.items`,Q)}function H(z,V,K,Q){const{gen:ie,schema:ve,data:Qe,allErrors:P,opts:X,self:Re}=z,{RULES:qe}=Re;if(ve.$ref&&(X.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ve,qe))){ie.block(()=>W(z,"$ref",qe.all.$ref.definition));return}X.jtd||ee(z,V),ie.block(()=>{for(const ft of qe.rules)Vt(ft);Vt(qe.post)});function Vt(ft){(0,r.shouldUseGroup)(ve,ft)&&(ft.type?(ie.if((0,n.checkDataType)(ft.type,Qe,X.strictNumbers)),le(z,ft),V.length===1&&V[0]===ft.type&&K&&(ie.else(),(0,n.reportTypeError)(z)),ie.endIf()):le(z,ft),P||ie.if((0,i._)`${l.default.errors} === ${Q||0}`))}}function le(z,V){const{gen:K,schema:Q,opts:{useDefaults:ie}}=z;ie&&(0,o.assignDefaults)(z,V.type),K.block(()=>{for(const ve of V.rules)(0,r.shouldUseRule)(Q,ve)&&W(z,ve.keyword,ve.definition,V.type)})}function ee(z,V){z.schemaEnv.meta||!z.opts.strictTypes||(he(z,V),z.opts.allowUnionTypes||Z(z,V),R(z,z.dataTypes))}function he(z,V){if(V.length){if(!z.dataTypes.length){z.dataTypes=V;return}V.forEach(K=>{F(z.dataTypes,K)||N(z,`type "${K}" not allowed by context "${z.dataTypes.join(",")}"`)}),x(z,V)}}function Z(z,V){V.length>1&&!(V.length===2&&V.includes("null"))&&N(z,"use allowUnionTypes to allow union type keyword")}function R(z,V){const K=z.self.RULES.all;for(const Q in K){const ie=K[Q];if(typeof ie=="object"&&(0,r.shouldUseRule)(z.schema,ie)){const{type:ve}=ie.definition;ve.length&&!ve.some(Qe=>B(V,Qe))&&N(z,`missing type "${ve.join(",")}" for keyword "${Q}"`)}}}function B(z,V){return z.includes(V)||V==="number"&&z.includes("integer")}function F(z,V){return z.includes(V)||V==="integer"&&z.includes("number")}function x(z,V){const K=[];for(const Q of z.dataTypes)F(V,Q)?K.push(Q):V.includes("integer")&&Q==="number"&&K.push("integer");z.dataTypes=K}function N(z,V){const K=z.schemaEnv.baseId+z.errSchemaPath;V+=` at "${K}" (strictTypes)`,(0,u.checkStrictMode)(z,V,z.opts.strictTypes)}class D{constructor(V,K,Q){if((0,s.validateKeywordUsage)(V,K,Q),this.gen=V.gen,this.allErrors=V.allErrors,this.keyword=Q,this.data=V.data,this.schema=V.schema[Q],this.$data=K.$data&&V.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(V,this.schema,Q,this.$data),this.schemaType=K.schemaType,this.parentSchema=V.schema,this.params={},this.it=V,this.def=K,this.$data)this.schemaCode=V.gen.const("vSchema",Te(this.$data,V));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,K.schemaType,K.allowUndefined))throw new Error(`${Q} value must be ${JSON.stringify(K.schemaType)}`);("code"in K?K.trackErrors:K.errors!==!1)&&(this.errsCount=V.gen.const("_errs",l.default.errors))}result(V,K,Q){this.failResult((0,i.not)(V),K,Q)}failResult(V,K,Q){this.gen.if(V),Q?Q():this.error(),K?(this.gen.else(),K(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(V,K){this.failResult((0,i.not)(V),void 0,K)}fail(V){if(V===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(V),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(V){if(!this.$data)return this.fail(V);const{schemaCode:K}=this;this.fail((0,i._)`${K} !== undefined && (${(0,i.or)(this.invalid$data(),V)})`)}error(V,K,Q){if(K){this.setParams(K),this._error(V,Q),this.setParams({});return}this._error(V,Q)}_error(V,K){(V?m.reportExtraError:m.reportError)(this,this.def.error,K)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(V){this.allErrors||this.gen.if(V)}setParams(V,K){K?Object.assign(this.params,V):this.params=V}block$data(V,K,Q=i.nil){this.gen.block(()=>{this.check$data(V,Q),K()})}check$data(V=i.nil,K=i.nil){if(!this.$data)return;const{gen:Q,schemaCode:ie,schemaType:ve,def:Qe}=this;Q.if((0,i.or)((0,i._)`${ie} === undefined`,K)),V!==i.nil&&Q.assign(V,!0),(ve.length||Qe.validateSchema)&&(Q.elseIf(this.invalid$data()),this.$dataError(),V!==i.nil&&Q.assign(V,!1)),Q.else()}invalid$data(){const{gen:V,schemaCode:K,schemaType:Q,def:ie,it:ve}=this;return(0,i.or)(Qe(),P());function Qe(){if(Q.length){if(!(K instanceof i.Name))throw new Error("ajv implementation error");const X=Array.isArray(Q)?Q:[Q];return(0,i._)`${(0,n.checkDataTypes)(X,K,ve.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function P(){if(ie.validateSchema){const X=V.scopeValue("validate$data",{ref:ie.validateSchema});return(0,i._)`!${X}(${K})`}return i.nil}}subschema(V,K){const Q=(0,a.getSubschema)(this.it,V);(0,a.extendSubschemaData)(Q,this.it,V),(0,a.extendSubschemaMode)(Q,V);const ie={...this.it,...Q,items:void 0,props:void 0};return h(ie,K),ie}mergeEvaluated(V,K){const{it:Q,gen:ie}=this;Q.opts.unevaluated&&(Q.props!==!0&&V.props!==void 0&&(Q.props=u.mergeEvaluated.props(ie,V.props,Q.props,K)),Q.items!==!0&&V.items!==void 0&&(Q.items=u.mergeEvaluated.items(ie,V.items,Q.items,K)))}mergeValidEvaluated(V,K){const{it:Q,gen:ie}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return ie.if(K,()=>this.mergeEvaluated(V,i.Name)),!0}}Ar.KeywordCxt=D;function W(z,V,K,Q){const ie=new D(z,K,V);"code"in K?K.code(ie,Q):ie.$data&&K.validate?(0,s.funcKeywordCode)(ie,K):"macro"in K?(0,s.macroKeywordCode)(ie,K):(K.compile||K.validate)&&(0,s.funcKeywordCode)(ie,K)}const re=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Te(z,{dataLevel:V,dataNames:K,dataPathArr:Q}){let ie,ve;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!re.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);ie=z,ve=l.default.rootData}else{const Re=se.exec(z);if(!Re)throw new Error(`Invalid JSON-pointer: ${z}`);const qe=+Re[1];if(ie=Re[2],ie==="#"){if(qe>=V)throw new Error(X("property/index",qe));return Q[V-qe]}if(qe>V)throw new Error(X("data",qe));if(ve=K[V-qe],!ie)return ve}let Qe=ve;const P=ie.split("/");for(const Re of P)Re&&(ve=(0,i._)`${ve}${(0,i.getProperty)((0,u.unescapeJsonPointer)(Re))}`,Qe=(0,i._)`${Qe} && ${ve}`);return Qe;function X(Re,qe){return`Cannot access ${Re} ${qe} levels up, current level is ${V}`}}return Ar.getData=Te,Ar}var Ma={},Kg;function Xc(){if(Kg)return Ma;Kg=1,Object.defineProperty(Ma,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Ma.default=e,Ma}var Oa={},Yg;function Aa(){if(Yg)return Oa;Yg=1,Object.defineProperty(Oa,"__esModule",{value:!0});const e=Pa();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 Oa.default=t,Oa}var Gt={},Qg;function eu(){if(Qg)return Gt;Qg=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.resolveSchema=Gt.getCompilingSchema=Gt.resolveRef=Gt.compileSchema=Gt.SchemaEnv=void 0;const e=Ne(),t=Xc(),r=sn(),n=Pa(),o=je(),s=Na();class a{constructor(w){var _;this.refs={},this.dynamicAnchors={};let h;typeof w.schema=="object"&&(h=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(_=w.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(h?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=h?.$async,this.refs={}}}Gt.SchemaEnv=a;function i(y){const w=u.call(this,y);if(w)return w;const _=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:h,lines:S}=this.opts.code,{ownProperties:k}=this.opts,C=new e.CodeGen(this.scope,{es5:h,lines:S,ownProperties:k});let b;y.$async&&(b=C.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const E=C.scopeName("validate");y.validateName=E;const I={gen:C,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:C.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:E,ValidationError:b,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let L;try{this._compilations.add(y),(0,s.validateFunctionCode)(I),C.optimize(this.opts.code.optimize);const M=C.toString();L=`${C.scopeRefs(r.default.scope)}return ${M}`,this.opts.code.process&&(L=this.opts.code.process(L,y));const O=new Function(`${r.default.self}`,`${r.default.scope}`,L)(this,this.scope.get());if(this.scope.value(E,{ref:O}),O.errors=null,O.schema=y.schema,O.schemaEnv=y,y.$async&&(O.$async=!0),this.opts.code.source===!0&&(O.source={validateName:E,validateCode:M,scopeValues:C._values}),this.opts.unevaluated){const{props:U,items:G}=I;O.evaluated={props:U instanceof e.Name?void 0:U,items:G instanceof e.Name?void 0:G,dynamicProps:U instanceof e.Name,dynamicItems:G instanceof e.Name},O.source&&(O.source.evaluated=(0,e.stringify)(O.evaluated))}return y.validate=O,y}catch(M){throw delete y.validate,delete y.validateName,L&&this.logger.error("Error compiling schema, function code:",L),M}finally{this._compilations.delete(y)}}Gt.compileSchema=i;function l(y,w,_){var h;_=(0,n.resolveUrl)(this.opts.uriResolver,w,_);const S=y.refs[_];if(S)return S;let k=p.call(this,y,_);if(k===void 0){const C=(h=y.localRefs)===null||h===void 0?void 0:h[_],{schemaId:b}=this.opts;C&&(k=new a({schema:C,schemaId:b,root:y,baseId:w}))}if(k!==void 0)return y.refs[_]=c.call(this,k)}Gt.resolveRef=l;function c(y){return(0,n.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:i.call(this,y)}function u(y){for(const w of this._compilations)if(m(w,y))return w}Gt.getCompilingSchema=u;function m(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let _;for(;typeof(_=this.refs[w])=="string";)w=_;return _||this.schemas[w]||f.call(this,y,w)}function f(y,w){const _=this.opts.uriResolver.parse(w),h=(0,n._getFullPath)(this.opts.uriResolver,_);let S=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&h===S)return v.call(this,_,y);const k=(0,n.normalizeId)(h),C=this.refs[k]||this.schemas[k];if(typeof C=="string"){const b=f.call(this,y,C);return typeof b?.schema!="object"?void 0:v.call(this,_,b)}if(typeof C?.schema=="object"){if(C.validate||i.call(this,C),k===(0,n.normalizeId)(w)){const{schema:b}=C,{schemaId:E}=this.opts,I=b[E];return I&&(S=(0,n.resolveUrl)(this.opts.uriResolver,S,I)),new a({schema:b,schemaId:E,root:y,baseId:S})}return v.call(this,_,C)}}Gt.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(y,{baseId:w,schema:_,root:h}){var S;if(((S=y.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(const b of y.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const E=_[(0,o.unescapeFragment)(b)];if(E===void 0)return;_=E;const I=typeof _=="object"&&_[this.opts.schemaId];!g.has(b)&&I&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,I))}let k;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const b=(0,n.resolveUrl)(this.opts.uriResolver,w,_.$ref);k=f.call(this,h,b)}const{schemaId:C}=this.opts;if(k=k||new a({schema:_,schemaId:C,root:h,baseId:w}),k.schema!==k.root.schema)return k}return Gt}const yx={$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 qa={},as={exports:{}},tu,Xg;function ey(){if(Xg)return tu;Xg=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(p){let f="",g=0,v=0;for(v=0;v<p.length;v++)if(g=p[v].charCodeAt(0),g!==48){if(!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[v];break}for(v+=1;v<p.length;v++){if(g=p[v].charCodeAt(0),!(g>=48&&g<=57||g>=65&&g<=70||g>=97&&g<=102))return"";f+=p[v]}return f}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,f,g){if(p.length){const v=r(p);if(v!=="")f.push(v);else return g.error=!0,!1;p.length=0}return!0}function a(p){let f=0;const g={error:!1,address:"",zone:""},v=[],y=[];let w=!1,_=!1,h=s;for(let S=0;S<p.length;S++){const k=p[S];if(!(k==="["||k==="]"))if(k===":"){if(w===!0&&(_=!0),!h(y,v,g))break;if(++f>7){g.error=!0;break}S>0&&p[S-1]===":"&&(w=!0),v.push(":");continue}else if(k==="%"){if(!h(y,v,g))break;h=o}else{y.push(k);continue}}return y.length&&(h===o?g.zone=y.join(""):_?v.push(y.join("")):v.push(r(y))),g.address=v.join(""),g}function i(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const f=a(p);if(f.error)return{host:p,isIPV6:!1};{let g=f.address,v=f.address;return f.zone&&(g+="%"+f.zone,v+="%25"+f.zone),{host:g,isIPV6:!0,escapedHost:v}}}function l(p,f){let g=0;for(let v=0;v<p.length;v++)p[v]===f&&g++;return g}function c(p){let f=p;const g=[];let v=-1,y=0;for(;y=f.length;){if(y===1){if(f===".")break;if(f==="/"){g.push("/");break}else{g.push(f);break}}else if(y===2){if(f[0]==="."){if(f[1]===".")break;if(f[1]==="/"){f=f.slice(2);continue}}else if(f[0]==="/"&&(f[1]==="."||f[1]==="/")){g.push("/");break}}else if(y===3&&f==="/.."){g.length!==0&&g.pop(),g.push("/");break}if(f[0]==="."){if(f[1]==="."){if(f[2]==="/"){f=f.slice(3);continue}}else if(f[1]==="/"){f=f.slice(2);continue}}else if(f[0]==="/"&&f[1]==="."){if(f[2]==="/"){f=f.slice(2);continue}else if(f[2]==="."&&f[3]==="/"){f=f.slice(3),g.length!==0&&g.pop();continue}}if((v=f.indexOf("/",1))===-1){g.push(f);break}else g.push(f.slice(0,v)),f=f.slice(v)}return g.join("")}function u(p,f){const g=f!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=g(p.scheme)),p.userinfo!==void 0&&(p.userinfo=g(p.userinfo)),p.host!==void 0&&(p.host=g(p.host)),p.path!==void 0&&(p.path=g(p.path)),p.query!==void 0&&(p.query=g(p.query)),p.fragment!==void 0&&(p.fragment=g(p.fragment)),p}function m(p){const f=[];if(p.userinfo!==void 0&&(f.push(p.userinfo),f.push("@")),p.host!==void 0){let g=unescape(p.host);if(!t(g)){const v=i(g);v.isIPV6===!0?g=`[${v.escapedHost}]`:g=p.host}f.push(g)}return(typeof p.port=="number"||typeof p.port=="string")&&(f.push(":"),f.push(String(p.port))),f.length?f.join(""):void 0}return tu={nonSimpleDomain:n,recomposeAuthority:m,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},tu}var ru,ty;function _x(){if(ty)return ru;ty=1;const{isUUID:e}=ey(),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 C=String(k.scheme).toLowerCase()==="https";return(k.port===(C?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[C,b]=k.resourceName.split("?");k.path=C&&C!=="/"?C:void 0,k.query=b,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,C){if(!k.path)return k.error="URN can not be parsed",k;const b=k.path.match(t);if(b){const E=C.scheme||k.scheme||"urn";k.nid=b[1].toLowerCase(),k.nss=b[2];const I=`${E}:${C.nid||k.nid}`,L=S(I);k.path=void 0,L&&(k=L.parse(k,C))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,C){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const b=C.scheme||k.scheme||"urn",E=k.nid.toLowerCase(),I=`${b}:${C.nid||E}`,L=S(I);L&&(k=L.serialize(k,C));const M=k,A=k.nss;return M.path=`${E||C.nid}:${A}`,C.skipEscape=!0,M}function m(k,C){const b=k;return b.uuid=b.nss,b.nss=void 0,!C.tolerant&&(!b.uuid||!e(b.uuid))&&(b.error=b.error||"UUID is not valid."),b}function p(k){const C=k;return C.nss=(k.uuid||"").toLowerCase(),C}const f={scheme:"http",domainHost:!0,parse:s,serialize:a},g={scheme:"https",domainHost:f.domainHost,parse:s,serialize:a},v={scheme:"ws",domainHost:!0,parse:i,serialize:l},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},h={http:f,https:g,ws:v,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:m,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(h,null);function S(k){return k&&(h[k]||h[k.toLowerCase()])||void 0}return ru={wsIsSecure:o,SCHEMES:h,isValidSchemeName:n,getSchemeHandler:S},ru}var ry;function vx(){if(ry)return as.exports;ry=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=ey(),{SCHEMES:a,getSchemeHandler:i}=_x();function l(y,w){return typeof y=="string"?y=p(g(y,w),w):typeof y=="object"&&(y=g(p(y,w),w)),y}function c(y,w,_){const h=_?Object.assign({scheme:"null"},_):{scheme:"null"},S=u(g(y,h),g(w,h),h,!0);return h.skipEscape=!0,p(S,h)}function u(y,w,_,h){const S={};return h||(y=g(p(y,_),_),w=g(p(w,_),_)),_=_||{},!_.tolerant&&w.scheme?(S.scheme=w.scheme,S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.path?(w.path[0]==="/"?S.path=t(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?S.path="/"+w.path:y.path?S.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:S.path=w.path,S.path=t(S.path)),S.query=w.query):(S.path=y.path,w.query!==void 0?S.query=w.query:S.query=y.query),S.userinfo=y.userinfo,S.host=y.host,S.port=y.port),S.scheme=y.scheme),S.fragment=w.fragment,S}function m(y,w,_){return typeof y=="string"?(y=unescape(y),y=p(n(g(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{..._,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(g(w,_),!0),{..._,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{..._,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const _={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},h=Object.assign({},w),S=[],k=i(h.scheme||_.scheme);k&&k.serialize&&k.serialize(_,h),_.path!==void 0&&(h.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),h.reference!=="suffix"&&_.scheme&&S.push(_.scheme,":");const C=r(_);if(C!==void 0&&(h.reference!=="suffix"&&S.push("//"),S.push(C),_.path&&_.path[0]!=="/"&&S.push("/")),_.path!==void 0){let b=_.path;!h.absolutePath&&(!k||!k.absolutePath)&&(b=t(b)),C===void 0&&b[0]==="/"&&b[1]==="/"&&(b="/%2F"+b.slice(2)),S.push(b)}return _.query!==void 0&&S.push("?",_.query),_.fragment!==void 0&&S.push("#",_.fragment),S.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(y,w){const _=Object.assign({},w),h={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let S=!1;_.reference==="suffix"&&(_.scheme?y=_.scheme+":"+y:y="//"+y);const k=y.match(f);if(k){if(h.scheme=k[1],h.userinfo=k[3],h.host=k[4],h.port=parseInt(k[5],10),h.path=k[6]||"",h.query=k[7],h.fragment=k[8],isNaN(h.port)&&(h.port=k[5]),h.host)if(o(h.host)===!1){const E=e(h.host);h.host=E.host.toLowerCase(),S=E.isIPV6}else S=!0;h.scheme===void 0&&h.userinfo===void 0&&h.host===void 0&&h.port===void 0&&h.query===void 0&&!h.path?h.reference="same-document":h.scheme===void 0?h.reference="relative":h.fragment===void 0?h.reference="absolute":h.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==h.reference&&(h.error=h.error||"URI is not a "+_.reference+" reference.");const C=i(_.scheme||h.scheme);if(!_.unicodeSupport&&(!C||!C.unicodeSupport)&&h.host&&(_.domainHost||C&&C.domainHost)&&S===!1&&s(h.host))try{h.host=URL.domainToASCII(h.host.toLowerCase())}catch(b){h.error=h.error||"Host's domain name can not be converted to ASCII: "+b}(!C||C&&!C.skipNormalize)&&(y.indexOf("%")!==-1&&(h.scheme!==void 0&&(h.scheme=unescape(h.scheme)),h.host!==void 0&&(h.host=unescape(h.host))),h.path&&(h.path=escape(unescape(h.path))),h.fragment&&(h.fragment=encodeURI(decodeURIComponent(h.fragment)))),C&&C.parse&&C.parse(h,_)}else h.error=h.error||"URI can not be parsed.";return h}const v={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:m,serialize:p,parse:g};return as.exports=v,as.exports.default=v,as.exports.fastUri=v,as.exports}var ny;function wx(){if(ny)return qa;ny=1,Object.defineProperty(qa,"__esModule",{value:!0});const e=vx();return e.code='require("ajv/dist/runtime/uri").default',qa.default=e,qa}var oy;function bx(){return oy||(oy=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=Na();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ne();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Xc(),o=Aa(),s=Lg(),a=eu(),i=Ne(),l=Pa(),c=Ra(),u=je(),m=yx,p=wx(),f=(Z,R)=>new RegExp(Z,R);f.code="new RegExp";const g=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function h(Z){var R,B,F,x,N,D,W,re,se,Te,z,V,K,Q,ie,ve,Qe,P,X,Re,qe,Vt,ft,Ke,zr;const Xe=Z.strict,Wt=(R=Z.code)===null||R===void 0?void 0:R.optimize,Fr=Wt===!0||Wt===void 0?1:Wt||0,et=(F=(B=Z.code)===null||B===void 0?void 0:B.regExp)!==null&&F!==void 0?F:f,Se=(x=Z.uriResolver)!==null&&x!==void 0?x:p.default;return{strictSchema:(D=(N=Z.strictSchema)!==null&&N!==void 0?N:Xe)!==null&&D!==void 0?D:!0,strictNumbers:(re=(W=Z.strictNumbers)!==null&&W!==void 0?W:Xe)!==null&&re!==void 0?re:!0,strictTypes:(Te=(se=Z.strictTypes)!==null&&se!==void 0?se:Xe)!==null&&Te!==void 0?Te:"log",strictTuples:(V=(z=Z.strictTuples)!==null&&z!==void 0?z:Xe)!==null&&V!==void 0?V:"log",strictRequired:(Q=(K=Z.strictRequired)!==null&&K!==void 0?K:Xe)!==null&&Q!==void 0?Q:!1,code:Z.code?{...Z.code,optimize:Fr,regExp:et}:{optimize:Fr,regExp:et},loopRequired:(ie=Z.loopRequired)!==null&&ie!==void 0?ie:_,loopEnum:(ve=Z.loopEnum)!==null&&ve!==void 0?ve:_,meta:(Qe=Z.meta)!==null&&Qe!==void 0?Qe:!0,messages:(P=Z.messages)!==null&&P!==void 0?P:!0,inlineRefs:(X=Z.inlineRefs)!==null&&X!==void 0?X:!0,schemaId:(Re=Z.schemaId)!==null&&Re!==void 0?Re:"$id",addUsedSchema:(qe=Z.addUsedSchema)!==null&&qe!==void 0?qe:!0,validateSchema:(Vt=Z.validateSchema)!==null&&Vt!==void 0?Vt:!0,validateFormats:(ft=Z.validateFormats)!==null&&ft!==void 0?ft:!0,unicodeRegExp:(Ke=Z.unicodeRegExp)!==null&&Ke!==void 0?Ke:!0,int32range:(zr=Z.int32range)!==null&&zr!==void 0?zr:!0,uriResolver:Se}}class S{constructor(R={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,R=this.opts={...R,...h(R)};const{es5:B,lines:F}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:B,lines:F}),this.logger=A(R.logger);const x=R.validateFormats;R.validateFormats=!1,this.RULES=(0,s.getRules)(),k.call(this,y,R,"NOT SUPPORTED"),k.call(this,w,R,"DEPRECATED","warn"),this._metaOpts=L.call(this),R.formats&&E.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),R.keywords&&I.call(this,R.keywords),typeof R.meta=="object"&&this.addMetaSchema(R.meta),b.call(this),R.validateFormats=x}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:R,meta:B,schemaId:F}=this.opts;let x=m;F==="id"&&(x={...m},x.id=x.$id,delete x.$id),B&&R&&this.addMetaSchema(x,x[F],!1)}defaultMeta(){const{meta:R,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof R=="object"?R[B]||R:void 0}validate(R,B){let F;if(typeof R=="string"){if(F=this.getSchema(R),!F)throw new Error(`no schema with key or ref "${R}"`)}else F=this.compile(R);const x=F(B);return"$async"in F||(this.errors=F.errors),x}compile(R,B){const F=this._addSchema(R,B);return F.validate||this._compileSchemaEnv(F)}compileAsync(R,B){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:F}=this.opts;return x.call(this,R,B);async function x(Te,z){await N.call(this,Te.$schema);const V=this._addSchema(Te,z);return V.validate||D.call(this,V)}async function N(Te){Te&&!this.getSchema(Te)&&await x.call(this,{$ref:Te},!0)}async function D(Te){try{return this._compileSchemaEnv(Te)}catch(z){if(!(z instanceof o.default))throw z;return W.call(this,z),await re.call(this,z.missingSchema),D.call(this,Te)}}function W({missingSchema:Te,missingRef:z}){if(this.refs[Te])throw new Error(`AnySchema ${Te} is loaded but ${z} cannot be resolved`)}async function re(Te){const z=await se.call(this,Te);this.refs[Te]||await N.call(this,z.$schema),this.refs[Te]||this.addSchema(z,Te,B)}async function se(Te){const z=this._loading[Te];if(z)return z;try{return await(this._loading[Te]=F(Te))}finally{delete this._loading[Te]}}}addSchema(R,B,F,x=this.opts.validateSchema){if(Array.isArray(R)){for(const D of R)this.addSchema(D,void 0,F,x);return this}let N;if(typeof R=="object"){const{schemaId:D}=this.opts;if(N=R[D],N!==void 0&&typeof N!="string")throw new Error(`schema ${D} must be string`)}return B=(0,l.normalizeId)(B||N),this._checkUnique(B),this.schemas[B]=this._addSchema(R,F,B,x,!0),this}addMetaSchema(R,B,F=this.opts.validateSchema){return this.addSchema(R,B,!0,F),this}validateSchema(R,B){if(typeof R=="boolean")return!0;let F;if(F=R.$schema,F!==void 0&&typeof F!="string")throw new Error("$schema must be a string");if(F=F||this.opts.defaultMeta||this.defaultMeta(),!F)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const x=this.validate(F,R);if(!x&&B){const N="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(N);else throw new Error(N)}return x}getSchema(R){let B;for(;typeof(B=C.call(this,R))=="string";)R=B;if(B===void 0){const{schemaId:F}=this.opts,x=new a.SchemaEnv({schema:{},schemaId:F});if(B=a.resolveSchema.call(this,x,R),!B)return;this.refs[R]=B}return B.validate||this._compileSchemaEnv(B)}removeSchema(R){if(R instanceof RegExp)return this._removeAllSchemas(this.schemas,R),this._removeAllSchemas(this.refs,R),this;switch(typeof R){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const B=C.call(this,R);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[R],delete this.refs[R],this}case"object":{const B=R;this._cache.delete(B);let F=R[this.opts.schemaId];return F&&(F=(0,l.normalizeId)(F),delete this.schemas[F],delete this.refs[F]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(R){for(const B of R)this.addKeyword(B);return this}addKeyword(R,B){let F;if(typeof R=="string")F=R,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=F);else if(typeof R=="object"&&B===void 0){if(B=R,F=B.keyword,Array.isArray(F)&&!F.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,F,B),!B)return(0,u.eachItem)(F,N=>G.call(this,N)),this;le.call(this,B);const x={...B,type:(0,c.getJSONTypes)(B.type),schemaType:(0,c.getJSONTypes)(B.schemaType)};return(0,u.eachItem)(F,x.type.length===0?N=>G.call(this,N,x):N=>x.type.forEach(D=>G.call(this,N,x,D))),this}getKeyword(R){const B=this.RULES.all[R];return typeof B=="object"?B.definition:!!B}removeKeyword(R){const{RULES:B}=this;delete B.keywords[R],delete B.all[R];for(const F of B.rules){const x=F.rules.findIndex(N=>N.keyword===R);x>=0&&F.rules.splice(x,1)}return this}addFormat(R,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[R]=B,this}errorsText(R=this.errors,{separator:B=", ",dataVar:F="data"}={}){return!R||R.length===0?"No errors":R.map(x=>`${F}${x.instancePath} ${x.message}`).reduce((x,N)=>x+B+N)}$dataMetaSchema(R,B){const F=this.RULES.all;R=JSON.parse(JSON.stringify(R));for(const x of B){const N=x.split("/").slice(1);let D=R;for(const W of N)D=D[W];for(const W in F){const re=F[W];if(typeof re!="object")continue;const{$data:se}=re.definition,Te=D[W];se&&Te&&(D[W]=he(Te))}}return R}_removeAllSchemas(R,B){for(const F in R){const x=R[F];(!B||B.test(F))&&(typeof x=="string"?delete R[F]:x&&!x.meta&&(this._cache.delete(x.schema),delete R[F]))}}_addSchema(R,B,F,x=this.opts.validateSchema,N=this.opts.addUsedSchema){let D;const{schemaId:W}=this.opts;if(typeof R=="object")D=R[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof R!="boolean")throw new Error("schema must be object or boolean")}let re=this._cache.get(R);if(re!==void 0)return re;F=(0,l.normalizeId)(D||F);const se=l.getSchemaRefs.call(this,R,F);return re=new a.SchemaEnv({schema:R,schemaId:W,meta:B,baseId:F,localRefs:se}),this._cache.set(re.schema,re),N&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=re),x&&this.validateSchema(R,!0),re}_checkUnique(R){if(this.schemas[R]||this.refs[R])throw new Error(`schema with key or id "${R}" already exists`)}_compileSchemaEnv(R){if(R.meta?this._compileMetaSchema(R):a.compileSchema.call(this,R),!R.validate)throw new Error("ajv implementation error");return R.validate}_compileMetaSchema(R){const B=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,R)}finally{this.opts=B}}}S.ValidationError=n.default,S.MissingRefError=o.default,e.default=S;function k(Z,R,B,F="error"){for(const x in Z){const N=x;N in R&&this.logger[F](`${B}: option ${x}. ${Z[N]}`)}}function C(Z){return Z=(0,l.normalizeId)(Z),this.schemas[Z]||this.refs[Z]}function b(){const Z=this.opts.schemas;if(Z)if(Array.isArray(Z))this.addSchema(Z);else for(const R in Z)this.addSchema(Z[R],R)}function E(){for(const Z in this.opts.formats){const R=this.opts.formats[Z];R&&this.addFormat(Z,R)}}function I(Z){if(Array.isArray(Z)){this.addVocabulary(Z);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const R in Z){const B=Z[R];B.keyword||(B.keyword=R),this.addKeyword(B)}}function L(){const Z={...this.opts};for(const R of g)delete Z[R];return Z}const M={log(){},warn(){},error(){}};function A(Z){if(Z===!1)return M;if(Z===void 0)return console;if(Z.log&&Z.warn&&Z.error)return Z;throw new Error("logger must implement log, warn and error methods")}const O=/^[a-z_$][a-z0-9_$:-]*$/i;function U(Z,R){const{RULES:B}=this;if((0,u.eachItem)(Z,F=>{if(B.keywords[F])throw new Error(`Keyword ${F} is already defined`);if(!O.test(F))throw new Error(`Keyword ${F} has invalid name`)}),!!R&&R.$data&&!("code"in R||"validate"in R))throw new Error('$data keyword must have "code" or "validate" function')}function G(Z,R,B){var F;const x=R?.post;if(B&&x)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:N}=this;let D=x?N.post:N.rules.find(({type:re})=>re===B);if(D||(D={type:B,rules:[]},N.rules.push(D)),N.keywords[Z]=!0,!R)return;const W={keyword:Z,definition:{...R,type:(0,c.getJSONTypes)(R.type),schemaType:(0,c.getJSONTypes)(R.schemaType)}};R.before?H.call(this,D,W,R.before):D.rules.push(W),N.all[Z]=W,(F=R.implements)===null||F===void 0||F.forEach(re=>this.addKeyword(re))}function H(Z,R,B){const F=Z.rules.findIndex(x=>x.keyword===B);F>=0?Z.rules.splice(F,0,R):(Z.rules.push(R),this.logger.warn(`rule ${B} is not defined`))}function le(Z){let{metaSchema:R}=Z;R!==void 0&&(Z.$data&&this.opts.$data&&(R=he(R)),Z.validateSchema=this.compile(R,!0))}const ee={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function he(Z){return{anyOf:[Z,ee]}}})(Hc)),Hc}var La={},ja={},Da={},sy;function kx(){if(sy)return Da;sy=1,Object.defineProperty(Da,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Da.default=e,Da}var an={},ay;function Cx(){if(ay)return an;ay=1,Object.defineProperty(an,"__esModule",{value:!0}),an.callRef=an.getValidate=void 0;const e=Aa(),t=dr(),r=Ne(),n=sn(),o=eu(),s=je(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:m,it:p}=c,{baseId:f,schemaEnv:g,validateName:v,opts:y,self:w}=p,{root:_}=g;if((m==="#"||m==="#/")&&f===_.baseId)return S();const h=o.resolveRef.call(w,_,f,m);if(h===void 0)throw new e.default(p.opts.uriResolver,f,m);if(h instanceof o.SchemaEnv)return k(h);return C(h);function S(){if(g===_)return l(c,v,g,g.$async);const b=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${b}.validate`,_,_.$async)}function k(b){const E=i(c,b);l(c,E,b,b.$async)}function C(b){const E=u.scopeValue("schema",y.code.source===!0?{ref:b,code:(0,r.stringify)(b)}:{ref:b}),I=u.name("valid"),L=c.subschema({schema:b,dataTypes:[],schemaPath:r.nil,topSchemaRef:E,errSchemaPath:m},I);c.mergeEvaluated(L),c.ok(I)}}};function i(c,u){const{gen:m}=c;return u.validate?m.scopeValue("validate",{ref:u.validate}):(0,r._)`${m.scopeValue("wrapper",{ref:u})}.validate`}an.getValidate=i;function l(c,u,m,p){const{gen:f,it:g}=c,{allErrors:v,schemaEnv:y,opts:w}=g,_=w.passContext?n.default.this:r.nil;p?h():S();function h(){if(!y.$async)throw new Error("async schema referenced by sync schema");const b=f.let("valid");f.try(()=>{f.code((0,r._)`await ${(0,t.callValidateCode)(c,u,_)}`),C(u),v||f.assign(b,!0)},E=>{f.if((0,r._)`!(${E} instanceof ${g.ValidationError})`,()=>f.throw(E)),k(E),v||f.assign(b,!1)}),c.ok(b)}function S(){c.result((0,t.callValidateCode)(c,u,_),()=>C(u),()=>k(u))}function k(b){const E=(0,r._)`${b}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${E} : ${n.default.vErrors}.concat(${E})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function C(b){var E;if(!g.opts.unevaluated)return;const I=(E=m?.validate)===null||E===void 0?void 0:E.evaluated;if(g.props!==!0)if(I&&!I.dynamicProps)I.props!==void 0&&(g.props=s.mergeEvaluated.props(f,I.props,g.props));else{const L=f.var("props",(0,r._)`${b}.evaluated.props`);g.props=s.mergeEvaluated.props(f,L,g.props,r.Name)}if(g.items!==!0)if(I&&!I.dynamicItems)I.items!==void 0&&(g.items=s.mergeEvaluated.items(f,I.items,g.items));else{const L=f.var("items",(0,r._)`${b}.evaluated.items`);g.items=s.mergeEvaluated.items(f,L,g.items,r.Name)}}}return an.callRef=l,an.default=a,an}var iy;function Tx(){if(iy)return ja;iy=1,Object.defineProperty(ja,"__esModule",{value:!0});const e=kx(),t=Cx(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return ja.default=r,ja}var Ua={},za={},ly;function Sx(){if(ly)return za;ly=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Ne(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:a})=>(0,e.str)`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${a}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:a,data:i,schemaCode:l}=s;s.fail$data((0,e._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return za.default=o,za}var Fa={},cy;function Ix(){if(cy)return Fa;cy=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e=Ne(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${a} === 0 || (${c} = ${s}/${a}, ${u}))`)}};return Fa.default=r,Fa}var Va={},Za={},uy;function xx(){if(uy)return Za;uy=1,Object.defineProperty(Za,"__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 Za.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Za}var dy;function Ex(){if(dy)return Va;dy=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Ne(),t=je(),r=xx(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:a}){const i=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:a,data:i,schemaCode:l,it:c}=s,u=a==="maxLength"?e.operators.GT:e.operators.LT,m=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${m} ${u} ${l}`)}};return Va.default=o,Va}var Ba={},py;function $x(){if(py)return Ba;py=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=dr(),t=je(),r=Ne(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,r.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,r._)`{pattern: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:m}=s,p=m.opts.unicodeRegExp?"u":"";if(l){const{regExp:f}=m.opts.code,g=f.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(a,f),v=a.let("valid");a.try(()=>a.assign(v,(0,r._)`${g}(${u}, ${p}).test(${i})`),()=>a.assign(v,!1)),s.fail$data((0,r._)`!${v}`)}else{const f=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${f}.test(${i})`)}}};return Ba.default=o,Ba}var Ha={},fy;function Rx(){if(fy)return Ha;fy=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=Ne(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${i} ${a}`)}};return Ha.default=r,Ha}var Ja={},hy;function Px(){if(hy)return Ja;hy=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=dr(),t=Ne(),r=je(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:m}=s,{opts:p}=m;if(!u&&i.length===0)return;const f=i.length>=p.loopRequired;if(m.allErrors?g():v(),p.strictRequired){const _=s.parentSchema.properties,{definedProperties:h}=s.it;for(const S of i)if(_?.[S]===void 0&&!h.has(S)){const k=m.schemaEnv.baseId+m.errSchemaPath,C=`required property "${S}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(m,C,m.opts.strictRequired)}}function g(){if(f||u)s.block$data(t.nil,y);else for(const _ of i)(0,e.checkReportMissingProp)(s,_)}function v(){const _=a.let("missing");if(f||u){const h=a.let("valid",!0);s.block$data(h,()=>w(_,h)),s.ok(h)}else a.if((0,e.checkMissingProp)(s,i,_)),(0,e.reportMissingProp)(s,_),a.else()}function y(){a.forOf("prop",l,_=>{s.setParams({missingProperty:_}),a.if((0,e.noPropertyInData)(a,c,_,p.ownProperties),()=>s.error())})}function w(_,h){s.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(h,(0,e.propertyInData)(a,c,_,p.ownProperties)),a.if((0,t.not)(h),()=>{s.error(),a.break()})},t.nil)}}};return Ja.default=o,Ja}var Ga={},my;function Nx(){if(my)return Ga;my=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=Ne(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${i} ${a}`)}};return Ga.default=r,Ga}var Wa={},Ka={},gy;function nu(){if(gy)return Ka;gy=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Hg();return e.code='require("ajv/dist/runtime/equal").default',Ka.default=e,Ka}var yy;function Mx(){if(yy)return Wa;yy=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=Ra(),t=Ne(),r=je(),n=nu(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,t._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:m,schemaCode:p,it:f}=a;if(!c&&!u)return;const g=i.let("valid"),v=m.items?(0,e.getSchemaTypes)(m.items):[];a.block$data(g,y,(0,t._)`${p} === false`),a.ok(g);function y(){const S=i.let("i",(0,t._)`${l}.length`),k=i.let("j");a.setParams({i:S,j:k}),i.assign(g,!0),i.if((0,t._)`${S} > 1`,()=>(w()?_:h)(S,k))}function w(){return v.length>0&&!v.some(S=>S==="object"||S==="array")}function _(S,k){const C=i.name("item"),b=(0,e.checkDataTypes)(v,C,f.opts.strictNumbers,e.DataType.Wrong),E=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${S}--;`,()=>{i.let(C,(0,t._)`${l}[${S}]`),i.if(b,(0,t._)`continue`),v.length>1&&i.if((0,t._)`typeof ${C} == "string"`,(0,t._)`${C} += "_"`),i.if((0,t._)`typeof ${E}[${C}] == "number"`,()=>{i.assign(k,(0,t._)`${E}[${C}]`),a.error(),i.assign(g,!1).break()}).code((0,t._)`${E}[${C}] = ${S}`)})}function h(S,k){const C=(0,r.useFunc)(i,n.default),b=i.name("outer");i.label(b).for((0,t._)`;${S}--;`,()=>i.for((0,t._)`${k} = ${S}; ${k}--;`,()=>i.if((0,t._)`${C}(${l}[${S}], ${l}[${k}])`,()=>{a.error(),i.assign(g,!1).break(b)})))}}};return Wa.default=s,Wa}var Ya={},_y;function Ox(){if(_y)return Ya;_y=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=Ne(),t=je(),r=nu(),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 Ya.default=o,Ya}var Qa={},vy;function Ax(){if(vy)return Qa;vy=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=Ne(),t=je(),r=nu(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:m}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=m.opts.loopEnum;let f;const g=()=>f??(f=(0,t.useFunc)(a,r.default));let v;if(p||l)v=a.let("valid"),s.block$data(v,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);v=(0,e.or)(...c.map((h,S)=>w(_,S)))}s.pass(v);function y(){a.assign(v,!1),a.forOf("v",u,_=>a.if((0,e._)`${g()}(${i}, ${_})`,()=>a.assign(v,!0).break()))}function w(_,h){const S=c[h];return typeof S=="object"&&S!==null?(0,e._)`${g()}(${i}, ${_}[${h}])`:(0,e._)`${i} === ${S}`}}};return Qa.default=o,Qa}var wy;function qx(){if(wy)return Ua;wy=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e=Sx(),t=Ix(),r=Ex(),n=$x(),o=Rx(),s=Px(),a=Nx(),i=Mx(),l=Ox(),c=Ax(),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 Ua.default=u,Ua}var Xa={},ao={},by;function ky(){if(by)return ao;by=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.validateAdditionalItems=void 0;const e=Ne(),t=je(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:a,it:i}=s,{items:l}=a;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,a){const{gen:i,schema:l,data:c,keyword:u,it:m}=s;m.items=!0;const p=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${p} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(m,l)){const g=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(g),()=>f(g)),s.ok(g)}function f(g){i.forRange("i",a.length,p,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},g),m.allErrors||i.if((0,e.not)(g),()=>i.break())})}}return ao.validateAdditionalItems=o,ao.default=n,ao}var ei={},io={},Cy;function Ty(){if(Cy)return io;Cy=1,Object.defineProperty(io,"__esModule",{value:!0}),io.validateTuple=void 0;const e=Ne(),t=je(),r=dr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:a,it:i}=s;if(Array.isArray(a))return o(s,"additionalItems",a);i.items=!0,!(0,t.alwaysValidSchema)(i,a)&&s.ok((0,r.validateArray)(s))}};function o(s,a,i=s.schema){const{gen:l,parentSchema:c,data:u,keyword:m,it:p}=s;v(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const f=l.name("valid"),g=l.const("len",(0,e._)`${u}.length`);i.forEach((y,w)=>{(0,t.alwaysValidSchema)(p,y)||(l.if((0,e._)`${g} > ${w}`,()=>s.subschema({keyword:m,schemaProp:w,dataProp:w},f)),s.ok(f))});function v(y){const{opts:w,errSchemaPath:_}=p,h=i.length,S=h===y.minItems&&(h===y.maxItems||y[a]===!1);if(w.strictTuples&&!S){const k=`"${m}" is ${h}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(p,k,w.strictTuples)}}}return io.validateTuple=o,io.default=n,io}var Sy;function Lx(){if(Sy)return ei;Sy=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Ty(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return ei.default=t,ei}var ti={},Iy;function jx(){if(Iy)return ti;Iy=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Ne(),t=je(),r=dr(),n=ky(),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 ti.default=s,ti}var ri={},xy;function Dx(){if(xy)return ri;xy=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=Ne(),t=je(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:a,parentSchema:i,data:l,it:c}=o;let u,m;const{minContains:p,maxContains:f}=i;c.opts.next?(u=p===void 0?1:p,m=f):u=1;const g=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:m}),m===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(m!==void 0&&u>m){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let h=(0,e._)`${g} >= ${u}`;m!==void 0&&(h=(0,e._)`${h} && ${g} <= ${m}`),o.pass(h);return}c.items=!0;const v=s.name("valid");m===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),m!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(v,!1),y()),o.result(v,()=>o.reset());function y(){const h=s.name("_valid"),S=s.let("count",0);w(h,()=>s.if(h,()=>_(S)))}function w(h,S){s.forRange("i",0,g,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:t.Type.Num,compositeRule:!0},h),S()})}function _(h){s.code((0,e._)`${h}++`),m===void 0?s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${h} > ${m}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0)))}}};return ri.default=n,ri}var ou={},Ey;function Ux(){return Ey||(Ey=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ne(),r=je(),n=dr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const m=c===1?"property":"properties";return(0,t.str)`must have ${m} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:m}})=>(0,t._)`{property: ${l},
86
+ missingProperty: ${m},
79
87
  depsCount: ${c},
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 _ in l){if(_==="__proto__")continue;const f=Array.isArray(l[_])?c:u;f[_]=l[_]}return[c,u]}function i(l,c=l.schema){const{gen:u,data:_,it:f}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const p in c){const v=c[p];if(v.length===0)continue;const m=(0,n.propertyInData)(u,_,p,f.opts.ownProperties);l.setParams({property:p,depsCount:v.length,deps:v.join(", ")}),f.allErrors?u.if(m,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${m} && (${(0,n.checkMissingProp)(l,v,d)})`),(0,n.reportMissingProp)(l,d),u.else())}}e.validatePropertyDeps=i;function a(l,c=l.schema){const{gen:u,data:_,keyword:f,it:d}=l,p=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(d,c[v])||(u.if((0,n.propertyInData)(u,_,v,d.opts.ownProperties),()=>{const m=l.subschema({keyword:f,schemaProp:v},p);l.mergeValidEvaluated(m,p)},()=>u.var(p,!0)),l.ok(p))}e.validateSchemaDeps=a,e.default=o})(xl)),xl}var Ds={},s2;function Hk(){if(s2)return Ds;s2=1,Object.defineProperty(Ds,"__esModule",{value:!0});const e=ye(),t=Ce(),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 Ds.default=n,Ds}var zs={},a2;function i2(){if(a2)return zs;a2=1,Object.defineProperty(zs,"__esModule",{value:!0});const e=Ot(),t=ye(),r=fr(),n=Ce(),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:_,it:f}=i;if(!_)throw new Error("ajv implementation error");const{allErrors:d,opts:p}=f;if(f.props=!0,p.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(f,l))return;const v=(0,e.allSchemaProperties)(c.properties),m=(0,e.allSchemaProperties)(c.patternProperties);w(),i.ok((0,t._)`${_} === ${r.default.errors}`);function w(){a.forIn("key",u,k=>{!v.length&&!m.length?b(k):a.if(g(k),()=>b(k))})}function g(k){let C;if(v.length>8){const I=(0,n.schemaRefOrVal)(f,c.properties,"properties");C=(0,e.isOwnProperty)(a,I,k)}else v.length?C=(0,t.or)(...v.map(I=>(0,t._)`${k} === ${I}`)):C=t.nil;return m.length&&(C=(0,t.or)(C,...m.map(I=>(0,t._)`${(0,e.usePattern)(i,I)}.test(${k})`))),(0,t.not)(C)}function y(k){a.code((0,t._)`delete ${u}[${k}]`)}function b(k){if(p.removeAdditional==="all"||p.removeAdditional&&l===!1){y(k);return}if(l===!1){i.setParams({additionalProperty:k}),i.error(),d||a.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(f,l)){const C=a.name("valid");p.removeAdditional==="failing"?(S(k,C,!1),a.if((0,t.not)(C),()=>{i.reset(),y(k)})):(S(k,C),d||a.if((0,t.not)(C),()=>a.break()))}}function S(k,C,I){const R={keyword:"additionalProperties",dataProp:k,dataPropType:n.Type.Str};I===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(R,C)}}};return zs.default=s,zs}var Zs={},l2;function Jk(){if(l2)return Zs;l2=1,Object.defineProperty(Zs,"__esModule",{value:!0});const e=ms(),t=Ot(),r=Ce(),n=i2(),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 _=(0,t.allSchemaProperties)(a);for(const m of _)u.definedProperties.add(m);u.opts.unevaluated&&_.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(i,(0,r.toHash)(_),u.props));const f=_.filter(m=>!(0,r.alwaysValidSchema)(u,a[m]));if(f.length===0)return;const d=i.name("valid");for(const m of f)p(m)?v(m):(i.if((0,t.propertyInData)(i,c,m,u.opts.ownProperties)),v(m),u.allErrors||i.else().var(d,!0),i.endIf()),s.it.definedProperties.add(m),s.ok(d);function p(m){return u.opts.useDefaults&&!u.compositeRule&&a[m].default!==void 0}function v(m){s.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}}};return Zs.default=o,Zs}var Fs={},c2;function Gk(){if(c2)return Fs;c2=1,Object.defineProperty(Fs,"__esModule",{value:!0});const e=Ot(),t=ye(),r=Ce(),n=Ce(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,data:l,parentSchema:c,it:u}=s,{opts:_}=u,f=(0,e.allSchemaProperties)(a),d=f.filter(b=>(0,r.alwaysValidSchema)(u,a[b]));if(f.length===0||d.length===f.length&&(!u.opts.unevaluated||u.props===!0))return;const p=_.strictSchema&&!_.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:m}=u;w();function w(){for(const b of f)p&&g(b),u.allErrors?y(b):(i.var(v,!0),y(b),i.if(v))}function g(b){for(const S in p)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 k=d.includes(b);k||s.subschema({keyword:"patternProperties",schemaProp:b,dataProp:S,dataPropType:n.Type.Str},v),u.opts.unevaluated&&m!==!0?i.assign((0,t._)`${m}[${S}]`,!0):!k&&!u.allErrors&&i.if((0,t.not)(v),()=>i.break())})})}}};return Fs.default=o,Fs}var Vs={},u2;function Wk(){if(u2)return Vs;u2=1,Object.defineProperty(Vs,"__esModule",{value:!0});const e=Ce(),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 Vs.default=t,Vs}var Bs={},d2;function Kk(){if(d2)return Bs;d2=1,Object.defineProperty(Bs,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ot().validateUnion,error:{message:"must match a schema in anyOf"}};return Bs.default=t,Bs}var Hs={},p2;function Yk(){if(p2)return Hs;p2=1,Object.defineProperty(Hs,"__esModule",{value:!0});const e=ye(),t=Ce(),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),_=s.let("passing",null),f=s.name("_valid");o.setParams({passing:_}),s.block(d),o.result(u,()=>o.reset(),()=>o.error(!0));function d(){c.forEach((p,v)=>{let m;(0,t.alwaysValidSchema)(l,p)?s.var(f,!0):m=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},f),v>0&&s.if((0,e._)`${f} && ${u}`).assign(u,!1).assign(_,(0,e._)`[${_}, ${v}]`).else(),s.if(f,()=>{s.assign(u,!0),s.assign(_,v),m&&o.mergeEvaluated(m,e.Name)})})}}};return Hs.default=n,Hs}var Js={},f2;function Qk(){if(f2)return Js;f2=1,Object.defineProperty(Js,"__esModule",{value:!0});const e=Ce(),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 Js.default=t,Js}var Gs={},h2;function Xk(){if(h2)return Gs;h2=1,Object.defineProperty(Gs,"__esModule",{value:!0});const e=ye(),t=Ce(),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 _=i.let("valid",!0),f=i.name("_valid");if(d(),s.reset(),c&&u){const v=i.let("ifClause");s.setParams({ifClause:v}),i.if(f,p("then",v),p("else",v))}else c?i.if(f,p("then")):i.if((0,e.not)(f),p("else"));s.pass(_,()=>s.error(!0));function d(){const v=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);s.mergeEvaluated(v)}function p(v,m){return()=>{const w=s.subschema({keyword:v},f);i.assign(_,f),s.mergeValidEvaluated(w,_),m?i.assign(m,(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 Gs.default=n,Gs}var Ws={},m2;function eC(){if(m2)return Ws;m2=1,Object.defineProperty(Ws,"__esModule",{value:!0});const e=Ce(),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 Ws.default=t,Ws}var g2;function tC(){if(g2)return qs;g2=1,Object.defineProperty(qs,"__esModule",{value:!0});const e=Qm(),t=Zk(),r=e2(),n=Fk(),o=Vk(),s=Bk(),i=Hk(),a=i2(),l=Jk(),c=Gk(),u=Wk(),_=Kk(),f=Yk(),d=Qk(),p=Xk(),v=eC();function m(w=!1){const g=[u.default,_.default,f.default,d.default,p.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 qs.default=m,qs}var Ks={},Ys={},_2;function rC(){if(_2)return Ys;_2=1,Object.defineProperty(Ys,"__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:i,$data:a,schema:l,schemaCode:c,it:u}=n,{opts:_,errSchemaPath:f,schemaEnv:d,self:p}=u;if(!_.validateFormats)return;a?v():m();function v(){const w=s.scopeValue("formats",{ref:p.formats,code:_.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(),k()));function S(){return _.strictSchema===!1?e.nil:(0,e._)`${c} && !${b}`}function k(){const C=d.$async?(0,e._)`(${g}.async ? await ${b}(${i}) : ${b}(${i}))`:(0,e._)`${b}(${i})`,I=(0,e._)`(typeof ${b} == "function" ? ${C} : ${b}.test(${i}))`;return(0,e._)`${b} && ${b} !== true && ${y} === ${o} && !${I}`}}function m(){const w=p.formats[l];if(!w){S();return}if(w===!0)return;const[g,y,b]=k(w);g===o&&n.pass(C());function S(){if(_.strictSchema===!1){p.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${f}"`}}function k(I){const R=I instanceof RegExp?(0,e.regexpCode)(I):_.code.formats?(0,e._)`${_.code.formats}${(0,e.getProperty)(l)}`:void 0,L=s.scopeValue("formats",{key:l,ref:I,code:R});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${L}.validate`]:["string",I,L]}function C(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!d.$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 Ys.default=r,Ys}var y2;function nC(){if(y2)return Ks;y2=1,Object.defineProperty(Ks,"__esModule",{value:!0});const t=[rC().default];return Ks.default=t,Ks}var Lr={},v2;function oC(){return v2||(v2=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.contentVocabulary=Lr.metadataVocabulary=void 0,Lr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Lr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Lr}var w2;function sC(){if(w2)return ws;w2=1,Object.defineProperty(ws,"__esModule",{value:!0});const e=xk(),t=zk(),r=tC(),n=nC(),o=oC(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return ws.default=s,ws}var Qs={},ro={},b2;function aC(){if(b2)return ro;b2=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(ro.DiscrError=e={})),ro}var S2;function iC(){if(S2)return Qs;S2=1,Object.defineProperty(Qs,"__esModule",{value:!0});const e=ye(),t=aC(),r=$l(),n=ys(),o=Ce(),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:_,it:f}=a,{oneOf:d}=_;if(!f.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 v=l.let("valid",!1),m=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(p)}`);l.if((0,e._)`typeof ${m} == "string"`,()=>w(),()=>a.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:p})),a.ok(v);function w(){const b=y();l.if(!1);for(const S in b)l.elseIf((0,e._)`${m} === ${S}`),l.assign(v,g(b[S]));l.else(),a.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:p}),l.endIf()}function g(b){const S=l.name("valid"),k=a.subschema({keyword:"oneOf",schemaProp:b},S);return a.mergeEvaluated(k,e.Name),S}function y(){var b;const S={},k=I(_);let C=!0;for(let O=0;O<d.length;O++){let U=d[O];if(U?.$ref&&!(0,o.schemaHasRulesButRef)(U,f.self.RULES)){const F=U.$ref;if(U=r.resolveRef.call(f.self,f.schemaEnv.root,f.baseId,F),U instanceof r.SchemaEnv&&(U=U.schema),U===void 0)throw new n.default(f.opts.uriResolver,f.baseId,F)}const D=(b=U?.properties)===null||b===void 0?void 0:b[p];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);C=C&&(k||I(U)),R(D,O)}if(!C)throw new Error(`discriminator: "${p}" must be required`);return S;function I({required:O}){return Array.isArray(O)&&O.includes(p)}function R(O,U){if(O.const)L(O.const,U);else if(O.enum)for(const D of O.enum)L(D,U);else throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`)}function L(O,U){if(typeof O!="string"||O in S)throw new Error(`discriminator: "${p}" values must be unique strings`);S[O]=U}}}};return Qs.default=i,Qs}const lC={$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 k2;function C2(){return k2||(k2=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=Ek(),n=sC(),o=iC(),s=lC,i=["/properties"],a="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,i):s;this.addMetaSchema(p,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=ms();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 _=Cl();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return _.default}});var f=ys();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})(cs,cs.exports)),cs.exports}var cC=C2();const uC=Da(cC);var Xs={exports:{}},Rl={},$2;function dC(){return $2||($2=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(O,U){return{validate:O,compare:U}}e.fullFormats={date:t(s,i),time:t(l(!0),c),"date-time":t(f(!0),d),"iso-time":t(l(),u),"iso-date-time":t(f(),p),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:k},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$/,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,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(O){return O%4===0&&(O%100!==0||O%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(O){const U=n.exec(O);if(!U)return!1;const D=+U[1],F=+U[2],ee=+U[3];return F>=1&&F<=12&&ee>=1&&ee<=(F===2&&r(D)?29:o[F])}function i(O,U){if(O&&U)return O>U?1:O<U?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(O){return function(D){const F=a.exec(D);if(!F)return!1;const ee=+F[1],ie=+F[2],se=+F[3],X=F[4],de=F[5]==="-"?-1:1,V=+(F[6]||0),P=+(F[7]||0);if(V>23||P>59||O&&!X)return!1;if(ee<=23&&ie<=59&&se<60)return!0;const Z=ie-P*de,j=ee-V*de-(Z<0?1:0);return(j===23||j===-1)&&(Z===59||Z===-1)&&se<61}}function c(O,U){if(!(O&&U))return;const D=new Date("2020-01-01T"+O).valueOf(),F=new Date("2020-01-01T"+U).valueOf();if(D&&F)return D-F}function u(O,U){if(!(O&&U))return;const D=a.exec(O),F=a.exec(U);if(D&&F)return O=D[1]+D[2]+D[3],U=F[1]+F[2]+F[3],O>U?1:O<U?-1:0}const _=/t|\s/i;function f(O){const U=l(O);return function(F){const ee=F.split(_);return ee.length===2&&s(ee[0])&&U(ee[1])}}function d(O,U){if(!(O&&U))return;const D=new Date(O).valueOf(),F=new Date(U).valueOf();if(D&&F)return D-F}function p(O,U){if(!(O&&U))return;const[D,F]=O.split(_),[ee,ie]=U.split(_),se=i(D,ee);if(se!==void 0)return se||c(F,ie)}const v=/\/|:/,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 w(O){return v.test(O)&&m.test(O)}const g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(O){return g.lastIndex=0,g.test(O)}const b=-2147483648,S=2**31-1;function k(O){return Number.isInteger(O)&&O<=S&&O>=b}function C(O){return Number.isInteger(O)}function I(){return!0}const R=/[^\\]\\Z/;function L(O){if(R.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(Rl)),Rl}var Pl={},E2;function pC(){return E2||(E2=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=C2(),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: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:_,it:f}=a,{opts:d,self:p}=f;if(!d.validateFormats)return;const v=new t.KeywordCxt(f,p.RULES.all.format.definition,"format");v.$data?m():w();function m(){const y=l.scopeValue("formats",{ref:p.formats,code:d.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=p.formats[y];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${_}": format "${y}" does not define "compare" function`);const S=l.scopeValue("formats",{key:y,ref:b,code:d.code.formats?(0,r._)`${d.code.formats}${(0,r.getProperty)(y)}`:void 0});a.fail$data(g(S))}function g(y){return(0,r._)`${y}.compare(${c}, ${u}) ${o[_].fail} 0`}},dependencies:["format"]};const i=a=>(a.addKeyword(e.formatLimitDefinition),a);e.default=i})(Pl)),Pl}var T2;function fC(){return T2||(T2=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=dC(),n=pC(),o=ye(),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[_,f]=u.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,s],d=u.formats||r.formatNames;return l(c,d,_,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,_,f){var d,p;(d=(p=c.opts.code).formats)!==null&&d!==void 0||(p.formats=(0,o._)`require("ajv-formats/dist/formats").${f}`);for(const v of u)c.addFormat(v,_[v])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a})(Xs,Xs.exports)),Xs.exports}var hC=fC();const mC=Da(hC);function gC(){const e=new uC({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return mC(e),e}class _C{constructor(t){this._ajv=t??gC()}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 yC{constructor(t){this._client=t}async*callToolStream(t,r=Kn,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 ue(_e.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 ue(_e.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ue){yield{type:"error",error:u};return}yield{type:"error",error:new ue(_e.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function vC(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 wC(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 ea(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&&ea(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&ea(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&ea(r,t)}}function bC(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 ta extends mk{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 _C,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ji,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Li,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Oi,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new yC(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=gk(this._capabilities,t)}setRequestHandler(t,r){const o=em(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(ls(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=pr(zi,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new ue(_e.InvalidParams,`Invalid elicitation request: ${g}`)}const{params:_}=u.data;_.mode=_.mode??"form";const{supportsFormMode:f,supportsUrlMode:d}=bC(this._capabilities.elicitation);if(_.mode==="form"&&!f)throw new ue(_e.InvalidParams,"Client does not support form-mode elicitation requests");if(_.mode==="url"&&!d)throw new ue(_e.InvalidParams,"Client does not support URL-mode elicitation requests");const p=await Promise.resolve(r(l,c));if(_.task){const g=pr(Gn,p);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new ue(_e.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}const v=pr(Zi,p);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new ue(_e.InvalidParams,`Invalid elicitation result: ${g}`)}const m=v.data,w=_.mode==="form"?_.requestedSchema:void 0;if(_.mode==="form"&&m.action==="accept"&&m.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{ea(w,m.content)}catch{}return m};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){const a=async(l,c)=>{const u=pr(Ui,l);if(!u.success){const m=u.error instanceof Error?u.error.message:String(u.error);throw new ue(_e.InvalidParams,`Invalid sampling request: ${m}`)}const{params:_}=u.data,f=await Promise.resolve(r(l,c));if(_.task){const m=pr(Gn,f);if(!m.success){const w=m.error instanceof Error?m.error.message:String(m.error);throw new ue(_e.InvalidParams,`Invalid task creation result: ${w}`)}return m.data}const p=_.tools||_.toolChoice?wf:Di,v=pr(p,f);if(!v.success){const m=v.error instanceof Error?v.error.message:String(v.error);throw new ue(_e.InvalidParams,`Invalid sampling result: ${m}`)}return v.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:Ho,capabilities:this._capabilities,clientInfo:this._clientInfo}},nf,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!a6.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){vC(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&wC(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Or,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},bf,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Or,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},mf,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},hf,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},uf,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},df,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},pf,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Or,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Or,r)}async callTool(t,r=Kn,n){if(this.isToolTaskRequired(t.name))throw new ue(_e.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new ue(_e.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 ue(_e.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof ue?i:new ue(_e.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},_f,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=X6.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 _=await o();l(null,_)}catch(_){const f=_ instanceof Error?_:new Error(String(_));l(f,null)}},u=()=>{if(a){const _=this._listChangedDebounceTimers.get(t);_&&clearTimeout(_);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 I2 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(x2(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(x2(this),r)}}function SC(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Ol(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Ol).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Ol(e.cause)}`:e.message:`${e}`}function x2(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var R2=e=>{throw TypeError(e)},Ml=(e,t,r)=>t.has(e)||R2("Cannot "+r),Se=(e,t,r)=>(Ml(e,t,"read from private field"),r?r.call(e):t.get(e)),Fe=(e,t,r)=>t.has(e)?R2("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Le=(e,t,r,n)=>(Ml(e,t,"write to private field"),t.set(e,r),r),Xt=(e,t,r)=>(Ml(e,t,"access private method"),r),ut,jr,un,ra,na,no,dn,oo,mr,pn,fn,hn,so,Mt,Nl,Al,ql,P2,Ll,jl,ao,Ul,Dl;class oa 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,jr),Fe(this,un),Fe(this,ra),Fe(this,na),Fe(this,no),Fe(this,dn),Fe(this,oo,null),Fe(this,mr),Fe(this,pn),Fe(this,fn,null),Fe(this,hn,null),Fe(this,so,null),Fe(this,Al,async s=>{var i;Se(this,pn).reset();const{body:a,redirected:l,status:c,headers:u}=s;if(c===204){Xt(this,Mt,ao).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Le(this,un,new URL(s.url)):Le(this,un,void 0),c!==200){Xt(this,Mt,ao).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Xt(this,Mt,ao).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Se(this,ut)===this.CLOSED)return;Le(this,ut,this.OPEN);const _=new Event("open");if((i=Se(this,so))==null||i.call(this,_),this.dispatchEvent(_),typeof a!="object"||!a||!("getReader"in a)){Xt(this,Mt,ao).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const f=new TextDecoder,d=a.getReader();let p=!0;do{const{done:v,value:m}=await d.read();m&&Se(this,pn).feed(f.decode(m,{stream:!v})),v&&(p=!1,Se(this,pn).reset(),Xt(this,Mt,Ul).call(this))}while(p)}),Fe(this,ql,s=>{Le(this,mr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Xt(this,Mt,Ul).call(this,Ol(s))}),Fe(this,Ll,s=>{typeof s.id=="string"&&Le(this,oo,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:Se(this,un)?Se(this,un).origin:Se(this,jr).origin,lastEventId:s.id||""});Se(this,hn)&&(!s.event||s.event==="message")&&Se(this,hn).call(this,i),this.dispatchEvent(i)}),Fe(this,jl,s=>{Le(this,no,s)}),Fe(this,Dl,()=>{Le(this,dn,void 0),Se(this,ut)===this.CONNECTING&&Xt(this,Mt,Nl).call(this)});try{if(t instanceof URL)Le(this,jr,t);else if(typeof t=="string")Le(this,jr,new URL(t,kC()));else throw new Error("Invalid URL")}catch{throw SC("An invalid or illegal string was specified")}Le(this,pn,ou({onEvent:Se(this,Ll),onRetry:Se(this,jl)})),Le(this,ut,this.CONNECTING),Le(this,no,3e3),Le(this,na,(n=r?.fetch)!=null?n:globalThis.fetch),Le(this,ra,(o=r?.withCredentials)!=null?o:!1),Xt(this,Mt,Nl).call(this)}get readyState(){return Se(this,ut)}get url(){return Se(this,jr).href}get withCredentials(){return Se(this,ra)}get onerror(){return Se(this,fn)}set onerror(t){Le(this,fn,t)}get onmessage(){return Se(this,hn)}set onmessage(t){Le(this,hn,t)}get onopen(){return Se(this,so)}set onopen(t){Le(this,so,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(){Se(this,dn)&&clearTimeout(Se(this,dn)),Se(this,ut)!==this.CLOSED&&(Se(this,mr)&&Se(this,mr).abort(),Le(this,ut,this.CLOSED),Le(this,mr,void 0))}}ut=new WeakMap,jr=new WeakMap,un=new WeakMap,ra=new WeakMap,na=new WeakMap,no=new WeakMap,dn=new WeakMap,oo=new WeakMap,mr=new WeakMap,pn=new WeakMap,fn=new WeakMap,hn=new WeakMap,so=new WeakMap,Mt=new WeakSet,Nl=function(){Le(this,ut,this.CONNECTING),Le(this,mr,new AbortController),Se(this,na)(Se(this,jr),Xt(this,Mt,P2).call(this)).then(Se(this,Al)).catch(Se(this,ql))},Al=new WeakMap,ql=new WeakMap,P2=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Se(this,oo)?{"Last-Event-ID":Se(this,oo)}:void 0},cache:"no-store",signal:(e=Se(this,mr))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ll=new WeakMap,jl=new WeakMap,ao=function(e,t){var r;Se(this,ut)!==this.CLOSED&&Le(this,ut,this.CLOSED);const n=new I2("error",{code:t,message:e});(r=Se(this,fn))==null||r.call(this,n),this.dispatchEvent(n)},Ul=function(e,t){var r;if(Se(this,ut)===this.CLOSED)return;Le(this,ut,this.CONNECTING);const n=new I2("error",{code:t,message:e});(r=Se(this,fn))==null||r.call(this,n),this.dispatchEvent(n),Le(this,dn,setTimeout(Se(this,Dl),Se(this,no)))},Dl=new WeakMap,oa.CONNECTING=0,oa.OPEN=1,oa.CLOSED=2;function kC(){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 CC extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class zl{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=Y0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new St("No auth provider");let t;try{t=await Mr(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 St;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=Bo(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 oa(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}=ts(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 CC(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=Pr.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 St("No auth provider");if(await Mr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new St("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}=ts(o);if(this._resourceMetadataUrl=i,this._scope=a,await Mr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new St;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 $C="mcp";class O2{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,$C),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=Pr.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 mn=Nt;(function(e,t){const r=Nt,n=Nt,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())}})(sa,-118057+3521*-35+-2099*-233);const EC=()=>{const e=Nt,t=Nt,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}},TC=(e,t,r)=>{const n=Nt,o=Nt,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 M2{constructor(t){this._port=t}async[mn(401)](){const t=mn,r=mn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const i=t;try{const a=Pr.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=Nt,l=Nt;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=mn,o=mn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class IC extends M2{constructor(t,r=EC()){const n=mn,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)](TC,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function sa(){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 sa=function(){return e},sa()}function Nt(e,t){const r=sa();return Nt=function(n,o){return n=n-(17227+1*-16844),r[n]},Nt(e,t)}(function(e,t){const r=Pe,n=Pe,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())}})(aa,-411935*1+228107+208149*2);const xC=async(e,t,r)=>{var n;const o=Pe,s=Pe,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 _={};switch(c){case a.VRyiJ:_=await t.listTools(u);break;case a.VkPYu:_=await t.callTool(u);break;case a.fgMSD:_=await t.listResources(u);break;case a[s(466)]:_=await t.listResourceTemplates(u);break;case a.sthgI:_=await t[o(455)](u);break;case s(486):_=await t.subscribeResource(u);break;case o(410):_=await t.unsubscribeResource(u);break;case a[s(461)]:_=await t[s(414)](u);break;case a[o(412)]:_=await t[o(491)](u);break;case a[o(436)]:_=await t[o(478)]();break;case a.kkNqg:_=await t.complete(u);break;case o(464):_=await t.setLoggingLevel(u?.[s(443)]);break}const f={};f.result=_,f.jsonrpc=a[s(472)],f.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](f))},RC=async(e,t,r)=>{var n;const o=Pe,s=Pe,i={};i[o(487)]=s(462),i.ypHTC="ping",i.fPExS=o(465);const a=i,{id:l,method:c,params:u}=r;let _={};switch(c){case"roots/list":const d={};d.method=c,d[s(446)]=u,_=await t[o(469)](d,kf);break;case"sampling/createMessage":const p={};p[o(481)]=c,p[o(446)]=u,_=await t.request(p,Di);break;case a[o(487)]:const v={};v.method=c,v[s(446)]=u,_=await t.request(v,Zi);break;case a.ypHTC:const m={};m.method=c,_=await t.request(m,Or);break}const f={};return f.result=_,f.jsonrpc=a.fPExS,f.id=l,await((n=e?.transport)==null?void 0:n.send(f)),_};function Pe(e,t){const r=aa();return Pe=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},Pe(e,t)}const PC=(e,t)=>{const r=Pe,n=Pe,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,_,f;const d=n,p=r,{id:v,method:m}=i;try{o[d(451)](m,o.DhPFX)?await s.call(e,i,a):await o[p(474)](xC,e,t,i)}catch(w){const{code:g,message:y,data:b}=w;try{if(g){const S={};S[p(485)]=g,S[d(422)]=y,S.data=b;const k={};k[p(448)]=S,k.jsonrpc=o[d(417)],k.id=v,await((l=e?.transport)==null?void 0:l[p(460)](k))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(S){(f=(_=e?.transport)==null?void 0:_.onerror)==null||f.call(_,S)}}}},OC=(e,t)=>{const r=Pe,n=Pe,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:_,params:f}=i;if(_!==s[c(476)]&&(s.QWYMz(_,s.UPdQt)||f?.[u(490)]))try{await t[c(445)](i)}catch(d){(l=(a=e?.[c(488)])==null?void 0:a[c(480)])==null||l.call(a,d)}}},MC=(e,t)=>async r=>{var n,o,s,i,a;const l=Pe,c=Pe,u={TJhyV:function(_,f,d,p){return _(f,d,p)},MMNTY:l(465)};try{return await u.TJhyV(RC,e,t,r)}catch(_){const{code:f,message:d,data:p}=_;try{if(f){const v={};v.code=f,v[l(422)]=d,v[c(419)]=p;const m={};m[l(448)]=v,m[l(424)]=u.MMNTY,m.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](m))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,_)}catch(v){(a=(i=e?.[l(488)])==null?void 0:i.onerror)==null||a.call(i,v)}}},NC=(e,t)=>async r=>{var n,o,s;const i=Pe,a=Pe,l={};l.xmcLM=function(f,d){return f!==d},l.xSWLt="notifications/initialized",l[i(420)]=a(453);const c=l,{method:u,params:_}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[a(420)])||_?.[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 aa(){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 aa=function(){return e},aa()}const AC=(e,t)=>async r=>{var n,o,s,i,a,l;const c=Pe,u=Pe,_={};_.kSvAZ=c(465);const f=_;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(d){const{code:p,message:v,data:m}=d;try{if(p){const w={};w.code=p,w.message=v,w.data=m;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,d)}catch(w){(l=(a=e?.[c(488)])==null?void 0:a[u(480)])==null||l.call(a,w)}}},Zl=()=>{const e=Pe,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=Pe;if(c){const _=[];for(const f of r)try{_.push(f(l,c))}catch{}for(const f of _)if(t.rgPZO(f,null))return f}else for(const _ of r)try{t[u(427)](_,l)}catch{}},o=l=>{const c=Pe,u=Pe;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=Pe,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},i=()=>{const l=Pe;r[l(430)]=-505*7+1322+2213},a={};return a.handleListener=n,a[e(447)]=o,a.removeListener=s,a.clearListener=i,a},qC=e=>{const t=Pe,r=Pe,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(423)](Zl);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)](Zl);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(Zl);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=i,e[r(426)]=a}},LC=(e,{beforeInit:t,afterInit:r}={})=>{const n=Pe,o=Pe,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(qC,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)})},jC=er;(function(e,t){const r=er,n=er,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())}})(ia,995159+-6*-266138+-1619768);const UC=()=>{const e=er,t=er,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)})},DC=e=>{const t=er,r=er,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)]("")},gr={};gr[jC(211)]=UC,gr.randomBytes=DC;function er(e,t){const r=ia();return er=function(n,o){return n=n-(-7373+7187*1+395),r[n]},er(e,t)}function ia(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return ia=function(){return e},ia()}function tr(e,t){const r=la();return tr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},tr(e,t)}const At=tr,io=tr;(function(e,t){const r=tr,n=tr,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 zC=(e,t)=>{const r=tr,n=tr,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)](PC,e,t),OC(e,t);const s=o[n(283)](MC,t,e),i=o[n(294)](AC,t,e),a=o[r(277)](NC,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)}},Fl=(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,zl)&&((i=r._eventSource)==null||i.addEventListener(n.AIICR,()=>{var a;(a=r[tr(295)])==null||a.close()})),n.Qalmc(zC,e,t)},s={};s.afterInit=o,n.Qalmc(LC,t,s)},N2=(e,t=gr[At(299)]())=>{const r=At,n=At,o={RVabx:function(u,_,f){return u(_,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,_){const f=r,d=r,p=new Headers(_?.[f(268)]||{});Object.entries(i).forEach(([m,w])=>{p.set(m,w)});const v={..._};return v.headers=p,o[d(279)](fetch,u,v)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,i.Authorization=n(256)+e),c},A2=(e,t=gr[At(299)]())=>{const r=io,n=At,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},Vl=async(e,t,r)=>{const n=At,o=At,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,St)){const l=await t();return await i[n(257)](l),await Vl(e,t,r)}else throw a}},q2=(e,t)=>{const r=io,n=io,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 ZC=async e=>{const t=io,r=At,n={GKDjq:function(R,L,O){return R(L,O)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(R){return R()},kdowC:function(R,L,O,U){return R(L,O,U)},KkViY:"sessionId"},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:_}=e,f={};f[r(305)]=l,f.requestInit=c,f.eventSourceInit=u;const d=f,p=a||gr[r(299)](),v=n[t(289)](N2,i,p);if(c){const R={...v.requestInit,...c};R[r(268)]={...v[r(280)][t(268)],...c.headers},d.requestInit=R}else d.requestInit=v[t(280)];if(u){const R={...v[t(270)],...u};d.eventSourceInit=R}else d.eventSourceInit=v[t(270)];const m={};m[t(254)]=!0;const w={};w.roots=m,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 ta(y,b),k=()=>new zl(new URL(s),d);let C=n[t(282)](k);if(l){const R=q2(l,_);C=await n[t(263)](Vl,S,R,k)}else await S.connect(C);Fl(S,o,C),C.sessionId=C[r(274)].searchParams[t(297)](n.KkViY);const I={};return I.transport=C,I.sessionId=C[r(286)],I},FC=async e=>{const t=io,r=At,n={wfHUn:function(R,L,O){return R(L,O)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(R){return R()},PdsSn:function(R,L,O,U){return R(L,O,U)}},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:_}=e,f={};f.authProvider=l,f.requestInit=c,f.reconnectionOptions=u;const d=f,p=a||gr.randomUUID(),v=n[r(272)](A2,i,p);if(c){const R={...v[t(280)],...c};R.headers={...v.requestInit[t(268)],...c.headers},d.requestInit=R}else d[r(280)]=v[r(280)];const m={};m[r(254)]=!0;const w={};w.roots=m,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 ta(y,b),k=()=>new rs(new URL(s),d);let C=n.rSiEq(k);if(l){const R=n[t(272)](q2,l,_);C=await n[t(296)](Vl,S,R,k)}else await S[t(260)](C);n.PdsSn(Fl,S,o,C);const I={};return I.transport=C,I[r(286)]=C[r(286)],I},VC=async e=>{const t=At,r=At,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,_={};_.name="mcp-socket-proxy-client",_.version=r(248);const f={};f[r(251)]=u;const d=new ta(_,f),p=a||gr[r(299)](),v=new O2(new URL(s+"?sessionId="+p+r(265)+i));await d.connect(v),n[t(259)](Fl,d,o,v);const m={};return m.transport=v,m[r(286)]=p,m},_r=qt,lo=qt;(function(e,t){const r=qt,n=qt,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())}})(ca,1297719+-42747*-22+-1289197);function qt(e,t){const r=ca();return qt=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},qt(e,t)}const BC=()=>gr.randomBytes(-8746+-382*-23);class G${constructor(t){const r=qt,n=qt,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(BC),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=qt,c=qt,u={};u[l(198)]="GET";const _=await fetch(t,u);!_.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+_[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 d=await f.json();(a=(i=this._callBackPromise).resolve)==null||a.call(i,d.code)}async[_r(191)](t,r){const n=_r,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=qt;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[_r(206)]}get[lo(190)](){return this._clientMetadata}[_r(213)](){return this[_r(197)]}[lo(218)](){return this[lo(200)]}[_r(194)](t){this._clientInformation=t}tokens(){return this[lo(210)]}saveTokens(t){const r=lo;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[_r(212)](){const t=_r,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function ca(){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 ca=function(){return e},ca()}(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())}})(ua,262*-2438+1346066*-1+2*1373311);function ua(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return ua=function(){return e},ua()}function da(e,t){var r=ua();return da=function(n,o){n=n-287;var s=r[n];return s},da(e,t)}class HC{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new ta(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 _;return await(async()=>{const{transport:d,sessionId:p}=s==="sse"?await ZC(u):s==="socket"?await VC(u):await FC(u);d.onerror=async v=>{a?.(v)},_={transport:d,sessionId:p}})(),_}const l=new URL(r);let c;if(s==="channel"&&(c=new IC(r),await this.client.connect(c)),s==="sse"){const u=N2(n,o);c=new zl(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new O2(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=A2(n,o);c=new rs(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,Kn,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(zi,t)}onCreateMessage(t){this.client.setRequestHandler(Ui,t)}onListRoots(t){this.client.setRequestHandler(Sf,t)}onToolListChanged(t){this.client.setNotificationHandler(ji,t)}onPromptListChanged(t){this.client.setNotificationHandler(Li,t)}onResourceListChanged(t){this.client.setNotificationHandler(Oi,t)}onResourceUpdated(t){this.client.setNotificationHandler(ff,t)}onLoggingMessage(t){this.client.setNotificationHandler(vf,t)}async onPagehide(t){t.persisted||(JC(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const JC=e=>e instanceof rs,L2=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]=gd({description:o,inputSchema:Pn({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}};function GC(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
88
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const m in l){if(m==="__proto__")continue;const p=Array.isArray(l[m])?c:u;p[m]=l[m]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:m,it:p}=l;if(Object.keys(c).length===0)return;const f=u.let("missing");for(const g in c){const v=c[g];if(v.length===0)continue;const y=(0,n.propertyInData)(u,m,g,p.opts.ownProperties);l.setParams({property:g,depsCount:v.length,deps:v.join(", ")}),p.allErrors?u.if(y,()=>{for(const w of v)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${y} && (${(0,n.checkMissingProp)(l,v,f)})`),(0,n.reportMissingProp)(l,f),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:m,keyword:p,it:f}=l,g=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(f,c[v])||(u.if((0,n.propertyInData)(u,m,v,f.opts.ownProperties),()=>{const y=l.subschema({keyword:p,schemaProp:v},g);l.mergeValidEvaluated(y,g)},()=>u.var(g,!0)),l.ok(g))}e.validateSchemaDeps=i,e.default=o})(ou)),ou}var ni={},$y;function zx(){if($y)return ni;$y=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=Ne(),t=je(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:a,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,a))return;const c=s.name("valid");s.forIn("key",i,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return ni.default=n,ni}var oi={},Ry;function Py(){if(Ry)return oi;Ry=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=dr(),t=Ne(),r=sn(),n=je(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,t._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:m,it:p}=a;if(!m)throw new Error("ajv implementation error");const{allErrors:f,opts:g}=p;if(p.props=!0,g.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const v=(0,e.allSchemaProperties)(c.properties),y=(0,e.allSchemaProperties)(c.patternProperties);w(),a.ok((0,t._)`${m} === ${r.default.errors}`);function w(){i.forIn("key",u,C=>{!v.length&&!y.length?S(C):i.if(_(C),()=>S(C))})}function _(C){let b;if(v.length>8){const E=(0,n.schemaRefOrVal)(p,c.properties,"properties");b=(0,e.isOwnProperty)(i,E,C)}else v.length?b=(0,t.or)(...v.map(E=>(0,t._)`${C} === ${E}`)):b=t.nil;return y.length&&(b=(0,t.or)(b,...y.map(E=>(0,t._)`${(0,e.usePattern)(a,E)}.test(${C})`))),(0,t.not)(b)}function h(C){i.code((0,t._)`delete ${u}[${C}]`)}function S(C){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){h(C);return}if(l===!1){a.setParams({additionalProperty:C}),a.error(),f||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const b=i.name("valid");g.removeAdditional==="failing"?(k(C,b,!1),i.if((0,t.not)(b),()=>{a.reset(),h(C)})):(k(C,b),f||i.if((0,t.not)(b),()=>i.break()))}}function k(C,b,E){const I={keyword:"additionalProperties",dataProp:C,dataPropType:n.Type.Str};E===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,b)}}};return oi.default=s,oi}var si={},Ny;function Fx(){if(Ny)return si;Ny=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Na(),t=dr(),r=je(),n=Py(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const m=(0,t.allSchemaProperties)(i);for(const y of m)u.definedProperties.add(y);u.opts.unevaluated&&m.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(m),u.props));const p=m.filter(y=>!(0,r.alwaysValidSchema)(u,i[y]));if(p.length===0)return;const f=a.name("valid");for(const y of p)g(y)?v(y):(a.if((0,t.propertyInData)(a,c,y,u.opts.ownProperties)),v(y),u.allErrors||a.else().var(f,!0),a.endIf()),s.it.definedProperties.add(y),s.ok(f);function g(y){return u.opts.useDefaults&&!u.compositeRule&&i[y].default!==void 0}function v(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return si.default=o,si}var ai={},My;function Vx(){if(My)return ai;My=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=dr(),t=Ne(),r=je(),n=je(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:m}=u,p=(0,e.allSchemaProperties)(i),f=p.filter(S=>(0,r.alwaysValidSchema)(u,i[S]));if(p.length===0||f.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const g=m.strictSchema&&!m.allowMatchingProperties&&c.properties,v=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:y}=u;w();function w(){for(const S of p)g&&_(S),u.allErrors?h(S):(a.var(v,!0),h(S),a.if(v))}function _(S){for(const k in g)new RegExp(S).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${S} (use allowMatchingProperties)`)}function h(S){a.forIn("key",l,k=>{a.if((0,t._)`${(0,e.usePattern)(s,S)}.test(${k})`,()=>{const C=f.includes(S);C||s.subschema({keyword:"patternProperties",schemaProp:S,dataProp:k,dataPropType:n.Type.Str},v),u.opts.unevaluated&&y!==!0?a.assign((0,t._)`${y}[${k}]`,!0):!C&&!u.allErrors&&a.if((0,t.not)(v),()=>a.break())})})}}};return ai.default=o,ai}var ii={},Oy;function Zx(){if(Oy)return ii;Oy=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=je(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return ii.default=t,ii}var li={},Ay;function Bx(){if(Ay)return li;Ay=1,Object.defineProperty(li,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dr().validateUnion,error:{message:"must match a schema in anyOf"}};return li.default=t,li}var ci={},qy;function Hx(){if(qy)return ci;qy=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Ne(),t=je(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:a,parentSchema:i,it:l}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=s.let("valid",!1),m=s.let("passing",null),p=s.name("_valid");o.setParams({passing:m}),s.block(f),o.result(u,()=>o.reset(),()=>o.error(!0));function f(){c.forEach((g,v)=>{let y;(0,t.alwaysValidSchema)(l,g)?s.var(p,!0):y=o.subschema({keyword:"oneOf",schemaProp:v,compositeRule:!0},p),v>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(m,(0,e._)`[${m}, ${v}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(m,v),y&&o.mergeEvaluated(y,e.Name)})})}}};return ci.default=n,ci}var ui={},Ly;function Jx(){if(Ly)return ui;Ly=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=je(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const a=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(s,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return ui.default=t,ui}var di={},jy;function Gx(){if(jy)return di;jy=1,Object.defineProperty(di,"__esModule",{value:!0});const e=Ne(),t=je(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:a,parentSchema:i,it:l}=s;i.then===void 0&&i.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const m=a.let("valid",!0),p=a.name("_valid");if(f(),s.reset(),c&&u){const v=a.let("ifClause");s.setParams({ifClause:v}),a.if(p,g("then",v),g("else",v))}else c?a.if(p,g("then")):a.if((0,e.not)(p),g("else"));s.pass(m,()=>s.error(!0));function f(){const v=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(v)}function g(v,y){return()=>{const w=s.subschema({keyword:v},p);a.assign(m,p),s.mergeValidEvaluated(w,m),y?a.assign(y,(0,e._)`${v}`):s.setParams({ifClause:v})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return di.default=n,di}var pi={},Dy;function Wx(){if(Dy)return pi;Dy=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=je(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return pi.default=t,pi}var Uy;function Kx(){if(Uy)return Xa;Uy=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=ky(),t=Lx(),r=Ty(),n=jx(),o=Dx(),s=Ux(),a=zx(),i=Py(),l=Fx(),c=Vx(),u=Zx(),m=Bx(),p=Hx(),f=Jx(),g=Gx(),v=Wx();function y(w=!1){const _=[u.default,m.default,p.default,f.default,g.default,v.default,a.default,i.default,s.default,l.default,c.default];return w?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return Xa.default=y,Xa}var fi={},hi={},zy;function Yx(){if(zy)return hi;zy=1,Object.defineProperty(hi,"__esModule",{value:!0});const e=Ne(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:m,errSchemaPath:p,schemaEnv:f,self:g}=u;if(!m.validateFormats)return;i?v():y();function v(){const w=s.scopeValue("formats",{ref:g.formats,code:m.code.formats}),_=s.const("fDef",(0,e._)`${w}[${c}]`),h=s.let("fType"),S=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(h,(0,e._)`${_}.type || "string"`).assign(S,(0,e._)`${_}.validate`),()=>s.assign(h,(0,e._)`"string"`).assign(S,_)),n.fail$data((0,e.or)(k(),C()));function k(){return m.strictSchema===!1?e.nil:(0,e._)`${c} && !${S}`}function C(){const b=f.$async?(0,e._)`(${_}.async ? await ${S}(${a}) : ${S}(${a}))`:(0,e._)`${S}(${a})`,E=(0,e._)`(typeof ${S} == "function" ? ${b} : ${S}.test(${a}))`;return(0,e._)`${S} && ${S} !== true && ${h} === ${o} && !${E}`}}function y(){const w=g.formats[l];if(!w){k();return}if(w===!0)return;const[_,h,S]=C(w);_===o&&n.pass(b());function k(){if(m.strictSchema===!1){g.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function C(E){const I=E instanceof RegExp?(0,e.regexpCode)(E):m.code.formats?(0,e._)`${m.code.formats}${(0,e.getProperty)(l)}`:void 0,L=s.scopeValue("formats",{key:l,ref:E,code:I});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,e._)`${L}.validate`]:["string",E,L]}function b(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!f.$async)throw new Error("async format in sync schema");return(0,e._)`await ${S}(${a})`}return typeof h=="function"?(0,e._)`${S}(${a})`:(0,e._)`${S}.test(${a})`}}}};return hi.default=r,hi}var Fy;function Qx(){if(Fy)return fi;Fy=1,Object.defineProperty(fi,"__esModule",{value:!0});const t=[Yx().default];return fi.default=t,fi}var An={},Vy;function Xx(){return Vy||(Vy=1,Object.defineProperty(An,"__esModule",{value:!0}),An.contentVocabulary=An.metadataVocabulary=void 0,An.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],An.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),An}var Zy;function e7(){if(Zy)return La;Zy=1,Object.defineProperty(La,"__esModule",{value:!0});const e=Tx(),t=qx(),r=Kx(),n=Qx(),o=Xx(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return La.default=s,La}var mi={},is={},By;function t7(){if(By)return is;By=1,Object.defineProperty(is,"__esModule",{value:!0}),is.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(is.DiscrError=e={})),is}var Hy;function r7(){if(Hy)return mi;Hy=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Ne(),t=t7(),r=eu(),n=Aa(),o=je(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:m,it:p}=i,{oneOf:f}=m;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const g=u.propertyName;if(typeof g!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!f)throw new Error("discriminator: requires oneOf keyword");const v=l.let("valid",!1),y=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(g)}`);l.if((0,e._)`typeof ${y} == "string"`,()=>w(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:g})),i.ok(v);function w(){const S=h();l.if(!1);for(const k in S)l.elseIf((0,e._)`${y} === ${k}`),l.assign(v,_(S[k]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:g}),l.endIf()}function _(S){const k=l.name("valid"),C=i.subschema({keyword:"oneOf",schemaProp:S},k);return i.mergeEvaluated(C,e.Name),k}function h(){var S;const k={},C=E(m);let b=!0;for(let M=0;M<f.length;M++){let A=f[M];if(A?.$ref&&!(0,o.schemaHasRulesButRef)(A,p.self.RULES)){const U=A.$ref;if(A=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,U),A instanceof r.SchemaEnv&&(A=A.schema),A===void 0)throw new n.default(p.opts.uriResolver,p.baseId,U)}const O=(S=A?.properties)===null||S===void 0?void 0:S[g];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${g}"`);b=b&&(C||E(A)),I(O,M)}if(!b)throw new Error(`discriminator: "${g}" must be required`);return k;function E({required:M}){return Array.isArray(M)&&M.includes(g)}function I(M,A){if(M.const)L(M.const,A);else if(M.enum)for(const O of M.enum)L(O,A);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function L(M,A){if(typeof M!="string"||M in k)throw new Error(`discriminator: "${g}" values must be unique strings`);k[M]=A}}}};return mi.default=a,mi}const n7={$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 Jy;function Gy(){return Jy||(Jy=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=bx(),n=e7(),o=r7(),s=n7,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(g=>this.addVocabulary(g)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const g=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(g,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=Na();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Ne();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var m=Xc();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return m.default}});var p=Aa();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Ia,Ia.exports)),Ia.exports}var o7=Gy();const s7=gl(o7);var gi={exports:{}},su={},Wy;function a7(){return Wy||(Wy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(M,A){return{validate:M,compare:A}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(p(!0),f),"iso-time":t(l(),u),"iso-date-time":t(p(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:L,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:h,int32:{type:"number",validate:C},int64:{type:"number",validate:b},float:{type:"number",validate:E},double:{type:"number",validate:E},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(M){return M%4===0&&(M%100!==0||M%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(M){const A=n.exec(M);if(!A)return!1;const O=+A[1],U=+A[2],G=+A[3];return U>=1&&U<=12&&G>=1&&G<=(U===2&&r(O)?29:o[U])}function a(M,A){if(M&&A)return M>A?1:M<A?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(M){return function(O){const U=i.exec(O);if(!U)return!1;const G=+U[1],H=+U[2],le=+U[3],ee=U[4],he=U[5]==="-"?-1:1,Z=+(U[6]||0),R=+(U[7]||0);if(Z>23||R>59||M&&!ee)return!1;if(G<=23&&H<=59&&le<60)return!0;const B=H-R*he,F=G-Z*he-(B<0?1:0);return(F===23||F===-1)&&(B===59||B===-1)&&le<61}}function c(M,A){if(!(M&&A))return;const O=new Date("2020-01-01T"+M).valueOf(),U=new Date("2020-01-01T"+A).valueOf();if(O&&U)return O-U}function u(M,A){if(!(M&&A))return;const O=i.exec(M),U=i.exec(A);if(O&&U)return M=O[1]+O[2]+O[3],A=U[1]+U[2]+U[3],M>A?1:M<A?-1:0}const m=/t|\s/i;function p(M){const A=l(M);return function(U){const G=U.split(m);return G.length===2&&s(G[0])&&A(G[1])}}function f(M,A){if(!(M&&A))return;const O=new Date(M).valueOf(),U=new Date(A).valueOf();if(O&&U)return O-U}function g(M,A){if(!(M&&A))return;const[O,U]=M.split(m),[G,H]=A.split(m),le=a(O,G);if(le!==void 0)return le||c(U,H)}const v=/\/|:/,y=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function w(M){return v.test(M)&&y.test(M)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function h(M){return _.lastIndex=0,_.test(M)}const S=-2147483648,k=2**31-1;function C(M){return Number.isInteger(M)&&M<=k&&M>=S}function b(M){return Number.isInteger(M)}function E(){return!0}const I=/[^\\]\\Z/;function L(M){if(I.test(M))return!1;try{return new RegExp(M),!0}catch{return!1}}})(su)),su}var au={},Ky;function i7(){return Ky||(Ky=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Gy(),r=Ne(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:m,it:p}=i,{opts:f,self:g}=p;if(!f.validateFormats)return;const v=new t.KeywordCxt(p,g.RULES.all.format.definition,"format");v.$data?y():w();function y(){const h=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),S=l.const("fmt",(0,r._)`${h}[${v.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${S} != "object"`,(0,r._)`${S} instanceof RegExp`,(0,r._)`typeof ${S}.compare != "function"`,_(S)))}function w(){const h=v.schema,S=g.formats[h];if(!S||S===!0)return;if(typeof S!="object"||S instanceof RegExp||typeof S.compare!="function")throw new Error(`"${m}": format "${h}" does not define "compare" function`);const k=l.scopeValue("formats",{key:h,ref:S,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(h)}`:void 0});i.fail$data(_(k))}function _(h){return(0,r._)`${h}.compare(${c}, ${u}) ${o[m].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(au)),au}var Yy;function l7(){return Yy||(Yy=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=a7(),n=i7(),o=Ne(),s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[m,p]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],f=u.formats||r.formatNames;return l(c,f,m,p),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,m,p){var f,g;(f=(g=c.opts.code).formats)!==null&&f!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const v of u)c.addFormat(v,m[v])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(gi,gi.exports)),gi.exports}var c7=l7();const u7=gl(c7);function d7(){const e=new s7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return u7(e),e}class p7{constructor(t){this._ajv=t??d7()}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 f7{constructor(t){this._client=t}async*callToolStream(t,r=ts,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:t},r,s),i=o.getToolOutputValidator(t.name);for await(const l of a){if(l.type==="result"&&i){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new ke(Ee.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new ke(Ee.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ke){yield{type:"error",error:u};return}yield{type:"error",error:new ke(Ee.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function h7(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 m7(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 yi(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&&yi(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&yi(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&yi(r,t)}}function g7(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 _i extends ux{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 p7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",gc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",mc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",uc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new f7(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=dx(this._capabilities,t)}setRequestHandler(t,r){const o=Tg(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Sa(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const i=async(l,c)=>{const u=on(vc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new ke(Ee.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:m}=u.data;m.mode=m.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=g7(this._capabilities.elicitation);if(m.mode==="form"&&!p)throw new ke(Ee.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!f)throw new ke(Ee.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(m.task){const _=on(Xo,g);if(!_.success){const h=_.error instanceof Error?_.error.message:String(_.error);throw new ke(Ee.InvalidParams,`Invalid task creation result: ${h}`)}return _.data}const v=on(wc,g);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new ke(Ee.InvalidParams,`Invalid elicitation result: ${_}`)}const y=v.data,w=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&y.action==="accept"&&y.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{yi(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=on(yc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new ke(Ee.InvalidParams,`Invalid sampling request: ${y}`)}const{params:m}=u.data,p=await Promise.resolve(r(l,c));if(m.task){const y=on(Xo,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new ke(Ee.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const g=m.tools||m.toolChoice?Km:_c,v=on(g,p);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new ke(Ee.InvalidParams,`Invalid sampling result: ${y}`)}return v.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:ca,capabilities:this._capabilities,clientInfo:this._clientInfo}},Om,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!MC.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){h7(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&m7(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},$n,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Ym,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},$n,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Bm,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Zm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Um,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},zm,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Fm,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},$n,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},$n,r)}async callTool(t,r=ts,n){if(this.isToolTaskRequired(t.name))throw new ke(Ee.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new ke(Ee.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new ke(Ee.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ke?a:new ke(Ee.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},Jm,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=IT.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:l}=n,c=async()=>{if(!a){l(null,null);return}try{const m=await o();l(null,m)}catch(m){const p=m instanceof Error?m:new Error(String(m));l(p,null)}},u=()=>{if(i){const m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);const p=setTimeout(c,i);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Qy 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(Xy(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(Xy(this),r)}}function y7(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function iu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(iu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${iu(e.cause)}`:e.message:`${e}`}function Xy(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var e_=e=>{throw TypeError(e)},lu=(e,t,r)=>t.has(e)||e_("Cannot "+r),Ae=(e,t,r)=>(lu(e,t,"read from private field"),r?r.call(e):t.get(e)),_t=(e,t,r)=>t.has(e)?e_("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),rt=(e,t,r,n)=>(lu(e,t,"write to private field"),t.set(e,r),r),jr=(e,t,r)=>(lu(e,t,"access private method"),r),Ft,qn,lo,vi,wi,ls,co,cs,ln,uo,po,fo,us,pr,cu,uu,du,t_,pu,fu,ds,hu,mu;class bi extends EventTarget{constructor(t,r){var n,o;super(),_t(this,pr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,_t(this,Ft),_t(this,qn),_t(this,lo),_t(this,vi),_t(this,wi),_t(this,ls),_t(this,co),_t(this,cs,null),_t(this,ln),_t(this,uo),_t(this,po,null),_t(this,fo,null),_t(this,us,null),_t(this,uu,async s=>{var a;Ae(this,uo).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){jr(this,pr,ds).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?rt(this,lo,new URL(s.url)):rt(this,lo,void 0),c!==200){jr(this,pr,ds).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){jr(this,pr,ds).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ae(this,Ft)===this.CLOSED)return;rt(this,Ft,this.OPEN);const m=new Event("open");if((a=Ae(this,us))==null||a.call(this,m),this.dispatchEvent(m),typeof i!="object"||!i||!("getReader"in i)){jr(this,pr,ds).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,f=i.getReader();let g=!0;do{const{done:v,value:y}=await f.read();y&&Ae(this,uo).feed(p.decode(y,{stream:!v})),v&&(g=!1,Ae(this,uo).reset(),jr(this,pr,hu).call(this))}while(g)}),_t(this,du,s=>{rt(this,ln,void 0),!(s.name==="AbortError"||s.type==="aborted")&&jr(this,pr,hu).call(this,iu(s))}),_t(this,pu,s=>{typeof s.id=="string"&&rt(this,cs,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:Ae(this,lo)?Ae(this,lo).origin:Ae(this,qn).origin,lastEventId:s.id||""});Ae(this,fo)&&(!s.event||s.event==="message")&&Ae(this,fo).call(this,a),this.dispatchEvent(a)}),_t(this,fu,s=>{rt(this,ls,s)}),_t(this,mu,()=>{rt(this,co,void 0),Ae(this,Ft)===this.CONNECTING&&jr(this,pr,cu).call(this)});try{if(t instanceof URL)rt(this,qn,t);else if(typeof t=="string")rt(this,qn,new URL(t,_7()));else throw new Error("Invalid URL")}catch{throw y7("An invalid or illegal string was specified")}rt(this,uo,df({onEvent:Ae(this,pu),onRetry:Ae(this,fu)})),rt(this,Ft,this.CONNECTING),rt(this,ls,3e3),rt(this,wi,(n=r?.fetch)!=null?n:globalThis.fetch),rt(this,vi,(o=r?.withCredentials)!=null?o:!1),jr(this,pr,cu).call(this)}get readyState(){return Ae(this,Ft)}get url(){return Ae(this,qn).href}get withCredentials(){return Ae(this,vi)}get onerror(){return Ae(this,po)}set onerror(t){rt(this,po,t)}get onmessage(){return Ae(this,fo)}set onmessage(t){rt(this,fo,t)}get onopen(){return Ae(this,us)}set onopen(t){rt(this,us,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(){Ae(this,co)&&clearTimeout(Ae(this,co)),Ae(this,Ft)!==this.CLOSED&&(Ae(this,ln)&&Ae(this,ln).abort(),rt(this,Ft,this.CLOSED),rt(this,ln,void 0))}}Ft=new WeakMap,qn=new WeakMap,lo=new WeakMap,vi=new WeakMap,wi=new WeakMap,ls=new WeakMap,co=new WeakMap,cs=new WeakMap,ln=new WeakMap,uo=new WeakMap,po=new WeakMap,fo=new WeakMap,us=new WeakMap,pr=new WeakSet,cu=function(){rt(this,Ft,this.CONNECTING),rt(this,ln,new AbortController),Ae(this,wi)(Ae(this,qn),jr(this,pr,t_).call(this)).then(Ae(this,uu)).catch(Ae(this,du))},uu=new WeakMap,du=new WeakMap,t_=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ae(this,cs)?{"Last-Event-ID":Ae(this,cs)}:void 0},cache:"no-store",signal:(e=Ae(this,ln))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},pu=new WeakMap,fu=new WeakMap,ds=function(e,t){var r;Ae(this,Ft)!==this.CLOSED&&rt(this,Ft,this.CLOSED);const n=new Qy("error",{code:t,message:e});(r=Ae(this,po))==null||r.call(this,n),this.dispatchEvent(n)},hu=function(e,t){var r;if(Ae(this,Ft)===this.CLOSED)return;rt(this,Ft,this.CONNECTING);const n=new Qy("error",{code:t,message:e});(r=Ae(this,po))==null||r.call(this,n),this.dispatchEvent(n),rt(this,co,setTimeout(Ae(this,mu),Ae(this,ls)))},mu=new WeakMap,bi.CONNECTING=0,bi.OPEN=1,bi.CLOSED=2;function _7(){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 v7 extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class gu{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=Em(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new rr("No auth provider");let t;try{t=await Rn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new rr;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=la(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 bi(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await t(o,{...s,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=_a(i);this._resourceMetadataUrl=l,this._scope=c}return i}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new v7(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let a;try{a=En.parse(JSON.parse(s.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new rr("No auth provider");if(await Rn(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=_a(o);if(this._resourceMetadataUrl=a,this._scope=i,await Rn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new rr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}const w7="mcp";class r_{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,w7),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=En.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 ho=fr;(function(e,t){const r=fr,n=fr,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())}})(ki,-118057+3521*-35+-2099*-233);const b7=()=>{const e=fr,t=fr,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[t(394)]=t(414),r.ktWqD=function(a,i){return a!==i},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let s=859*2+-3*-1039+-4835*1;for(;;){switch(o[s++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},k7=(e,t,r)=>{const n=fr,o=fr,s={};s.eOzBp=function(i,l){return i!==l},s.ooaJk="undefined",s[n(402)]=function(i,l){return i===l},s[n(421)]="function";const a=s;a[o(389)](typeof window,a.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&a.pTvSc(typeof e[o(423)],a[n(421)])&&e.postMessage(t,r)};class n_{constructor(t){this._port=t}async[ho(401)](){const t=ho,r=ho;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=En.parse(n.data.message);(o=this.onmessage)==null||o.call(this,i,n[a(412)][a(428)])}catch(i){const l=new Error("MessageChannel failed to parse message: "+i);(s=this[a(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,a=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,a)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,s){return o instanceof s},cDUwk:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=fr,l=fr;try{const c={};c[i(404)]=r?.[i(404)];const u={};u[i(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[i(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(a=this.onerror)==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=ho,o=ho;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class C7 extends n_{constructor(t,r=b7()){const n=ho,o={lSpBh:function(a,i,l,c){return a(i,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](k7,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function ki(){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 ki=function(){return e},ki()}function fr(e,t){const r=ki();return fr=function(n,o){return n=n-(17227+1*-16844),r[n]},fr(e,t)}(function(e,t){const r=He,n=He,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())}})(Ci,-411935*1+228107+208149*2);const T7=async(e,t,r)=>{var n;const o=He,s=He,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let m={};switch(c){case i.VRyiJ:m=await t.listTools(u);break;case i.VkPYu:m=await t.callTool(u);break;case i.fgMSD:m=await t.listResources(u);break;case i[s(466)]:m=await t.listResourceTemplates(u);break;case i.sthgI:m=await t[o(455)](u);break;case s(486):m=await t.subscribeResource(u);break;case o(410):m=await t.unsubscribeResource(u);break;case i[s(461)]:m=await t[s(414)](u);break;case i[o(412)]:m=await t[o(491)](u);break;case i[o(436)]:m=await t[o(478)]();break;case i.kkNqg:m=await t.complete(u);break;case o(464):m=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=m,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},S7=async(e,t,r)=>{var n;const o=He,s=He,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let m={};switch(c){case"roots/list":const f={};f.method=c,f[s(446)]=u,m=await t[o(469)](f,Xm);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,m=await t.request(g,_c);break;case i[o(487)]:const v={};v.method=c,v[s(446)]=u,m=await t.request(v,wc);break;case i.ypHTC:const y={};y.method=c,m=await t.request(y,$n);break}const p={};return p.result=m,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),m};function He(e,t){const r=Ci();return He=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},He(e,t)}const I7=(e,t)=>{const r=He,n=He,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,m,p;const f=n,g=r,{id:v,method:y}=a;try{o[f(451)](y,o.DhPFX)?await s.call(e,a,i):await o[g(474)](T7,e,t,a)}catch(w){const{code:_,message:h,data:S}=w;try{if(_){const k={};k[g(485)]=_,k[f(422)]=h,k.data=S;const C={};C[g(448)]=k,C.jsonrpc=o[f(417)],C.id=v,await((l=e?.transport)==null?void 0:l[g(460)](C))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(k){(p=(m=e?.transport)==null?void 0:m.onerror)==null||p.call(m,k)}}}},x7=(e,t)=>{const r=He,n=He,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:m,params:p}=a;if(m!==s[c(476)]&&(s.QWYMz(m,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(f){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,f)}}},E7=(e,t)=>async r=>{var n,o,s,a,i;const l=He,c=He,u={TJhyV:function(m,p,f,g){return m(p,f,g)},MMNTY:l(465)};try{return await u.TJhyV(S7,e,t,r)}catch(m){const{code:p,message:f,data:g}=m;try{if(p){const v={};v.code=p,v[l(422)]=f,v[c(419)]=g;const y={};y[l(448)]=v,y[l(424)]=u.MMNTY,y.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](y))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,m)}catch(v){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,v)}}},$7=(e,t)=>async r=>{var n,o,s;const a=He,i=He,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:m}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||m?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function Ci(){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 Ci=function(){return e},Ci()}const R7=(e,t)=>async r=>{var n,o,s,a,i,l;const c=He,u=He,m={};m.kSvAZ=c(465);const p=m;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(f){const{code:g,message:v,data:y}=f;try{if(g){const w={};w.code=g,w.message=v,w.data=y;const _={};_.error=w,_[u(424)]=p.kSvAZ,_.id=r.id,await((o=e?.transport)==null?void 0:o.send(_))}else(a=(s=e?.transport)==null?void 0:s[c(480)])==null||a.call(s,f)}catch(w){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,w)}}},yu=()=>{const e=He,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=He;if(c){const m=[];for(const p of r)try{m.push(p(l,c))}catch{}for(const p of m)if(t.rgPZO(p,null))return p}else for(const m of r)try{t[u(427)](m,l)}catch{}},o=l=>{const c=He,u=He;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=He,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=He;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},P7=e=>{const t=He,r=He,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](yu);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(489)](yu);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=a,e.clearRequestListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n.jsmFN(yu);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},N7=(e,{beforeInit:t,afterInit:r}={})=>{const n=He,o=He,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(P7,e),e[o(438)](i=>{const l=n;e.originalOnResponse[l(440)](e,i)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](i=>{const l=o,{method:c}=i,u=a[l(483)](c);s[l(467)](typeof u,"function")&&u(i)})},M7=Dr;(function(e,t){const r=Dr,n=Dr,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())}})(Ti,995159+-6*-266138+-1619768);const O7=()=>{const e=Dr,t=Dr,r={};r.svuxn=function(o,s){return o&s},r.ZUPdr=function(o,s){return o===s},r[e(227)]=function(o,s){return o===s},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const s=e,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?a:n[s(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},A7=e=>{const t=Dr,r=Dr,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)]("")},cn={};cn[M7(211)]=O7,cn.randomBytes=A7;function Dr(e,t){const r=Ti();return Dr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},Dr(e,t)}function Ti(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Ti=function(){return e},Ti()}function Ur(e,t){const r=Si();return Ur=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Ur(e,t)}const hr=Ur,ps=Ur;(function(e,t){const r=Ur,n=Ur,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())}})(Si,-4*308317+753182*2+658196);const q7=(e,t)=>{const r=Ur,n=Ur,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)](I7,e,t),x7(e,t);const s=o[n(283)](E7,t,e),a=o[n(294)](R7,t,e),i=o[r(277)]($7,t,e);t.addRequestListener(s),t.addResponseListener(a),t[n(287)](i),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(a),t[c(252)](i)}},_u=(e,t,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,l){return a(i,l)}},o=()=>{var a;n.QhPqi(r,gu)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[Ur(295)])==null||i.close()})),n.Qalmc(q7,e,t)},s={};s.afterInit=o,n.Qalmc(N7,t,s)},o_=(e,t=cn[hr(299)]())=>{const r=hr,n=hr,o={RVabx:function(u,m,p){return u(m,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const a=s,i={};i["sse-session-id"]=t;const l={};l.headers=i,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,m){const p=r,f=r,g=new Headers(m?.[p(268)]||{});Object.entries(a).forEach(([y,w])=>{g.set(y,w)});const v={...m};return v.headers=g,o[f(279)](fetch,u,v)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},s_=(e,t=cn[hr(299)]())=>{const r=ps,n=hr,o={};o[r(271)]="include";const s=o,a={};a["stream-session-id"]=t;const i={};i[n(268)]=a,i.credentials=s[r(271)];const l={};l.requestInit=i;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},vu=async(e,t,r)=>{const n=hr,o=hr,s={rRtFD:function(i){return i()},ToRAF:function(i,l){return i instanceof l}},a=s[n(276)](r);try{return await e[o(260)](a),a}catch(i){if(s[n(275)](i,rr)){const l=await t();return await a[n(257)](l),await vu(e,t,r)}else throw i}},a_=(e,t)=>{const r=ps,n=ps,o={};o[r(267)]=function(a,i){return a in i},o.timcZ="waitForOAuthCode",o[r(253)]=function(a,i){return a===i},o.ufiEQ=r(285),o[n(250)]=r(293);const s=o;if(s.oGmBG(s[r(258)],e))return e[n(278)];if(s[n(253)](typeof t,s.ufiEQ))return t;throw new Error(s.daYBw)};function Si(){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 Si=function(){return e},Si()}const L7=async e=>{const t=ps,r=hr,n={GKDjq:function(I,L,M){return I(L,M)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(I){return I()},kdowC:function(I,L,M,A){return I(L,M,A)},KkViY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:m}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const f=p,g=i||cn[r(299)](),v=n[t(289)](o_,a,g);if(c){const I={...v.requestInit,...c};I[r(268)]={...v[r(280)][t(268)],...c.headers},f.requestInit=I}else f.requestInit=v[t(280)];if(u){const I={...v[t(270)],...u};f.eventSourceInit=I}else f.eventSourceInit=v[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const _=w,h={};h.name=n[r(261)],h[t(288)]=n.mcbiU;const S={};S[t(251)]=_;const k=new _i(h,S),C=()=>new gu(new URL(s),f);let b=n[t(282)](C);if(l){const I=a_(l,m);b=await n[t(263)](vu,k,I,C)}else await k.connect(b);_u(k,o,b),b.sessionId=b[r(274)].searchParams[t(297)](n.KkViY);const E={};return E.transport=b,E.sessionId=b[r(286)],E},j7=async e=>{const t=ps,r=hr,n={wfHUn:function(I,L,M){return I(L,M)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(I){return I()},PdsSn:function(I,L,M,A){return I(L,M,A)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:m}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const f=p,g=i||cn.randomUUID(),v=n[r(272)](s_,a,g);if(c){const I={...v[t(280)],...c};I.headers={...v.requestInit[t(268)],...c.headers},f.requestInit=I}else f[r(280)]=v[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const _=w,h={};h.name=n[t(262)],h.version=n.omKPe;const S={};S.capabilities=_;const k=new _i(h,S),C=()=>new va(new URL(s),f);let b=n.rSiEq(C);if(l){const I=n[t(272)](a_,l,m);b=await n[t(296)](vu,k,I,C)}else await k[t(260)](b);n.PdsSn(_u,k,o,b);const E={};return E.transport=b,E[r(286)]=b[r(286)],E},D7=async e=>{const t=hr,r=hr,n={eZwNI:function(w,_,h,S){return w(_,h,S)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,m={};m.name="mcp-socket-proxy-client",m.version=r(248);const p={};p[r(251)]=u;const f=new _i(m,p),g=i||cn[r(299)](),v=new r_(new URL(s+"?sessionId="+g+r(265)+a));await f.connect(v),n[t(259)](_u,f,o,v);const y={};return y.transport=v,y[r(286)]=g,y},un=mr,fs=mr;(function(e,t){const r=mr,n=mr,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())}})(Ii,1297719+-42747*-22+-1289197);function mr(e,t){const r=Ii();return mr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},mr(e,t)}const U7=()=>cn.randomBytes(-8746+-382*-23);class zE{constructor(t){const r=mr,n=mr,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:a,redirectCallback:i,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||o.HbwOh(U7),this._redirectCallback=i||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=mr,c=mr,u={};u[l(198)]="GET";const m=await fetch(t,u);!m.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+m[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const f=await p.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,f.code)}async[un(191)](t,r){const n=un,o={};o.xAOmI="POST";const s=o,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(t,{method:s.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=mr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[un(206)]}get[fs(190)](){return this._clientMetadata}[un(213)](){return this[un(197)]}[fs(218)](){return this[fs(200)]}[un(194)](t){this._clientInformation=t}tokens(){return this[fs(210)]}saveTokens(t){const r=fs;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[un(212)](){const t=un,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function Ii(){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 Ii=function(){return e},Ii()}(function(e,t){for(var r=Ei,n=Ei,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())}})(xi,262*-2438+1346066*-1+2*1373311);function xi(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return xi=function(){return e},xi()}function Ei(e,t){var r=xi();return Ei=function(n,o){n=n-287;var s=r[n];return s},Ei(e,t)}class z7{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new _i(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:a,onError:i}=t;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:o};let m;return await(async()=>{const{transport:f,sessionId:g}=s==="sse"?await L7(u):s==="socket"?await D7(u):await j7(u);f.onerror=async v=>{i?.(v)},m={transport:f,sessionId:g}})(),m}const l=new URL(r);let c;if(s==="channel"&&(c=new C7(r),await this.client.connect(c)),s==="sse"){const u=o_(n,o);c=new gu(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new r_(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=s_(n,o);c=new va(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,ts,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(vc,t)}onCreateMessage(t){this.client.setRequestHandler(yc,t)}onListRoots(t){this.client.setRequestHandler(Qm,t)}onToolListChanged(t){this.client.setNotificationHandler(gc,t)}onPromptListChanged(t){this.client.setNotificationHandler(mc,t)}onResourceListChanged(t){this.client.setNotificationHandler(uc,t)}onResourceUpdated(t){this.client.setNotificationHandler(Vm,t)}onLoggingMessage(t){this.client.setNotificationHandler(Wm,t)}async onPagehide(t){t.persisted||(F7(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const F7=e=>e instanceof va,i_=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]=Mf({description:o,inputSchema:Qn({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function V7(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
81
89
 
82
90
  # 工具调用
83
91
 
84
92
  `;return r+=`你可以根据需要调用以下工具:
85
93
 
86
94
  `,r+=`<tools>
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)}
95
+ `,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)}
88
96
  `}),r+=`</tools>
89
97
 
90
98
  `,r+=`## 工具调用格式
@@ -111,23 +119,23 @@ ${t}:`]}}function Nh({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??vo
111
119
  `,r+=`- 必须严格按照 XML 格式调用工具
112
120
  `,r+=`- arguments 必须是有效的 JSON 格式
113
121
  `,r+=`- 如果不需要调用工具,直接给出最终答案即可
114
- `,r}function j2(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 WC={openai:Jh,deepseek:Xh};class KC{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=WC[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 rs(new URL(t.url)):"type"in t&&t.type==="extension"?r=new pk(t.sessionId):"transport"in t?r=t.transport:r=t,t.useAISdkClient??!1){const o=await o6({transport:r});return o.__transport__=r,o}else{const o=new HC({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 ns||r&&r instanceof M2)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 L2(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=GC(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.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},_=a[0]?.role==="system"?a:[u,...a];return t===di?this._chatReActStream(_,s,l,n,o):this._chatReActNonStream(_,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:d,...p}=s,m=(await w0({model:this.llm(n),messages:f,...p})).text,w={role:"assistant",content:m};l.push(w),i.push(w);const g=j2(m,r);if(!g)return this.responseMessages=i,{text:m,response:{messages:i}};const y=await this._executeReActToolCall(g.toolName,g.arguments,r),k={role:"user",content:`<tool_response>
116
- ${y.success?JSON.stringify(y.result):`工具执行失败 - ${y.error}`}
117
- </tool_response>`};l.push(k),i.push(k)}return this.responseMessages=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,d)=>{l=f,c=d});return{fullStream:new ReadableStream({async start(f){let d=[...t];const p=t[0]?.role==="system"?t[0]:null,v=p?t.slice(1):[...t];let m=0,w="";const g=s.maxImages??3;try{for(;m<o;){m++;const y=i._buildMessagesForModel(p,v,g),{tools:b,...S}=s;delete S.system,delete S.onFinish;const k=await di({...S,model:a,messages:y});let C="";for await(const X of k.fullStream)X.type==="text-delta"?(C+=X.text||"",f.enqueue({type:"text-delta",text:X.text})):X.type==="text-start"?f.enqueue({type:"text-start"}):X.type==="text-end"||f.enqueue(X);w+=C;const I={role:"assistant",content:w};v.push(I),d.push(I);const R=j2(w,r);if(!R){f.enqueue({type:"text-end"}),f.close(),i.responseMessages=d,l({messages:d});return}if(R.toolName==="computer"&&R.arguments?.action==="terminate"){f.enqueue({type:"text-end"}),f.close(),i.responseMessages=d,l({messages:d});return}const L=`react-${Date.now()}`;f.enqueue({type:"tool-input-start",id:L,toolName:R.toolName});const O=JSON.stringify(R.arguments,null,2);f.enqueue({type:"tool-input-delta",id:L,delta:O});const U=await i._executeReActToolCall(R.toolName,R.arguments,r);let D,F=U.result;if(U.success&&U.result&&typeof U.result=="object"&&U.result.screenshot){D=U.result.screenshot;const{screenshot:X,...de}=U.result;F=de}let ee="";U.success?F&&Array.isArray(F.content)&&F.content.length>0&&F.content[0].text?ee=F.content[0].text:ee=JSON.stringify(F):ee=`工具执行失败 - ${U.error}`;let ie=`<tool_response>
118
- ${ee}
119
- </tool_response>`;D&&(ie+=`
120
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),f.enqueue({type:"tool-result",toolCallId:L,result:ie});const se=D?{role:"user",content:[{type:"text",text:ie},{type:"image",image:D}]}:{role:"user",content:ie};v.push(se),d.push(se),w=""}f.enqueue({type:"text-end"}),f.close(),i.responseMessages=d,l({messages:d})}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:ii(n),...o,tools:this._tempMergeTools(o.tools)};let i=null;if(o.message&&!o.messages)i={role:"user",content:o.message},this.responseMessages.push(i),s.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const l=o.messages[o.messages.length-1];l.role==="user"&&(i=l)}const a=t(s);return a?.response?.then(l=>{const c=l.messages?.[0];i&&c?.role!=="user"&&this.responseMessages.push(i),this.responseMessages.push(...l.messages)}),a?.usage?.then(l=>{this.onUsage?.(l)}),a}async chat(t){return this._chat(w0,t)}async chatStream(t){return this._chat(di,t)}}var gn={},Bl,U2;function YC(){return U2||(U2=1,Bl=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Bl}var Hl={},yr={},D2;function Ur(){if(D2)return yr;D2=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 yr.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},yr.getSymbolTotalCodewords=function(n){return t[n]},yr.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},yr.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},yr.isKanjiModeEnabled=function(){return typeof e<"u"},yr.toSJIS=function(n){return e(n)},yr}var Jl={},z2;function Gl(){return z2||(z2=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}}})(Jl)),Jl}var Wl,Z2;function QC(){if(Z2)return Wl;Z2=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++}},Wl=e,Wl}var Kl,F2;function XC(){if(F2)return Kl;F2=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]},Kl=e,Kl}var Yl={},V2;function e$(){return V2||(V2=1,(function(e){const t=Ur().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}})(Yl)),Yl}var Ql={},B2;function t$(){if(B2)return Ql;B2=1;const e=Ur().getSymbolSize,t=7;return Ql.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Ql}var Xl={},H2;function r$(){return H2||(H2=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 _=0;_<s;_++){a=l=0,c=u=null;for(let f=0;f<s;f++){let d=o.get(_,f);d===c?a++:(a>=5&&(i+=t.N1+(a-5)),c=d,a=1),d=o.get(f,_),d===u?l++:(l>=5&&(i+=t.N1+(l-5)),u=d,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}})(Xl)),Xl}var pa={},J2;function G2(){if(J2)return pa;J2=1;const e=Gl(),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 pa.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}},pa.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}},pa}var ec={},co={},W2;function n$(){if(W2)return co;W2=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]})(),co.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},co.exp=function(n){return e[n]},co.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},co}var K2;function o$(){return K2||(K2=1,(function(e){const t=n$();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}})(ec)),ec}var tc,Y2;function s$(){if(Y2)return tc;Y2=1;const e=o$();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},tc=t,tc}var rc={},nc={},oc={},Q2;function X2(){return Q2||(Q2=1,oc.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),oc}var Vt={},e1;function t1(){if(e1)return Vt;e1=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
- ]))+`;Vt.KANJI=new RegExp(r,"g"),Vt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Vt.BYTE=new RegExp(n,"g"),Vt.NUMERIC=new RegExp(e,"g"),Vt.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Vt.testKanji=function(l){return o.test(l)},Vt.testNumeric=function(l){return s.test(l)},Vt.testAlphanumeric=function(l){return i.test(l)},Vt}var r1;function Dr(){return r1||(r1=1,(function(e){const t=X2(),r=t1();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}}})(nc)),nc}var n1;function a$(){return n1||(n1=1,(function(e){const t=Ur(),r=G2(),n=Gl(),o=Dr(),s=X2(),i=7973,a=t.getBCHDigit(i);function l(f,d,p){for(let v=1;v<=40;v++)if(d<=e.getCapacity(v,p,f))return v}function c(f,d){return o.getCharCountIndicator(f,d)+4}function u(f,d){let p=0;return f.forEach(function(v){const m=c(v.mode,d);p+=m+v.getBitsLength()}),p}function _(f,d){for(let p=1;p<=40;p++)if(u(f,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,v){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const m=t.getSymbolTotalCodewords(d),w=r.getTotalCodewordsCount(d,p),g=(m-w)*8;if(v===o.MIXED)return g;const y=g-c(v,d);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(d,p){let v;const m=n.from(p,n.M);if(Array.isArray(d)){if(d.length>1)return _(d,m);if(d.length===0)return 1;v=d[0]}else v=d;return l(v.mode,v.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)-a>=0;)p^=i<<t.getBCHDigit(p)-a;return d<<12|p}})(rc)),rc}var sc={},o1;function i$(){if(o1)return sc;o1=1;const e=Ur(),t=1335,r=21522,n=e.getBCHDigit(t);return sc.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},sc}var ac={},ic,s1;function l$(){if(s1)return ic;s1=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,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))},ic=t,ic}var lc,a1;function c$(){if(a1)return lc;a1=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 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)},lc=r,lc}var cc,i1;function u$(){if(i1)return cc;i1=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)},cc=t,cc}var uc,l1;function d$(){if(l1)return uc;l1=1;const e=Dr(),t=Ur();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)}},uc=r,uc}var dc={exports:{}},c1;function p$(){return c1||(c1=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,_,f,d,p,v,m;!a.empty();){l=a.pop(),c=l.value,_=l.cost,f=r[c]||{};for(u in f)f.hasOwnProperty(u)&&(d=f[u],p=_+d,v=i[u],m=typeof i[u]>"u",(m||v>p)&&(i[u]=p,a.push(u,p),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})(dc)),dc.exports}var u1;function f$(){return u1||(u1=1,(function(e){const t=Dr(),r=l$(),n=c$(),o=u$(),s=d$(),i=t1(),a=Ur(),l=p$();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 _(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(C,I){return C.index-I.index}).map(function(C){return{data:C.data,mode:C.mode,length:C.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 d(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 p(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 k=0;k<w.length;k++){const C=w[k],I=[];for(let R=0;R<C.length;R++){const L=C[R],O=""+k+R;I.push(O),y[O]={node:L,lastCount:0},b[O]={};for(let U=0;U<S.length;U++){const D=S[U];y[D]&&y[D].node.mode===L.mode?(b[D][O]=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][O]=f(L.length,L.mode)+4+t.getCharCountIndicator(L.mode,g))}}S=I}for(let k=0;k<S.length;k++)b[S[k]].end=0;return{map:b,table:y}}function m(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(m(b,null)):b.data&&y.push(m(b.data,b.mode)),y},[])},e.fromString=function(g,y){const b=_(g,a.isKanjiModeEnabled()),S=p(b),k=v(S,y),C=l.find_path(k.map,"start","end"),I=[];for(let R=1;R<C.length-1;R++)I.push(k.table[C[R]].node);return e.fromArray(d(I))},e.rawSplit=function(g){return e.fromArray(_(g,a.isKanjiModeEnabled()))}})(ac)),ac}var d1;function h$(){if(d1)return Hl;d1=1;const e=Ur(),t=Gl(),r=QC(),n=XC(),o=e$(),s=t$(),i=r$(),a=G2(),l=s$(),c=a$(),u=i$(),_=Dr(),f=f$();function d(k,C){const I=k.size,R=s.getPositions(C);for(let L=0;L<R.length;L++){const O=R[L][0],U=R[L][1];for(let D=-1;D<=7;D++)if(!(O+D<=-1||I<=O+D))for(let F=-1;F<=7;F++)U+F<=-1||I<=U+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?k.set(O+D,U+F,!0,!0):k.set(O+D,U+F,!1,!0))}}function p(k){const C=k.size;for(let I=8;I<C-8;I++){const R=I%2===0;k.set(I,6,R,!0),k.set(6,I,R,!0)}}function v(k,C){const I=o.getPositions(C);for(let R=0;R<I.length;R++){const L=I[R][0],O=I[R][1];for(let U=-2;U<=2;U++)for(let D=-2;D<=2;D++)U===-2||U===2||D===-2||D===2||U===0&&D===0?k.set(L+U,O+D,!0,!0):k.set(L+U,O+D,!1,!0)}}function m(k,C){const I=k.size,R=c.getEncodedBits(C);let L,O,U;for(let D=0;D<18;D++)L=Math.floor(D/3),O=D%3+I-8-3,U=(R>>D&1)===1,k.set(L,O,U,!0),k.set(O,L,U,!0)}function w(k,C,I){const R=k.size,L=u.getEncodedBits(C,I);let O,U;for(O=0;O<15;O++)U=(L>>O&1)===1,O<6?k.set(O,8,U,!0):O<8?k.set(O+1,8,U,!0):k.set(R-15+O,8,U,!0),O<8?k.set(8,R-O-1,U,!0):O<9?k.set(8,15-O-1+1,U,!0):k.set(8,15-O-1,U,!0);k.set(R-8,8,1,!0)}function g(k,C){const I=k.size;let R=-1,L=I-1,O=7,U=0;for(let D=I-1;D>0;D-=2)for(D===6&&D--;;){for(let F=0;F<2;F++)if(!k.isReserved(L,D-F)){let ee=!1;U<C.length&&(ee=(C[U]>>>O&1)===1),k.set(L,D-F,ee),O--,O===-1&&(U++,O=7)}if(L+=R,L<0||I<=L){L-=R,R=-R;break}}}function y(k,C,I){const R=new r;I.forEach(function(F){R.put(F.mode.bit,4),R.put(F.getLength(),_.getCharCountIndicator(F.mode,k)),F.write(R)});const L=e.getSymbolTotalCodewords(k),O=a.getTotalCodewordsCount(k,C),U=(L-O)*8;for(R.getLengthInBits()+4<=U&&R.put(0,4);R.getLengthInBits()%8!==0;)R.putBit(0);const D=(U-R.getLengthInBits())/8;for(let F=0;F<D;F++)R.put(F%2?17:236,8);return b(R,k,C)}function b(k,C,I){const R=e.getSymbolTotalCodewords(C),L=a.getTotalCodewordsCount(C,I),O=R-L,U=a.getBlocksCount(C,I),D=R%U,F=U-D,ee=Math.floor(R/U),ie=Math.floor(O/U),se=ie+1,X=ee-ie,de=new l(X);let V=0;const P=new Array(U),Z=new Array(U);let j=0;const T=new Uint8Array(k.buffer);for(let pe=0;pe<U;pe++){const ae=pe<F?ie:se;P[pe]=T.slice(V,V+ae),Z[pe]=de.encode(P[pe]),V+=ae,j=Math.max(j,ae)}const x=new Uint8Array(R);let E=0,B,G;for(B=0;B<j;B++)for(G=0;G<U;G++)B<P[G].length&&(x[E++]=P[G][B]);for(B=0;B<X;B++)for(G=0;G<U;G++)x[E++]=Z[G][B];return x}function S(k,C,I,R){let L;if(Array.isArray(k))L=f.fromArray(k);else if(typeof k=="string"){let ee=C;if(!ee){const ie=f.rawSplit(k);ee=c.getBestVersionForData(ie,I)}L=f.fromString(k,ee||40)}else throw new Error("Invalid data");const O=c.getBestVersionForData(L,I);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!C)C=O;else if(C<O)throw new Error(`
122
+ `,r}function l_(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 Z7={openai:R2,deepseek:Cg};class B7{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=Z7[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 va(new URL(t.url)):"type"in t&&t.type==="extension"?r=new ix(t.sessionId):"transport"in t?r=t.transport:r=t,t.useAISdkClient??!1){const o=await PC({transport:r});return o.__transport__=r,o}else{const o=new z7({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 wa||r&&r instanceof n_)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 i_(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=V7(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
123
+ ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,a=s.execute||s.call;return typeof a!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},m=i[0]?.role==="system"?i:[u,...i];return t===Vl?this._chatReActStream(m,s,l,n,o):this._chatReActNonStream(m,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(s<n)a.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return o.push(...a),o}async _chatReActNonStream(t,r,n,o,s){let a=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(i,l,u),{tools:f,...g}=s,y=(await Y0({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:y};l.push(w),a.push(w);const _=l_(y,r);if(!_)return this.responseMessages=a,{text:y,response:{messages:a}};const h=await this._executeReActToolCall(_.toolName,_.arguments,r),C={role:"user",content:`<tool_response>
124
+ ${h.success?JSON.stringify(h.result):`工具执行失败 - ${h.error}`}
125
+ </tool_response>`};l.push(C),a.push(C)}return this.responseMessages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(t,r,n,o,s){const a=this,i=this.llm(n);let l,c;const u=new Promise((p,f)=>{l=p,c=f});return{fullStream:new ReadableStream({async start(p){let f=[...t];const g=t[0]?.role==="system"?t[0]:null,v=g?t.slice(1):[...t];let y=0,w="";const _=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;y<o;){y++;const h=a._buildMessagesForModel(g,v,_),{tools:S,...k}=s;delete k.system,delete k.onFinish;const C=await Vl({...k,model:i,messages:h});let b="";for await(const H of C.fullStream)H.type==="text-delta"?(b+=H.text||"",p.enqueue({type:"text-delta",text:H.text})):H.type==="text-start"?p.enqueue({type:"text-start"}):H.type==="text-end"||H.type==="finish-step"||H.type==="finish"||H.type==="start"||H.type==="start-step"||p.enqueue(H);w+=b;const E={role:"assistant",content:w};v.push(E),f.push(E);const I=l_(w,r);if(!I){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f});return}if(I.toolName==="computer"&&I.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f});return}const L=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:L,toolName:I.toolName});const M=JSON.stringify(I.arguments,null,2);p.enqueue({type:"tool-input-delta",id:L,delta:M}),p.enqueue({type:"tool-input-end",id:L}),p.enqueue({type:"tool-call",toolCallId:L,toolName:I.toolName,input:I.arguments});const A=await a._executeReActToolCall(I.toolName,I.arguments,r);let O,U=A.result;if(A.success&&A.result&&typeof A.result=="object"&&A.result.screenshot){O=A.result.screenshot;const{screenshot:H,...le}=A.result;U=le}let G="";if(A.success){U&&Array.isArray(U.content)&&U.content.length>0&&U.content[0].text?G=U.content[0].text:G=JSON.stringify(U);let H=`<tool_response>
126
+ ${G}
127
+ </tool_response>`;O&&(H+=`
128
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:L,result:H});const le=O?{role:"user",content:[{type:"text",text:H},{type:"image",image:O}]}:{role:"user",content:H};v.push(le),f.push(le),w=""}else G=`工具执行失败 - ${A.error}`,p.enqueue({type:"tool-error",toolCallId:L,input:I.arguments,error:{message:G}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=f,l({messages:f})}catch(h){p.error(h),c(h)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:Ul(n),...o,tools:this._tempMergeTools(o.tools)};let a=null;if(o.message&&!o.messages)a={role:"user",content:o.message},this.responseMessages.push(a),s.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const l=o.messages[o.messages.length-1];l.role==="user"&&(a=l)}const i=t(s);return i?.response?.then(l=>{const c=l.messages?.[0];a&&c?.role!=="user"&&this.responseMessages.push(a),this.responseMessages.push(...l.messages)}),i}async chat(t){return this._chat(Y0,t)}async chatStream(t){return this._chat(Vl,t)}}var mo={},wu,c_;function H7(){return c_||(c_=1,wu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),wu}var bu={},dn={},u_;function Ln(){if(u_)return dn;u_=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 dn.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},dn.getSymbolTotalCodewords=function(n){return t[n]},dn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},dn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},dn.isKanjiModeEnabled=function(){return typeof e<"u"},dn.toSJIS=function(n){return e(n)},dn}var ku={},d_;function Cu(){return d_||(d_=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}}})(ku)),ku}var Tu,p_;function J7(){if(p_)return Tu;p_=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++}},Tu=e,Tu}var Su,f_;function G7(){if(f_)return Su;f_=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]},Su=e,Su}var Iu={},h_;function W7(){return h_||(h_=1,(function(e){const t=Ln().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}})(Iu)),Iu}var xu={},m_;function K7(){if(m_)return xu;m_=1;const e=Ln().getSymbolSize,t=7;return xu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},xu}var Eu={},g_;function Y7(){return g_||(g_=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,c=null,u=null;for(let m=0;m<s;m++){i=l=0,c=u=null;for(let p=0;p<s;p++){let f=o.get(m,p);f===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=f,i=1),f=o.get(p,m),f===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=f,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function r(n,o,s){switch(n){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,r(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})(Eu)),Eu}var $i={},y_;function __(){if(y_)return $i;y_=1;const e=Cu(),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 $i.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}},$i.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}},$i}var $u={},hs={},v_;function Q7(){if(v_)return hs;v_=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]})(),hs.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},hs.exp=function(n){return e[n]},hs.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},hs}var w_;function X7(){return w_||(w_=1,(function(e){const t=Q7();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}})($u)),$u}var Ru,b_;function eE(){if(b_)return Ru;b_=1;const e=X7();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},Ru=t,Ru}var Pu={},Nu={},Mu={},k_;function C_(){return k_||(k_=1,Mu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Mu}var Sr={},T_;function S_(){if(T_)return Sr;T_=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
129
+ ]))+`;Sr.KANJI=new RegExp(r,"g"),Sr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Sr.BYTE=new RegExp(n,"g"),Sr.NUMERIC=new RegExp(e,"g"),Sr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Sr.testKanji=function(l){return o.test(l)},Sr.testNumeric=function(l){return s.test(l)},Sr.testAlphanumeric=function(l){return a.test(l)},Sr}var I_;function jn(){return I_||(I_=1,(function(e){const t=C_(),r=S_();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}}})(Nu)),Nu}var x_;function tE(){return x_||(x_=1,(function(e){const t=Ln(),r=__(),n=Cu(),o=jn(),s=C_(),a=7973,i=t.getBCHDigit(a);function l(p,f,g){for(let v=1;v<=40;v++)if(f<=e.getCapacity(v,g,p))return v}function c(p,f){return o.getCharCountIndicator(p,f)+4}function u(p,f){let g=0;return p.forEach(function(v){const y=c(v.mode,f);g+=y+v.getBitsLength()}),g}function m(p,f){for(let g=1;g<=40;g++)if(u(p,g)<=e.getCapacity(g,f,o.MIXED))return g}e.from=function(f,g){return s.isValid(f)?parseInt(f,10):g},e.getCapacity=function(f,g,v){if(!s.isValid(f))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=o.BYTE);const y=t.getSymbolTotalCodewords(f),w=r.getTotalCodewordsCount(f,g),_=(y-w)*8;if(v===o.MIXED)return _;const h=_-c(v,f);switch(v){case o.NUMERIC:return Math.floor(h/10*3);case o.ALPHANUMERIC:return Math.floor(h/11*2);case o.KANJI:return Math.floor(h/13);case o.BYTE:default:return Math.floor(h/8)}},e.getBestVersionForData=function(f,g){let v;const y=n.from(g,n.M);if(Array.isArray(f)){if(f.length>1)return m(f,y);if(f.length===0)return 1;v=f[0]}else v=f;return l(v.mode,v.getLength(),y)},e.getEncodedBits=function(f){if(!s.isValid(f)||f<7)throw new Error("Invalid QR Code version");let g=f<<12;for(;t.getBCHDigit(g)-i>=0;)g^=a<<t.getBCHDigit(g)-i;return f<<12|g}})(Pu)),Pu}var Ou={},E_;function rE(){if(E_)return Ou;E_=1;const e=Ln(),t=1335,r=21522,n=e.getBCHDigit(t);return Ou.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},Ou}var Au={},qu,$_;function nE(){if($_)return qu;$_=1;const e=jn();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))},qu=t,qu}var Lu,R_;function oE(){if(R_)return Lu;R_=1;const e=jn(),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)},Lu=r,Lu}var ju,P_;function sE(){if(P_)return ju;P_=1;const e=jn();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)},ju=t,ju}var Du,N_;function aE(){if(N_)return Du;N_=1;const e=jn(),t=Ln();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
130
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},Du=r,Du}var Uu={exports:{}},M_;function iE(){return M_||(M_=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},a={};a[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,m,p,f,g,v,y;!i.empty();){l=i.pop(),c=l.value,m=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],g=m+f,v=a[u],y=typeof a[u]>"u",(y||v>g)&&(a[u]=g,i.push(u,g),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Uu)),Uu.exports}var O_;function lE(){return O_||(O_=1,(function(e){const t=jn(),r=nE(),n=oE(),o=sE(),s=aE(),a=S_(),i=Ln(),l=iE();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,_,h){const S=[];let k;for(;(k=w.exec(h))!==null;)S.push({data:k[0],index:k.index,mode:_,length:k[0].length});return S}function m(w){const _=u(a.NUMERIC,t.NUMERIC,w),h=u(a.ALPHANUMERIC,t.ALPHANUMERIC,w);let S,k;return i.isKanjiModeEnabled()?(S=u(a.BYTE,t.BYTE,w),k=u(a.KANJI,t.KANJI,w)):(S=u(a.BYTE_KANJI,t.BYTE,w),k=[]),_.concat(h,S,k).sort(function(b,E){return b.index-E.index}).map(function(b){return{data:b.data,mode:b.mode,length:b.length}})}function p(w,_){switch(_){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function f(w){return w.reduce(function(_,h){const S=_.length-1>=0?_[_.length-1]:null;return S&&S.mode===h.mode?(_[_.length-1].data+=h.data,_):(_.push(h),_)},[])}function g(w){const _=[];for(let h=0;h<w.length;h++){const S=w[h];switch(S.mode){case t.NUMERIC:_.push([S,{data:S.data,mode:t.ALPHANUMERIC,length:S.length},{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.ALPHANUMERIC:_.push([S,{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.KANJI:_.push([S,{data:S.data,mode:t.BYTE,length:c(S.data)}]);break;case t.BYTE:_.push([{data:S.data,mode:t.BYTE,length:c(S.data)}])}}return _}function v(w,_){const h={},S={start:{}};let k=["start"];for(let C=0;C<w.length;C++){const b=w[C],E=[];for(let I=0;I<b.length;I++){const L=b[I],M=""+C+I;E.push(M),h[M]={node:L,lastCount:0},S[M]={};for(let A=0;A<k.length;A++){const O=k[A];h[O]&&h[O].node.mode===L.mode?(S[O][M]=p(h[O].lastCount+L.length,L.mode)-p(h[O].lastCount,L.mode),h[O].lastCount+=L.length):(h[O]&&(h[O].lastCount=L.length),S[O][M]=p(L.length,L.mode)+4+t.getCharCountIndicator(L.mode,_))}}k=E}for(let C=0;C<k.length;C++)S[k[C]].end=0;return{map:S,table:h}}function y(w,_){let h;const S=t.getBestModeForData(w);if(h=t.from(_,S),h!==t.BYTE&&h.bit<S.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(h)+`.
131
+ Suggested mode is: `+t.toString(S));switch(h===t.KANJI&&!i.isKanjiModeEnabled()&&(h=t.BYTE),h){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(_){return _.reduce(function(h,S){return typeof S=="string"?h.push(y(S,null)):S.data&&h.push(y(S.data,S.mode)),h},[])},e.fromString=function(_,h){const S=m(_,i.isKanjiModeEnabled()),k=g(S),C=v(k,h),b=l.find_path(C.map,"start","end"),E=[];for(let I=1;I<b.length-1;I++)E.push(C.table[b[I]].node);return e.fromArray(f(E))},e.rawSplit=function(_){return e.fromArray(m(_,i.isKanjiModeEnabled()))}})(Au)),Au}var A_;function cE(){if(A_)return bu;A_=1;const e=Ln(),t=Cu(),r=J7(),n=G7(),o=W7(),s=K7(),a=Y7(),i=__(),l=eE(),c=tE(),u=rE(),m=jn(),p=lE();function f(C,b){const E=C.size,I=s.getPositions(b);for(let L=0;L<I.length;L++){const M=I[L][0],A=I[L][1];for(let O=-1;O<=7;O++)if(!(M+O<=-1||E<=M+O))for(let U=-1;U<=7;U++)A+U<=-1||E<=A+U||(O>=0&&O<=6&&(U===0||U===6)||U>=0&&U<=6&&(O===0||O===6)||O>=2&&O<=4&&U>=2&&U<=4?C.set(M+O,A+U,!0,!0):C.set(M+O,A+U,!1,!0))}}function g(C){const b=C.size;for(let E=8;E<b-8;E++){const I=E%2===0;C.set(E,6,I,!0),C.set(6,E,I,!0)}}function v(C,b){const E=o.getPositions(b);for(let I=0;I<E.length;I++){const L=E[I][0],M=E[I][1];for(let A=-2;A<=2;A++)for(let O=-2;O<=2;O++)A===-2||A===2||O===-2||O===2||A===0&&O===0?C.set(L+A,M+O,!0,!0):C.set(L+A,M+O,!1,!0)}}function y(C,b){const E=C.size,I=c.getEncodedBits(b);let L,M,A;for(let O=0;O<18;O++)L=Math.floor(O/3),M=O%3+E-8-3,A=(I>>O&1)===1,C.set(L,M,A,!0),C.set(M,L,A,!0)}function w(C,b,E){const I=C.size,L=u.getEncodedBits(b,E);let M,A;for(M=0;M<15;M++)A=(L>>M&1)===1,M<6?C.set(M,8,A,!0):M<8?C.set(M+1,8,A,!0):C.set(I-15+M,8,A,!0),M<8?C.set(8,I-M-1,A,!0):M<9?C.set(8,15-M-1+1,A,!0):C.set(8,15-M-1,A,!0);C.set(I-8,8,1,!0)}function _(C,b){const E=C.size;let I=-1,L=E-1,M=7,A=0;for(let O=E-1;O>0;O-=2)for(O===6&&O--;;){for(let U=0;U<2;U++)if(!C.isReserved(L,O-U)){let G=!1;A<b.length&&(G=(b[A]>>>M&1)===1),C.set(L,O-U,G),M--,M===-1&&(A++,M=7)}if(L+=I,L<0||E<=L){L-=I,I=-I;break}}}function h(C,b,E){const I=new r;E.forEach(function(U){I.put(U.mode.bit,4),I.put(U.getLength(),m.getCharCountIndicator(U.mode,C)),U.write(I)});const L=e.getSymbolTotalCodewords(C),M=i.getTotalCodewordsCount(C,b),A=(L-M)*8;for(I.getLengthInBits()+4<=A&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const O=(A-I.getLengthInBits())/8;for(let U=0;U<O;U++)I.put(U%2?17:236,8);return S(I,C,b)}function S(C,b,E){const I=e.getSymbolTotalCodewords(b),L=i.getTotalCodewordsCount(b,E),M=I-L,A=i.getBlocksCount(b,E),O=I%A,U=A-O,G=Math.floor(I/A),H=Math.floor(M/A),le=H+1,ee=G-H,he=new l(ee);let Z=0;const R=new Array(A),B=new Array(A);let F=0;const x=new Uint8Array(C.buffer);for(let se=0;se<A;se++){const Te=se<U?H:le;R[se]=x.slice(Z,Z+Te),B[se]=he.encode(R[se]),Z+=Te,F=Math.max(F,Te)}const N=new Uint8Array(I);let D=0,W,re;for(W=0;W<F;W++)for(re=0;re<A;re++)W<R[re].length&&(N[D++]=R[re][W]);for(W=0;W<ee;W++)for(re=0;re<A;re++)N[D++]=B[re][W];return N}function k(C,b,E,I){let L;if(Array.isArray(C))L=p.fromArray(C);else if(typeof C=="string"){let G=b;if(!G){const H=p.rawSplit(C);G=c.getBestVersionForData(H,E)}L=p.fromString(C,G||40)}else throw new Error("Invalid data");const M=c.getBestVersionForData(L,E);if(!M)throw new Error("The amount of data is too big to be stored in a QR Code");if(!b)b=M;else if(b<M)throw new Error(`
124
132
  The chosen QR Code version cannot contain this amount of data.
125
- Minimum version required to store current data is: `+O+`.
126
- `);const U=y(C,I,L),D=e.getSymbolSize(C),F=new n(D);return d(F,C),p(F),v(F,C),w(F,I,0),C>=7&&m(F,C),g(F,U),isNaN(R)&&(R=i.getBestMask(F,w.bind(null,F,I))),i.applyMask(R,F),w(F,I,R),{modules:F,version:C,errorCorrectionLevel:I,maskPattern:R,segments:L}}return Hl.create=function(C,I){if(typeof C>"u"||C==="")throw new Error("No input text");let R=t.M,L,O;return typeof I<"u"&&(R=t.from(I.errorCorrectionLevel,t.M),L=c.from(I.version),O=i.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),S(C,L,R,O)},Hl}var pc={},fc={},p1;function f1(){return p1||(p1=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,_=[s.color.light,s.color.dark];for(let f=0;f<c;f++)for(let d=0;d<c;d++){let p=(f*c+d)*4,v=s.color.light;if(f>=u&&d>=u&&f<c-u&&d<c-u){const m=Math.floor((f-u)/l),w=Math.floor((d-u)/l);v=_[a[m*i+w]?1:0]}n[p++]=v.r,n[p++]=v.g,n[p++]=v.b,n[p]=v.a}}})(fc)),fc}var h1;function m$(){return h1||(h1=1,(function(e){const t=f1();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),_=c.getContext("2d"),f=_.createImageData(u,u);return t.qrToImageData(f.data,s,l),r(_,c,u),_.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",_=l.rendererOpts||{};return c.toDataURL(u,_.quality)}})(pc)),pc}var hc={},m1;function g$(){if(m1)return hc;m1=1;const e=f1();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 _=0;_<o.length;_++){const f=Math.floor(_%s),d=Math.floor(_/s);!f&&!c&&(c=!0),o[_]?(u++,_>0&&f>0&&o[_-1]||(a+=c?r("M",f+i,.5+d+i):r("m",l,0),l=0,c=!1),f+1<s&&o[_+1]||(a+=r("h",u),u=0)):l++}return a}return hc.render=function(s,i,a){const l=e.getOptions(i),c=s.modules.size,u=s.modules.data,_=c+l.margin*2,f=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+_+"v"+_+'H0z"/>':"",d="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',p='viewBox="0 0 '+_+" "+_+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+p+' shape-rendering="crispEdges">'+f+d+`</svg>
127
- `;return typeof a=="function"&&a(null,m),m},hc}var g1;function _$(){if(g1)return gn;g1=1;const e=YC(),t=h$(),r=m$(),n=g$();function o(s,i,a,l,c){const u=[].slice.call(arguments,1),_=u.length,f=typeof u[_-1]=="function";if(!f&&!e())throw new Error("Callback required as last argument");if(f){if(_<2)throw new Error("Too few arguments provided");_===2?(c=a,a=i,i=l=void 0):_===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=i,i=void 0))}else{if(_<1)throw new Error("Too few arguments provided");return _===1?(a=i,i=l=void 0):_===2&&!i.getContext&&(l=a,a=i,i=void 0),new Promise(function(d,p){try{const v=t.create(a,l);d(s(v,i,l))}catch(v){p(v)}})}try{const d=t.create(a,l);c(null,s(d,i,l))}catch(d){c(d)}}return gn.create=t.create,gn.toCanvas=o.bind(null,r.render),gn.toDataURL=o.bind(null,r.renderToDataURL),gn.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),gn}var y$=_$();const _1=Da(y$);class y1{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 _1.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return _1.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const v$={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class w${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={...v$,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
133
+ Minimum version required to store current data is: `+M+`.
134
+ `);const A=h(b,E,L),O=e.getSymbolSize(b),U=new n(O);return f(U,b),g(U),v(U,b),w(U,E,0),b>=7&&y(U,b),_(U,A),isNaN(I)&&(I=a.getBestMask(U,w.bind(null,U,E))),a.applyMask(I,U),w(U,E,I),{modules:U,version:b,errorCorrectionLevel:E,maskPattern:I,segments:L}}return bu.create=function(b,E){if(typeof b>"u"||b==="")throw new Error("No input text");let I=t.M,L,M;return typeof E<"u"&&(I=t.from(E.errorCorrectionLevel,t.M),L=c.from(E.version),M=a.from(E.maskPattern),E.toSJISFunc&&e.setToSJISFunction(E.toSJISFunc)),k(b,L,I,M)},bu}var zu={},Fu={},q_;function L_(){return q_||(q_=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,m=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let f=0;f<c;f++){let g=(p*c+f)*4,v=s.color.light;if(p>=u&&f>=u&&p<c-u&&f<c-u){const y=Math.floor((p-u)/l),w=Math.floor((f-u)/l);v=m[i[y*a+w]?1:0]}n[g++]=v.r,n[g++]=v.g,n[g++]=v.b,n[g]=v.a}}})(Fu)),Fu}var j_;function uE(){return j_||(j_=1,(function(e){const t=L_();function r(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),m=c.getContext("2d"),p=m.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(m,c,u),m.putImageData(p,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",m=l.rendererOpts||{};return c.toDataURL(u,m.quality)}})(zu)),zu}var Vu={},D_;function dE(){if(D_)return Vu;D_=1;const e=L_();function t(o,s){const a=o.a/255,i=s+'="'+o.hex+'"';return a<1?i+" "+s+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(o,s,a){let i=o+s;return typeof a<"u"&&(i+=" "+a),i}function n(o,s,a){let i="",l=0,c=!1,u=0;for(let m=0;m<o.length;m++){const p=Math.floor(m%s),f=Math.floor(m/s);!p&&!c&&(c=!0),o[m]?(u++,m>0&&p>0&&o[m-1]||(i+=c?r("M",p+a,.5+f+a):r("m",l,0),l=0,c=!1),p+1<s&&o[m+1]||(i+=r("h",u),u=0)):l++}return i}return Vu.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,m=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+m+"v"+m+'H0z"/>':"",f="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',g='viewBox="0 0 '+m+" "+m+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+g+' shape-rendering="crispEdges">'+p+f+`</svg>
135
+ `;return typeof i=="function"&&i(null,y),y},Vu}var U_;function pE(){if(U_)return mo;U_=1;const e=H7(),t=cE(),r=uE(),n=dE();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),m=u.length,p=typeof u[m-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(m<2)throw new Error("Too few arguments provided");m===2?(c=i,i=a,a=l=void 0):m===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(m<1)throw new Error("Too few arguments provided");return m===1?(i=a,a=l=void 0):m===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(f,g){try{const v=t.create(i,l);f(s(v,a,l))}catch(v){g(v)}})}try{const f=t.create(i,l);c(null,s(f,a,l))}catch(f){c(f)}}return mo.create=t.create,mo.toCanvas=o.bind(null,r.render),mo.toDataURL=o.bind(null,r.renderToDataURL),mo.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),mo}var fE=pE();const z_=gl(fE);class F_{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 z_.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return z_.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const hE={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class mE{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={...hE,...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=`
128
136
  <div class="${this.opts.className}__arrow"></div>
129
137
  <div class="${this.opts.className}__inner">${t}</div>
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 v1="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(v1))return;const e=document.createElement("style");e.id=v1,e.textContent=`
138
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-a:i==="bottom"?c=r.bottom+o+a:i==="left"?u=r.left+s-n.width-a:i==="right"&&(u=r.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+a.width<=o-5&&t+a.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const V_="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(V_))return;const e=document.createElement("style");e.id=V_,e.textContent=`
131
139
  .tiny-remoter-native-tooltip {
132
140
  position: absolute;
133
141
  z-index: 9999;
@@ -174,7 +182,7 @@ Minimum version required to store current data is: `+O+`.
174
182
  transform: translateY(-50%);
175
183
  border-right-color: rgba(0,0,0,.75);
176
184
  }
177
- `,document.head.appendChild(e)})();const b$="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",S$="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",k$="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",C$="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",$$="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",E$="https://agent.opentiny.design/tiny-robot",T$="https://ai.opentiny.design/next-remoter",I$="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",w1=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:C$},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:b$},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:k$},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:S$}];class x${constructor(t){if(this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new w$(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||T$,remoteUrl:t.remoteUrl||E$,logoUrl:t.logoUrl||I$},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?w1(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}):w1(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
185
+ `,document.head.appendChild(e)})();const gE="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",yE="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",_E="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_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",vE="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_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",wE="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",bE="https://chat.opentiny.design",kE="https://ai.opentiny.design/next-remoter",CE="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",Z_=e=>[{action:"qr-code",show:!0,text:"扫码登录",desc:"使用手机遥控页面",icon:vE},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:gE},{action:"remote-url",show:!0,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:_E},{action:"remote-control",show:!0,text:"识别码",desc:`${e.sessionId.slice(-6)}`,know:!0,showCopyIcon:!0,icon:yE}];class TE{constructor(t){if(this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new mE(n,{content:"复制",placement:"top",trigger:"hover"})},!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||kE,remoteUrl:t.remoteUrl||bE,logoUrl:t.logoUrl||CE},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?Z_(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}):Z_(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=`
178
186
  <div class="tiny-remoter-floating-block__icon">
179
187
  <img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
180
188
  </div>
@@ -189,14 +197,14 @@ Minimum version required to store current data is: `+O+`.
189
197
  <div>
190
198
  ${r.showCopyIcon?`
191
199
  <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
192
- <img src="${$$}"/>
200
+ <img src="${wE}"/>
193
201
  </div>
194
202
  `:""}
195
203
  </div>
196
204
  </div>
197
205
  </div>
198
206
  </div>
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.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const 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()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new y1((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
207
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){const r=await new F_((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
200
208
  <div style="text-align: center; padding: 32px;">
201
209
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
202
210
  <div style="
@@ -622,4 +630,4 @@ Minimum version required to store current data is: `+O+`.
622
630
  color: white;
623
631
  }
624
632
  }
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 R$=(e={})=>new x$(e);Ht.AgentModelProvider=KC,Ht.QrCode=y1,Ht.createRemoter=R$,Ht.getAISDKTools=L2,Object.defineProperty(Ht,Symbol.toStringTag,{value:"Module"})}));
633
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const SE=(e={})=>new TE(e);$r.AgentModelProvider=B7,$r.QrCode=F_,$r.createRemoter=SE,$r.getAISDKTools=i_,Object.defineProperty($r,Symbol.toStringTag,{value:"Module"})}));