@opentiny/next-sdk 0.2.8 → 0.2.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent/AgentModelProvider.ts +10 -3
- package/agent/type.ts +3 -3
- package/dist/agent/type.d.ts +3 -0
- package/dist/index.es.dev.js +123 -25
- package/dist/index.es.js +10161 -10085
- package/dist/index.js +897 -821
- package/dist/index.umd.dev.js +123 -25
- package/dist/index.umd.js +41 -41
- package/dist/page-tools/bridge.d.ts +23 -0
- package/dist/remoter/createRemoter.d.ts +3 -2
- package/dist/webagent.dev.js +15891 -15877
- package/dist/webagent.es.dev.js +15891 -15877
- package/dist/webagent.es.js +3154 -3142
- package/dist/webagent.js +35 -35
- package/package.json +1 -1
- package/page-tools/bridge.ts +134 -0
- package/remoter/createRemoter.ts +44 -23
package/dist/webagent.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
(function(Mr,Vn){typeof exports=="object"&&typeof module<"u"?Vn(exports):typeof define=="function"&&define.amd?define(["exports"],Vn):(Mr=typeof globalThis<"u"?globalThis:Mr||self,Vn(Mr.WebAgent={}))})(this,(function(Mr){"use strict";var Vn="vercel.ai.error",
|
|
2
|
-
Error message: ${yn(r)}`,cause:r}),this[xd]=!0,this.text=t}static isInstance(t){return ge.hasMarker(t,Id)}},$d="AI_LoadAPIKeyError",Rd=`vercel.ai.error.${$d}`,
|
|
3
|
-
Error message: ${yn(r)}`,cause:r}),this[Ud]=!0,this.value=t,this.context=n}static isInstance(t){return ge.hasMarker(t,jd)}static wrap({value:t,cause:r,context:n}){var o,s,i;return ed.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&&((i=r.context)==null?void 0:i.entityId)===n?.entityId?r:new ed({value:t,cause:r,context:n})}},zd="AI_UnsupportedFunctionalityError",Fd=`vercel.ai.error.${zd}`,vv=Symbol.for(Fd),Vd,Zd,Cr=class extends(Zd=ge,Vd=vv,Zd){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:zd,message:r}),this[Vd]=!0,this.functionality=t}static isInstance(t){return ge.hasMarker(t,Fd)}};const Bd=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 Co extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Hd={};function Wr(e){return Hd}function Jd(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 wv(e,t){return typeof t=="bigint"?t.toString():t}function Fi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Vi(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 bv(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 ze(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Rs(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function To(e){return JSON.stringify(e)}const Gd=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const kv=Fi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ns(e){if(Ps(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Ps(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Cv=new Set(["string","number","symbol"]);function So(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wn(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 Tv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Sv={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 Iv(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 wn(e,{...e._zod.def,shape:r,checks:[]})}function xv(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 wn(e,{...e._zod.def,shape:r,checks:[]})}function Ev(e,t){if(!Ns(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 Rs(this,"shape",n),n},checks:[]};return wn(e,r)}function $v(e,t){return wn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Rs(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Rv(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 wn(t,{...t._zod.def,shape:o,checks:[]})}function Pv(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 wn(t,{...t._zod.def,shape:o,checks:[]})}function Io(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function bn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ms(e){return typeof e=="string"?e:e?.message}function Kr(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Ms(e.inst?._zod.def?.error?.(e))??Ms(t?.error?.(e))??Ms(r.customError?.(e))??Ms(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Bi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function xo(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Wd=(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,wv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kd=J("$ZodError",Wd),Yd=J("$ZodError",Wd,{Parent:Error});function Nv(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 Mv(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 Ov=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 Co;if(i.issues.length){const a=new(o?.Err??e)(i.issues.map(l=>Kr(l,s,Wr())));throw Gd(a,o?.callee),a}return i.value},Av=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=>Kr(l,s,Wr())));throw Gd(a,o?.callee),a}return i.value},Qd=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 Co;return s.issues.length?{success:!1,error:new(e??Kd)(s.issues.map(i=>Kr(i,o,Wr())))}:{success:!0,data:s.value}},Xd=Qd(Yd),ep=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=>Kr(i,o,Wr())))}:{success:!0,data:s.value}},qv=ep(Yd),Lv=/^[cC][^\s-]{8,}$/,jv=/^[0-9a-z]+$/,Uv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dv=/^[0-9a-vA-V]{20}$/,zv=/^[A-Za-z0-9]{27}$/,Fv=/^[a-zA-Z0-9_-]{21}$/,Vv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Zv=/^([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})$/,tp=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)$/,Bv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Hv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Jv(){return new RegExp(Hv,"u")}const Gv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wv=/^(([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})$/,Kv=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Yv=/^(([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])$/,Qv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rp=/^[A-Za-z0-9_-]*$/,Xv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,e1=/^\+(?:[0-9]){6,14}[0-9]$/,np="(?:(?:\\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])))",t1=new RegExp(`^${np}$`);function op(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 r1(e){return new RegExp(`^${op(e)}$`)}function n1(e){const t=op({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(`^${np}T(?:${n})$`)}const o1=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},s1=/^\d+$/,a1=/^-?\d+(?:\.\d+)?/i,i1=/true|false/i,l1=/null/i,c1=/^[^A-Z]*$/,u1=/^[^a-z]*$/,zt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),sp={number:"number",bigint:"bigint",object:"date"},ap=J("$ZodCheckLessThan",(e,t)=>{zt.init(e,t);const r=sp[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})}}),ip=J("$ZodCheckGreaterThan",(e,t)=>{zt.init(e,t);const r=sp[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})}}),d1=J("$ZodCheckMultipleOf",(e,t)=>{zt.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):bv(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})}}),p1=J("$ZodCheckNumberFormat",(e,t)=>{zt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Sv[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=s1)}),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})}}),f1=J("$ZodCheckMaxLength",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Vi(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=Bi(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),h1=J("$ZodCheckMinLength",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Vi(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=Bi(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),m1=J("$ZodCheckLengthEquals",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Vi(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=Bi(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})}}),Os=J("$ZodCheckStringFormat",(e,t)=>{var r,n;zt.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=()=>{})}),g1=J("$ZodCheckRegex",(e,t)=>{Os.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})}}),y1=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=c1),Os.init(e,t)}),_1=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=u1),Os.init(e,t)}),v1=J("$ZodCheckIncludes",(e,t)=>{zt.init(e,t);const r=So(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})}}),w1=J("$ZodCheckStartsWith",(e,t)=>{zt.init(e,t);const r=new RegExp(`^${So(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})}}),b1=J("$ZodCheckEndsWith",(e,t)=>{zt.init(e,t);const r=new RegExp(`.*${So(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})}}),k1=J("$ZodCheckOverwrite",(e,t)=>{zt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class C1{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
|
|
1
|
+
(function(Mr,Vn){typeof exports=="object"&&typeof module<"u"?Vn(exports):typeof define=="function"&&define.amd?define(["exports"],Vn):(Mr=typeof globalThis<"u"?globalThis:Mr||self,Vn(Mr.WebAgent={}))})(this,(function(Mr){"use strict";var Vn="vercel.ai.error",uv=Symbol.for(Vn),rd,nd,ge=class sv extends(nd=Error,rd=uv,nd){constructor({name:t,message:r,cause:n}){super(r),this[rd]=!0,this.name=t,this.cause=n}static isInstance(t){return sv.hasMarker(t,Vn)}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}},od="AI_APICallError",sd=`vercel.ai.error.${od}`,dv=Symbol.for(sd),ad,id,ot=class extends(id=ge,ad=dv,id){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:od,message:t,cause:a}),this[ad]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=i,this.isRetryable=l,this.data=c}static isInstance(t){return ge.hasMarker(t,sd)}},ld="AI_EmptyResponseBodyError",cd=`vercel.ai.error.${ld}`,pv=Symbol.for(cd),ud,dd,fv=class extends(dd=ge,ud=pv,dd){constructor({message:t="Empty response body"}={}){super({name:ld,message:t}),this[ud]=!0}static isInstance(t){return ge.hasMarker(t,cd)}};function yn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var pd="AI_InvalidArgumentError",fd=`vercel.ai.error.${pd}`,hv=Symbol.for(fd),hd,md,gd=class extends(md=ge,hd=hv,md){constructor({message:t,cause:r,argument:n}){super({name:pd,message:t,cause:r}),this[hd]=!0,this.argument=n}static isInstance(t){return ge.hasMarker(t,fd)}},yd="AI_InvalidPromptError",_d=`vercel.ai.error.${yd}`,mv=Symbol.for(_d),vd,wd,_n=class extends(wd=ge,vd=mv,wd){constructor({prompt:e,message:t,cause:r}){super({name:yd,message:`Invalid prompt: ${t}`,cause:r}),this[vd]=!0,this.prompt=e}static isInstance(e){return ge.hasMarker(e,_d)}},bd="AI_InvalidResponseDataError",kd=`vercel.ai.error.${bd}`,gv=Symbol.for(kd),Cd,Td,Fi=class extends(Td=ge,Cd=gv,Td){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:bd,message:r}),this[Cd]=!0,this.data=t}static isInstance(t){return ge.hasMarker(t,kd)}},Sd="AI_JSONParseError",Id=`vercel.ai.error.${Sd}`,yv=Symbol.for(Id),xd,Ed,Es=class extends(Ed=ge,xd=yv,Ed){constructor({text:t,cause:r}){super({name:Sd,message:`JSON parsing failed: Text: ${t}.
|
|
2
|
+
Error message: ${yn(r)}`,cause:r}),this[xd]=!0,this.text=t}static isInstance(t){return ge.hasMarker(t,Id)}},$d="AI_LoadAPIKeyError",Rd=`vercel.ai.error.${$d}`,_v=Symbol.for(Rd),Pd,Nd,$s=class extends(Nd=ge,Pd=_v,Nd){constructor({message:t}){super({name:$d,message:t}),this[Pd]=!0}static isInstance(t){return ge.hasMarker(t,Rd)}},Md="AI_TooManyEmbeddingValuesForCallError",Od=`vercel.ai.error.${Md}`,vv=Symbol.for(Od),Ad,qd,wv=class extends(qd=ge,Ad=vv,qd){constructor(e){super({name:Md,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[Ad]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ge.hasMarker(e,Od)}},Ld="AI_TypeValidationError",jd=`vercel.ai.error.${Ld}`,bv=Symbol.for(jd),Ud,Dd,vn=class ed extends(Dd=ge,Ud=bv,Dd){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:Ld,message:`${o}: Value: ${JSON.stringify(t)}.
|
|
3
|
+
Error message: ${yn(r)}`,cause:r}),this[Ud]=!0,this.value=t,this.context=n}static isInstance(t){return ge.hasMarker(t,jd)}static wrap({value:t,cause:r,context:n}){var o,s,i;return ed.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&&((i=r.context)==null?void 0:i.entityId)===n?.entityId?r:new ed({value:t,cause:r,context:n})}},zd="AI_UnsupportedFunctionalityError",Fd=`vercel.ai.error.${zd}`,kv=Symbol.for(Fd),Vd,Zd,Cr=class extends(Zd=ge,Vd=kv,Zd){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:zd,message:r}),this[Vd]=!0,this.functionality=t}static isInstance(t){return ge.hasMarker(t,Fd)}};const Bd=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 Co extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Hd={};function Wr(e){return Hd}function Jd(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 Cv(e,t){return typeof t=="bigint"?t.toString():t}function Vi(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Zi(e){return e==null}function Bi(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Tv(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 ze(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Rs(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function To(e){return JSON.stringify(e)}const Gd=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Sv=Vi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ns(e){if(Ps(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Ps(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const Iv=new Set(["string","number","symbol"]);function So(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wn(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 xv(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Ev={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 $v(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 wn(e,{...e._zod.def,shape:r,checks:[]})}function Rv(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 wn(e,{...e._zod.def,shape:r,checks:[]})}function Pv(e,t){if(!Ns(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 Rs(this,"shape",n),n},checks:[]};return wn(e,r)}function Nv(e,t){return wn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Rs(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Mv(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 wn(t,{...t._zod.def,shape:o,checks:[]})}function Ov(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 wn(t,{...t._zod.def,shape:o,checks:[]})}function Io(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function bn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ms(e){return typeof e=="string"?e:e?.message}function Kr(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Ms(e.inst?._zod.def?.error?.(e))??Ms(t?.error?.(e))??Ms(r.customError?.(e))??Ms(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Hi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function xo(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Wd=(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,Cv,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kd=J("$ZodError",Wd),Yd=J("$ZodError",Wd,{Parent:Error});function Av(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function qv(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 Lv=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 Co;if(i.issues.length){const a=new(o?.Err??e)(i.issues.map(l=>Kr(l,s,Wr())));throw Gd(a,o?.callee),a}return i.value},jv=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=>Kr(l,s,Wr())));throw Gd(a,o?.callee),a}return i.value},Qd=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 Co;return s.issues.length?{success:!1,error:new(e??Kd)(s.issues.map(i=>Kr(i,o,Wr())))}:{success:!0,data:s.value}},Xd=Qd(Yd),ep=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=>Kr(i,o,Wr())))}:{success:!0,data:s.value}},Uv=ep(Yd),Dv=/^[cC][^\s-]{8,}$/,zv=/^[0-9a-z]+$/,Fv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Vv=/^[0-9a-vA-V]{20}$/,Zv=/^[A-Za-z0-9]{27}$/,Bv=/^[a-zA-Z0-9_-]{21}$/,Hv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Jv=/^([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})$/,tp=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)$/,Gv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Wv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Kv(){return new RegExp(Wv,"u")}const Yv=/^(?:(?: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])$/,Qv=/^(([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})$/,Xv=/^((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])$/,e1=/^(([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])$/,t1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rp=/^[A-Za-z0-9_-]*$/,r1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,n1=/^\+(?:[0-9]){6,14}[0-9]$/,np="(?:(?:\\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])))",o1=new RegExp(`^${np}$`);function op(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 s1(e){return new RegExp(`^${op(e)}$`)}function a1(e){const t=op({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(`^${np}T(?:${n})$`)}const i1=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},l1=/^\d+$/,c1=/^-?\d+(?:\.\d+)?/i,u1=/true|false/i,d1=/null/i,p1=/^[^A-Z]*$/,f1=/^[^a-z]*$/,zt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),sp={number:"number",bigint:"bigint",object:"date"},ap=J("$ZodCheckLessThan",(e,t)=>{zt.init(e,t);const r=sp[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})}}),ip=J("$ZodCheckGreaterThan",(e,t)=>{zt.init(e,t);const r=sp[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})}}),h1=J("$ZodCheckMultipleOf",(e,t)=>{zt.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):Tv(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})}}),m1=J("$ZodCheckNumberFormat",(e,t)=>{zt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Ev[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=l1)}),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})}}),g1=J("$ZodCheckMaxLength",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Zi(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const i=Hi(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),y1=J("$ZodCheckMinLength",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Zi(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const i=Hi(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),_1=J("$ZodCheckLengthEquals",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Zi(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const i=Hi(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})}}),Os=J("$ZodCheckStringFormat",(e,t)=>{var r,n;zt.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=()=>{})}),v1=J("$ZodCheckRegex",(e,t)=>{Os.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})}}),w1=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=p1),Os.init(e,t)}),b1=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=f1),Os.init(e,t)}),k1=J("$ZodCheckIncludes",(e,t)=>{zt.init(e,t);const r=So(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})}}),C1=J("$ZodCheckStartsWith",(e,t)=>{zt.init(e,t);const r=new RegExp(`^${So(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})}}),T1=J("$ZodCheckEndsWith",(e,t)=>{zt.init(e,t);const r=new RegExp(`.*${So(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})}}),S1=J("$ZodCheckOverwrite",(e,t)=>{zt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class I1{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
|
|
4
4
|
`).filter(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(`
|
|
5
|
-
`))}}const
|
|
5
|
+
`))}}const x1={major:4,minor:0,patch:0},We=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=x1;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=Io(s),c;for(const u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const m=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Co;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==m&&(l||(l=Io(s,m)))});else{if(s.issues.length===m)continue;l||(l=Io(s,m))}}return c?c.then(()=>s):s};e._zod.run=(s,i)=>{const a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Co;return a.then(l=>o(l,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{const s=Xd(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Uv(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ji=J("$ZodString",(e,t)=>{We.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??i1(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}}),Xe=J("$ZodStringFormat",(e,t)=>{Os.init(e,t),Ji.init(e,t)}),E1=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Jv),Xe.init(e,t)}),$1=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=tp(n))}else t.pattern??(t.pattern=tp());Xe.init(e,t)}),R1=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Gv),Xe.init(e,t)}),P1=J("$ZodURL",(e,t)=>{Xe.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:r1.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),N1=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Kv()),Xe.init(e,t)}),M1=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Bv),Xe.init(e,t)}),O1=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Dv),Xe.init(e,t)}),A1=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=zv),Xe.init(e,t)}),q1=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Fv),Xe.init(e,t)}),L1=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Vv),Xe.init(e,t)}),j1=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Zv),Xe.init(e,t)}),U1=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=a1(t)),Xe.init(e,t)}),D1=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=o1),Xe.init(e,t)}),z1=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=s1(t)),Xe.init(e,t)}),F1=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Hv),Xe.init(e,t)}),V1=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Yv),Xe.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),Z1=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Qv),Xe.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})}}}),B1=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Xv),Xe.init(e,t)}),H1=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=e1),Xe.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 lp(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const J1=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=t1),Xe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{lp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function G1(e){if(!rp.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return lp(r)}const W1=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=rp),Xe.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{G1(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),K1=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=n1),Xe.init(e,t)});function Y1(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 Q1=J("$ZodJWT",(e,t)=>{Xe.init(e,t),e._zod.check=r=>{Y1(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),cp=J("$ZodNumber",(e,t)=>{We.init(e,t),e._zod.pattern=e._zod.bag.pattern??c1,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}}),X1=J("$ZodNumber",(e,t)=>{m1.init(e,t),cp.init(e,t)}),ew=J("$ZodBoolean",(e,t)=>{We.init(e,t),e._zod.pattern=u1,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}}),tw=J("$ZodNull",(e,t)=>{We.init(e,t),e._zod.pattern=d1,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}}),rw=J("$ZodAny",(e,t)=>{We.init(e,t),e._zod.parse=r=>r}),nw=J("$ZodUnknown",(e,t)=>{We.init(e,t),e._zod.parse=r=>r}),ow=J("$ZodNever",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function up(e,t,r){e.issues.length&&t.issues.push(...bn(r,e.issues)),t.value[r]=e.value}const sw=J("$ZodArray",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let 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=>up(c,r,i))):up(l,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function As(e,t,r){e.issues.length&&t.issues.push(...bn(r,e.issues)),t.value[r]=e.value}function dp(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(...bn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const aw=J("$ZodObject",(e,t)=>{We.init(e,t);const r=Vi(()=>{const m=Object.keys(t.shape);for(const f of m)if(!(t.shape[f]instanceof We))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);const p=xv(t.shape);return{shape:t.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set(p)}});ze(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 I1(["shape","payload","ctx"]),f=r.value,g=_=>{const h=To(_);return`shape[${h}]._zod.run({ value: input[${h}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const _ of f.keys)v[_]=`key_${y++}`;p.write("const newResult = {}");for(const _ of f.keys)if(f.optionalKeys.has(_)){const h=v[_];p.write(`const ${h} = ${g(_)};`);const T=To(_);p.write(`
|
|
6
6
|
if (${h}.issues.length) {
|
|
7
7
|
if (input[${T}] === undefined) {
|
|
8
8
|
if (${T} in input) {
|
|
@@ -25,17 +25,17 @@ Error message: ${yn(r)}`,cause:r}),this[Ud]=!0,this.value=t,this.context=n}stati
|
|
|
25
25
|
if (${h}.issues.length) payload.issues = payload.issues.concat(${h}.issues.map(iss => ({
|
|
26
26
|
...iss,
|
|
27
27
|
path: iss.path ? [${To(_)}, ...iss.path] : [${To(_)}]
|
|
28
|
-
})));`),p.write(`newResult[${To(_)}] = ${h}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(_,h)=>w(m,_,h)};let o;const s=Ps,i=!Hd.jitless,l=i&&kv.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(i&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),m=o(m,p);else{m.value={};const h=u.shape;for(const T of u.keys){const b=h[T],k=b._zod.run({value:f[T],issues:[]},p),S=b._zod.optin==="optional"&&b._zod.optout==="optional";k instanceof Promise?g.push(k.then(I=>S?dp(I,m,T,f):As(I,m,T))):S?dp(k,m,T,f):As(k,m,T)}}if(!c)return g.length?Promise.all(g).then(()=>m):m;const v=[],y=u.keySet,w=c._zod,_=w.def.type;for(const h of Object.keys(f)){if(y.has(h))continue;if(_==="never"){v.push(h);continue}const T=w.run({value:f[h],issues:[]},p);T instanceof Promise?g.push(T.then(b=>As(b,m,h))):As(T,m,h)}return v.length&&m.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),g.length?Promise.all(g).then(()=>m):m}});function pp(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=>Kr(s,n,Wr())))}),t}const fp=J("$ZodUnion",(e,t)=>{We.init(e,t),ze(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ze(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ze(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ze(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Zi(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=>pp(i,r,e,n)):pp(s,r,e,n)}}),ow=J("$ZodDiscriminatedUnion",(e,t)=>{fp.init(e,t);const r=e._zod.parse;ze(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=Fi(()=>{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(!Ps(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)}}),sw=J("$ZodIntersection",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>hp(r,l,c)):hp(r,s,i)}});function Ji(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(Ns(e)&&Ns(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=Ji(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=Ji(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 hp(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Io(e))return e;const n=Ji(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 aw=J("$ZodRecord",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Ns(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(...bn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...bn(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=>Kr(c,n,Wr())),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(...bn(i,c.issues)),r.value[a.value]=c.value})):(l.issues.length&&r.issues.push(...bn(i,l.issues)),r.value[a.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),iw=J("$ZodEnum",(e,t)=>{We.init(e,t);const r=Jd(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Cv.has(typeof n)).map(n=>typeof n=="string"?So(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}}),lw=J("$ZodLiteral",(e,t)=>{We.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?So(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}}),cw=J("$ZodTransform",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Co;return r.value=o,r}}),uw=J("$ZodOptional",(e,t)=>{We.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${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)}),dw=J("$ZodNullable",(e,t)=>{We.init(e,t),ze(e._zod,"optin",()=>t.innerType._zod.optin),ze(e._zod,"optout",()=>t.innerType._zod.optout),ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Zi(r.source)}|null)$`):void 0}),ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),pw=J("$ZodDefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>mp(s,t)):mp(o,t)}});function mp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const fw=J("$ZodPrefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),hw=J("$ZodNonOptional",(e,t)=>{We.init(e,t),ze(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>gp(s,e)):gp(o,e)}});function gp(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 mw=J("$ZodCatch",(e,t)=>{We.init(e,t),e._zod.optin="optional",ze(e._zod,"optout",()=>t.innerType._zod.optout),ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>Kr(i,n,Wr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Kr(s,n,Wr()))},input:r.value}),r.issues=[]),r)}}),gw=J("$ZodPipe",(e,t)=>{We.init(e,t),ze(e._zod,"values",()=>t.in._zod.values),ze(e._zod,"optin",()=>t.in._zod.optin),ze(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>yp(s,t,n)):yp(o,t,n)}});function yp(e,t,r){return Io(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const yw=J("$ZodReadonly",(e,t)=>{We.init(e,t),ze(e._zod,"propValues",()=>t.innerType._zod.propValues),ze(e._zod,"values",()=>t.innerType._zod.values),ze(e._zod,"optin",()=>t.innerType._zod.optin),ze(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(_p):_p(o)}});function _p(e){return e.value=Object.freeze(e.value),e}const _w=J("$ZodLazy",(e,t)=>{We.init(e,t),ze(e._zod,"innerType",()=>t.getter()),ze(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),ze(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),ze(e._zod,"optin",()=>e._zod.innerType._zod.optin),ze(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),vw=J("$ZodCustom",(e,t)=>{zt.init(e,t),We.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>vp(s,r,n,e));vp(o,r,n,e)}});function vp(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(xo(o))}}class wp{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 ww(){return new wp}const Eo=ww();function bw(e,t){return new e({type:"string",...de(t)})}function kw(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...de(t)})}function bp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...de(t)})}function Cw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...de(t)})}function Tw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(t)})}function Sw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(t)})}function Iw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(t)})}function kp(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...de(t)})}function xw(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...de(t)})}function Ew(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(t)})}function $w(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...de(t)})}function Rw(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(t)})}function Pw(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...de(t)})}function Nw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...de(t)})}function Mw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(t)})}function Ow(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(t)})}function Aw(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(t)})}function qw(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(t)})}function Lw(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(t)})}function Cp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...de(t)})}function jw(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...de(t)})}function Uw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...de(t)})}function Dw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...de(t)})}function zw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(t)})}function Fw(e,t){return new e({type:"string",format:"date",check:"string_format",...de(t)})}function Vw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...de(t)})}function Zw(e,t){return new e({type:"string",format:"duration",check:"string_format",...de(t)})}function Bw(e,t){return new e({type:"number",checks:[],...de(t)})}function Hw(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 Gw(e,t){return new e({type:"boolean",...de(t)})}function Ww(e,t){return new e({type:"null",...de(t)})}function Kw(e){return new e({type:"any"})}function Yw(e){return new e({type:"unknown"})}function Qw(e,t){return new e({type:"never",...de(t)})}function Tp(e,t){return new ap({check:"less_than",...de(t),value:e,inclusive:!1})}function Gi(e,t){return new ap({check:"less_than",...de(t),value:e,inclusive:!0})}function Sp(e,t){return new ip({check:"greater_than",...de(t),value:e,inclusive:!1})}function Wi(e,t){return new ip({check:"greater_than",...de(t),value:e,inclusive:!0})}function Ip(e,t){return new d1({check:"multiple_of",...de(t),value:e})}function xp(e,t){return new f1({check:"max_length",...de(t),maximum:e})}function qs(e,t){return new h1({check:"min_length",...de(t),minimum:e})}function Ep(e,t){return new m1({check:"length_equals",...de(t),length:e})}function Xw(e,t){return new g1({check:"string_format",format:"regex",...de(t),pattern:e})}function eb(e){return new y1({check:"string_format",format:"lowercase",...de(e)})}function tb(e){return new _1({check:"string_format",format:"uppercase",...de(e)})}function rb(e,t){return new v1({check:"string_format",format:"includes",...de(t),includes:e})}function nb(e,t){return new w1({check:"string_format",format:"starts_with",...de(t),prefix:e})}function ob(e,t){return new b1({check:"string_format",format:"ends_with",...de(t),suffix:e})}function $o(e){return new k1({check:"overwrite",tx:e})}function sb(e){return $o(t=>t.normalize(e))}function ab(){return $o(e=>e.trim())}function ib(){return $o(e=>e.toLowerCase())}function lb(){return $o(e=>e.toUpperCase())}function cb(e,t,r){return new e({type:"array",element:t,...de(r)})}function ub(e,t,r){const n=de(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function db(e,t,r){return new e({type:"custom",check:"custom",fn:t,...de(r)})}class $p{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Eo,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);const l=t._zod.toJSONSchema?.();if(l)a.schema=l;else{const m={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)a.ref=p,this.process(p,m),this.seen.get(p).isParent=!0;else{const f=a.schema;switch(o.type){case"string":{const g=f;g.type="string";const{minimum:v,maximum:y,format:w,patterns:_,contentEncoding:h}=t._zod.bag;if(typeof v=="number"&&(g.minLength=v),typeof y=="number"&&(g.maxLength=y),w&&(g.format=s[w]??w,g.format===""&&delete g.format),h&&(g.contentEncoding=h),_&&_.size>0){const T=[..._];T.length===1?g.pattern=T[0].source:T.length>1&&(a.schema.allOf=[...T.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{const g=f,{minimum:v,maximum:y,format:w,multipleOf:_,exclusiveMaximum:h,exclusiveMinimum:T}=t._zod.bag;typeof w=="string"&&w.includes("int")?g.type="integer":g.type="number",typeof T=="number"&&(g.exclusiveMinimum=T),typeof v=="number"&&(g.minimum=v,typeof T=="number"&&(T>=v?delete g.minimum:delete g.exclusiveMinimum)),typeof h=="number"&&(g.exclusiveMaximum=h),typeof y=="number"&&(g.maximum=y,typeof h=="number"&&(h<=y?delete g.maximum:delete g.exclusiveMaximum)),typeof _=="number"&&(g.multipleOf=_);break}case"boolean":{const g=f;g.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const g=f,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(g.minItems=v),typeof y=="number"&&(g.maxItems=y),g.type="array",g.items=this.process(o.element,{...m,path:[...m.path,"items"]});break}case"object":{const g=f;g.type="object",g.properties={};const v=o.shape;for(const _ in v)g.properties[_]=this.process(v[_],{...m,path:[...m.path,"properties",_]});const y=new Set(Object.keys(v)),w=new Set([...y].filter(_=>{const h=o.shape[_]._zod;return this.io==="input"?h.optin===void 0:h.optout===void 0}));w.size>0&&(g.required=Array.from(w)),o.catchall?._zod.def.type==="never"?g.additionalProperties=!1:o.catchall?o.catchall&&(g.additionalProperties=this.process(o.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(g.additionalProperties=!1);break}case"union":{const g=f;g.anyOf=o.options.map((v,y)=>this.process(v,{...m,path:[...m.path,"anyOf",y]}));break}case"intersection":{const g=f,v=this.process(o.left,{...m,path:[...m.path,"allOf",0]}),y=this.process(o.right,{...m,path:[...m.path,"allOf",1]}),w=h=>"allOf"in h&&Object.keys(h).length===1,_=[...w(v)?v.allOf:[v],...w(y)?y.allOf:[y]];g.allOf=_;break}case"tuple":{const g=f;g.type="array";const v=o.items.map((_,h)=>this.process(_,{...m,path:[...m.path,"prefixItems",h]}));if(this.target==="draft-2020-12"?g.prefixItems=v:g.items=v,o.rest){const _=this.process(o.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?g.items=_:g.additionalItems=_}o.rest&&(g.items=this.process(o.rest,{...m,path:[...m.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(g.minItems=y),typeof w=="number"&&(g.maxItems=w);break}case"record":{const g=f;g.type="object",g.propertyNames=this.process(o.keyType,{...m,path:[...m.path,"propertyNames"]}),g.additionalProperties=this.process(o.valueType,{...m,path:[...m.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const g=f,v=Jd(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),a.ref=o.innerType;break}case"success":{const g=f;g.type="boolean";break}case"default":{this.process(o.innerType,m),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,m),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,m),a.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),a.ref=g;break}case"readonly":{this.process(o.innerType,m),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,m),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,m),a.ref=o.innerType;break}case"lazy":{const g=t._zod.innerType;this.process(g,m),a.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(a.schema,c),this.io==="input"&&vt(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const m=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,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}},i=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>
|
|
28
|
+
})));`),p.write(`newResult[${To(_)}] = ${h}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(_,h)=>w(m,_,h)};let o;const s=Ps,i=!Hd.jitless,l=i&&Sv.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(i&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),m=o(m,p);else{m.value={};const h=u.shape;for(const T of u.keys){const b=h[T],k=b._zod.run({value:f[T],issues:[]},p),S=b._zod.optin==="optional"&&b._zod.optout==="optional";k instanceof Promise?g.push(k.then(I=>S?dp(I,m,T,f):As(I,m,T))):S?dp(k,m,T,f):As(k,m,T)}}if(!c)return g.length?Promise.all(g).then(()=>m):m;const v=[],y=u.keySet,w=c._zod,_=w.def.type;for(const h of Object.keys(f)){if(y.has(h))continue;if(_==="never"){v.push(h);continue}const T=w.run({value:f[h],issues:[]},p);T instanceof Promise?g.push(T.then(b=>As(b,m,h))):As(T,m,h)}return v.length&&m.issues.push({code:"unrecognized_keys",keys:v,input:f,inst:e}),g.length?Promise.all(g).then(()=>m):m}});function pp(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=>Kr(s,n,Wr())))}),t}const fp=J("$ZodUnion",(e,t)=>{We.init(e,t),ze(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ze(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ze(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ze(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Bi(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=>pp(i,r,e,n)):pp(s,r,e,n)}}),iw=J("$ZodDiscriminatedUnion",(e,t)=>{fp.init(e,t);const r=e._zod.parse;ze(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=Vi(()=>{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(!Ps(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)}}),lw=J("$ZodIntersection",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>hp(r,l,c)):hp(r,s,i)}});function Gi(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(Ns(e)&&Ns(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=Gi(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=Gi(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 hp(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Io(e))return e;const n=Gi(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 cw=J("$ZodRecord",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Ns(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(...bn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...bn(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=>Kr(c,n,Wr())),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(...bn(i,c.issues)),r.value[a.value]=c.value})):(l.issues.length&&r.issues.push(...bn(i,l.issues)),r.value[a.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),uw=J("$ZodEnum",(e,t)=>{We.init(e,t);const r=Jd(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Iv.has(typeof n)).map(n=>typeof n=="string"?So(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}}),dw=J("$ZodLiteral",(e,t)=>{We.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?So(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}}),pw=J("$ZodTransform",(e,t)=>{We.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Co;return r.value=o,r}}),fw=J("$ZodOptional",(e,t)=>{We.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bi(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)}),hw=J("$ZodNullable",(e,t)=>{We.init(e,t),ze(e._zod,"optin",()=>t.innerType._zod.optin),ze(e._zod,"optout",()=>t.innerType._zod.optout),ze(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bi(r.source)}|null)$`):void 0}),ze(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),mw=J("$ZodDefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>mp(s,t)):mp(o,t)}});function mp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const gw=J("$ZodPrefault",(e,t)=>{We.init(e,t),e._zod.optin="optional",ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),yw=J("$ZodNonOptional",(e,t)=>{We.init(e,t),ze(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>gp(s,e)):gp(o,e)}});function gp(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 _w=J("$ZodCatch",(e,t)=>{We.init(e,t),e._zod.optin="optional",ze(e._zod,"optout",()=>t.innerType._zod.optout),ze(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>Kr(i,n,Wr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Kr(s,n,Wr()))},input:r.value}),r.issues=[]),r)}}),vw=J("$ZodPipe",(e,t)=>{We.init(e,t),ze(e._zod,"values",()=>t.in._zod.values),ze(e._zod,"optin",()=>t.in._zod.optin),ze(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>yp(s,t,n)):yp(o,t,n)}});function yp(e,t,r){return Io(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const ww=J("$ZodReadonly",(e,t)=>{We.init(e,t),ze(e._zod,"propValues",()=>t.innerType._zod.propValues),ze(e._zod,"values",()=>t.innerType._zod.values),ze(e._zod,"optin",()=>t.innerType._zod.optin),ze(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(_p):_p(o)}});function _p(e){return e.value=Object.freeze(e.value),e}const bw=J("$ZodLazy",(e,t)=>{We.init(e,t),ze(e._zod,"innerType",()=>t.getter()),ze(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),ze(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),ze(e._zod,"optin",()=>e._zod.innerType._zod.optin),ze(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),kw=J("$ZodCustom",(e,t)=>{zt.init(e,t),We.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>vp(s,r,n,e));vp(o,r,n,e)}});function vp(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(xo(o))}}class wp{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 Cw(){return new wp}const Eo=Cw();function Tw(e,t){return new e({type:"string",...de(t)})}function Sw(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...de(t)})}function bp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...de(t)})}function Iw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...de(t)})}function xw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(t)})}function Ew(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(t)})}function $w(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(t)})}function kp(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...de(t)})}function Rw(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...de(t)})}function Pw(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(t)})}function Nw(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...de(t)})}function Mw(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(t)})}function Ow(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...de(t)})}function Aw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...de(t)})}function qw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(t)})}function Lw(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(t)})}function jw(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(t)})}function Uw(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(t)})}function Dw(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(t)})}function Cp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...de(t)})}function zw(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...de(t)})}function Fw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...de(t)})}function Vw(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...de(t)})}function Zw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(t)})}function Bw(e,t){return new e({type:"string",format:"date",check:"string_format",...de(t)})}function Hw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...de(t)})}function Jw(e,t){return new e({type:"string",format:"duration",check:"string_format",...de(t)})}function Gw(e,t){return new e({type:"number",checks:[],...de(t)})}function Ww(e,t){return new e({type:"number",coerce:!0,checks:[],...de(t)})}function Kw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...de(t)})}function Yw(e,t){return new e({type:"boolean",...de(t)})}function Qw(e,t){return new e({type:"null",...de(t)})}function Xw(e){return new e({type:"any"})}function eb(e){return new e({type:"unknown"})}function tb(e,t){return new e({type:"never",...de(t)})}function Tp(e,t){return new ap({check:"less_than",...de(t),value:e,inclusive:!1})}function Wi(e,t){return new ap({check:"less_than",...de(t),value:e,inclusive:!0})}function Sp(e,t){return new ip({check:"greater_than",...de(t),value:e,inclusive:!1})}function Ki(e,t){return new ip({check:"greater_than",...de(t),value:e,inclusive:!0})}function Ip(e,t){return new h1({check:"multiple_of",...de(t),value:e})}function xp(e,t){return new g1({check:"max_length",...de(t),maximum:e})}function qs(e,t){return new y1({check:"min_length",...de(t),minimum:e})}function Ep(e,t){return new _1({check:"length_equals",...de(t),length:e})}function rb(e,t){return new v1({check:"string_format",format:"regex",...de(t),pattern:e})}function nb(e){return new w1({check:"string_format",format:"lowercase",...de(e)})}function ob(e){return new b1({check:"string_format",format:"uppercase",...de(e)})}function sb(e,t){return new k1({check:"string_format",format:"includes",...de(t),includes:e})}function ab(e,t){return new C1({check:"string_format",format:"starts_with",...de(t),prefix:e})}function ib(e,t){return new T1({check:"string_format",format:"ends_with",...de(t),suffix:e})}function $o(e){return new S1({check:"overwrite",tx:e})}function lb(e){return $o(t=>t.normalize(e))}function cb(){return $o(e=>e.trim())}function ub(){return $o(e=>e.toLowerCase())}function db(){return $o(e=>e.toUpperCase())}function pb(e,t,r){return new e({type:"array",element:t,...de(r)})}function fb(e,t,r){const n=de(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function hb(e,t,r){return new e({type:"custom",check:"custom",fn:t,...de(r)})}class $p{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Eo,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);const l=t._zod.toJSONSchema?.();if(l)a.schema=l;else{const m={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)a.ref=p,this.process(p,m),this.seen.get(p).isParent=!0;else{const f=a.schema;switch(o.type){case"string":{const g=f;g.type="string";const{minimum:v,maximum:y,format:w,patterns:_,contentEncoding:h}=t._zod.bag;if(typeof v=="number"&&(g.minLength=v),typeof y=="number"&&(g.maxLength=y),w&&(g.format=s[w]??w,g.format===""&&delete g.format),h&&(g.contentEncoding=h),_&&_.size>0){const T=[..._];T.length===1?g.pattern=T[0].source:T.length>1&&(a.schema.allOf=[...T.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{const g=f,{minimum:v,maximum:y,format:w,multipleOf:_,exclusiveMaximum:h,exclusiveMinimum:T}=t._zod.bag;typeof w=="string"&&w.includes("int")?g.type="integer":g.type="number",typeof T=="number"&&(g.exclusiveMinimum=T),typeof v=="number"&&(g.minimum=v,typeof T=="number"&&(T>=v?delete g.minimum:delete g.exclusiveMinimum)),typeof h=="number"&&(g.exclusiveMaximum=h),typeof y=="number"&&(g.maximum=y,typeof h=="number"&&(h<=y?delete g.maximum:delete g.exclusiveMaximum)),typeof _=="number"&&(g.multipleOf=_);break}case"boolean":{const g=f;g.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const g=f,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(g.minItems=v),typeof y=="number"&&(g.maxItems=y),g.type="array",g.items=this.process(o.element,{...m,path:[...m.path,"items"]});break}case"object":{const g=f;g.type="object",g.properties={};const v=o.shape;for(const _ in v)g.properties[_]=this.process(v[_],{...m,path:[...m.path,"properties",_]});const y=new Set(Object.keys(v)),w=new Set([...y].filter(_=>{const h=o.shape[_]._zod;return this.io==="input"?h.optin===void 0:h.optout===void 0}));w.size>0&&(g.required=Array.from(w)),o.catchall?._zod.def.type==="never"?g.additionalProperties=!1:o.catchall?o.catchall&&(g.additionalProperties=this.process(o.catchall,{...m,path:[...m.path,"additionalProperties"]})):this.io==="output"&&(g.additionalProperties=!1);break}case"union":{const g=f;g.anyOf=o.options.map((v,y)=>this.process(v,{...m,path:[...m.path,"anyOf",y]}));break}case"intersection":{const g=f,v=this.process(o.left,{...m,path:[...m.path,"allOf",0]}),y=this.process(o.right,{...m,path:[...m.path,"allOf",1]}),w=h=>"allOf"in h&&Object.keys(h).length===1,_=[...w(v)?v.allOf:[v],...w(y)?y.allOf:[y]];g.allOf=_;break}case"tuple":{const g=f;g.type="array";const v=o.items.map((_,h)=>this.process(_,{...m,path:[...m.path,"prefixItems",h]}));if(this.target==="draft-2020-12"?g.prefixItems=v:g.items=v,o.rest){const _=this.process(o.rest,{...m,path:[...m.path,"items"]});this.target==="draft-2020-12"?g.items=_:g.additionalItems=_}o.rest&&(g.items=this.process(o.rest,{...m,path:[...m.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(g.minItems=y),typeof w=="number"&&(g.maxItems=w);break}case"record":{const g=f;g.type="object",g.propertyNames=this.process(o.keyType,{...m,path:[...m.path,"propertyNames"]}),g.additionalProperties=this.process(o.valueType,{...m,path:[...m.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const g=f,v=Jd(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),a.ref=o.innerType;break}case"success":{const g=f;g.type="boolean";break}case"default":{this.process(o.innerType,m),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,m),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,m),a.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),a.ref=g;break}case"readonly":{this.process(o.innerType,m),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,m),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,m),a.ref=o.innerType;break}case"lazy":{const g=t._zod.innerType;this.process(g,m),a.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(a.schema,c),this.io==="input"&&vt(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const m=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const v=n.external.registry.get(u[0])?.id,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}},i=u=>{if(u[1].schema.$ref)return;const m=u[1],{ref:p,defId:f}=s(u);m.def={...m.schema},f&&(m.defId=f);const g=m.schema;for(const v in g)delete g[v];g.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const m=u[1];if(m.cycle)throw new Error(`Cycle detected: #/${m.cycle?.join("/")}/<root>
|
|
29
29
|
|
|
30
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const m=u[1];if(t===u[0]){i(u);continue}if(n.external){const f=n.external.registry.get(u[0])?.id;if(t!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(m.cycle){i(u);continue}if(m.count>1&&n.reused==="ref"){i(u);continue}}const a=(u,m)=>{const 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){a(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())a(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const m=u[1];m.def&&m.defId&&(c[m.defId]=m.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function pb(e,t){if(e instanceof wp){const n=new $p(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 $p(t);return r.process(e),r.emit(e,t)}function vt(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 vt(o.element,r);case"object":{for(const s in o.shape)if(vt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(vt(s,r))return!0;return!1}case"intersection":return vt(o.left,r)||vt(o.right,r);case"tuple":{for(const s of o.items)if(vt(s,r))return!0;return!!(o.rest&&vt(o.rest,r))}case"record":return vt(o.keyType,r)||vt(o.valueType,r);case"map":return vt(o.keyType,r)||vt(o.valueType,r);case"set":return vt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return vt(o.innerType,r);case"lazy":return vt(o.getter(),r);case"default":return vt(o.innerType,r);case"prefault":return vt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return vt(o.in,r)||vt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const fb=J("ZodISODateTime",(e,t)=>{q1.init(e,t),st.init(e,t)});function Rp(e){return zw(fb,e)}const hb=J("ZodISODate",(e,t)=>{L1.init(e,t),st.init(e,t)});function mb(e){return Fw(hb,e)}const gb=J("ZodISOTime",(e,t)=>{j1.init(e,t),st.init(e,t)});function yb(e){return Vw(gb,e)}const _b=J("ZodISODuration",(e,t)=>{U1.init(e,t),st.init(e,t)});function vb(e){return Zw(_b,e)}const Ls=J("ZodError",(e,t)=>{Kd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Mv(e,r)},flatten:{value:r=>Nv(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}),wb=Ov(Ls),bb=Av(Ls),kb=Qd(Ls),Pp=ep(Ls),Qe=J("ZodType",(e,t)=>(We.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>wn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>wb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>kb(e,r,n),e.parseAsync=async(r,n)=>bb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Pp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(p3(r,n)),e.superRefine=r=>e.check(f3(r)),e.overwrite=r=>e.check($o(r)),e.optional=()=>ce(e),e.nullable=()=>Fp(e),e.nullish=()=>ce(Fp(e)),e.nonoptional=r=>o3(e,r),e.array=()=>q(e),e.or=r=>ae([e,r]),e.and=r=>Yi(e,r),e.transform=r=>Xi(e,Dp(r)),e.default=r=>t3(e,r),e.prefault=r=>n3(e,r),e.catch=r=>a3(e,r),e.pipe=r=>Xi(e,r),e.readonly=()=>c3(e),e.describe=r=>{const n=e.clone();return Eo.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Eo.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Eo.get(e);const n=e.clone();return Eo.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Np=J("_ZodString",(e,t)=>{Hi.init(e,t),Qe.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Xw(...n)),e.includes=(...n)=>e.check(rb(...n)),e.startsWith=(...n)=>e.check(nb(...n)),e.endsWith=(...n)=>e.check(ob(...n)),e.min=(...n)=>e.check(qs(...n)),e.max=(...n)=>e.check(xp(...n)),e.length=(...n)=>e.check(Ep(...n)),e.nonempty=(...n)=>e.check(qs(1,...n)),e.lowercase=n=>e.check(eb(n)),e.uppercase=n=>e.check(tb(n)),e.trim=()=>e.check(ab()),e.normalize=(...n)=>e.check(sb(...n)),e.toLowerCase=()=>e.check(ib()),e.toUpperCase=()=>e.check(lb())}),Cb=J("ZodString",(e,t)=>{Hi.init(e,t),Np.init(e,t),e.email=r=>e.check(kw(Tb,r)),e.url=r=>e.check(kp(Op,r)),e.jwt=r=>e.check(Dw(Ub,r)),e.emoji=r=>e.check(xw(Ib,r)),e.guid=r=>e.check(bp(Mp,r)),e.uuid=r=>e.check(Cw(js,r)),e.uuidv4=r=>e.check(Tw(js,r)),e.uuidv6=r=>e.check(Sw(js,r)),e.uuidv7=r=>e.check(Iw(js,r)),e.nanoid=r=>e.check(Ew(xb,r)),e.guid=r=>e.check(bp(Mp,r)),e.cuid=r=>e.check($w(Eb,r)),e.cuid2=r=>e.check(Rw($b,r)),e.ulid=r=>e.check(Pw(Rb,r)),e.base64=r=>e.check(Cp(Ap,r)),e.base64url=r=>e.check(jw(Lb,r)),e.xid=r=>e.check(Nw(Pb,r)),e.ksuid=r=>e.check(Mw(Nb,r)),e.ipv4=r=>e.check(Ow(Mb,r)),e.ipv6=r=>e.check(Aw(Ob,r)),e.cidrv4=r=>e.check(qw(Ab,r)),e.cidrv6=r=>e.check(Lw(qb,r)),e.e164=r=>e.check(Uw(jb,r)),e.datetime=r=>e.check(Rp(r)),e.date=r=>e.check(mb(r)),e.time=r=>e.check(yb(r)),e.duration=r=>e.check(vb(r))});function d(e){return bw(Cb,e)}const st=J("ZodStringFormat",(e,t)=>{Xe.init(e,t),Np.init(e,t)}),Tb=J("ZodEmail",(e,t)=>{x1.init(e,t),st.init(e,t)}),Mp=J("ZodGUID",(e,t)=>{S1.init(e,t),st.init(e,t)}),js=J("ZodUUID",(e,t)=>{I1.init(e,t),st.init(e,t)}),Op=J("ZodURL",(e,t)=>{E1.init(e,t),st.init(e,t)});function Sb(e){return kp(Op,e)}const Ib=J("ZodEmoji",(e,t)=>{$1.init(e,t),st.init(e,t)}),xb=J("ZodNanoID",(e,t)=>{R1.init(e,t),st.init(e,t)}),Eb=J("ZodCUID",(e,t)=>{P1.init(e,t),st.init(e,t)}),$b=J("ZodCUID2",(e,t)=>{N1.init(e,t),st.init(e,t)}),Rb=J("ZodULID",(e,t)=>{M1.init(e,t),st.init(e,t)}),Pb=J("ZodXID",(e,t)=>{O1.init(e,t),st.init(e,t)}),Nb=J("ZodKSUID",(e,t)=>{A1.init(e,t),st.init(e,t)}),Mb=J("ZodIPv4",(e,t)=>{D1.init(e,t),st.init(e,t)}),Ob=J("ZodIPv6",(e,t)=>{z1.init(e,t),st.init(e,t)}),Ab=J("ZodCIDRv4",(e,t)=>{F1.init(e,t),st.init(e,t)}),qb=J("ZodCIDRv6",(e,t)=>{V1.init(e,t),st.init(e,t)}),Ap=J("ZodBase64",(e,t)=>{Z1.init(e,t),st.init(e,t)});function qp(e){return Cp(Ap,e)}const Lb=J("ZodBase64URL",(e,t)=>{H1.init(e,t),st.init(e,t)}),jb=J("ZodE164",(e,t)=>{J1.init(e,t),st.init(e,t)}),Ub=J("ZodJWT",(e,t)=>{W1.init(e,t),st.init(e,t)}),Ki=J("ZodNumber",(e,t)=>{cp.init(e,t),Qe.init(e,t),e.gt=(n,o)=>e.check(Sp(n,o)),e.gte=(n,o)=>e.check(Wi(n,o)),e.min=(n,o)=>e.check(Wi(n,o)),e.lt=(n,o)=>e.check(Tp(n,o)),e.lte=(n,o)=>e.check(Gi(n,o)),e.max=(n,o)=>e.check(Gi(n,o)),e.int=n=>e.check(Lp(n)),e.safe=n=>e.check(Lp(n)),e.positive=n=>e.check(Sp(0,n)),e.nonnegative=n=>e.check(Wi(0,n)),e.negative=n=>e.check(Tp(0,n)),e.nonpositive=n=>e.check(Gi(0,n)),e.multipleOf=(n,o)=>e.check(Ip(n,o)),e.step=(n,o)=>e.check(Ip(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 U(e){return Bw(Ki,e)}const Db=J("ZodNumberFormat",(e,t)=>{K1.init(e,t),Ki.init(e,t)});function Lp(e){return Jw(Db,e)}const zb=J("ZodBoolean",(e,t)=>{Y1.init(e,t),Qe.init(e,t)});function he(e){return Gw(zb,e)}const Fb=J("ZodNull",(e,t)=>{Q1.init(e,t),Qe.init(e,t)});function Us(e){return Ww(Fb,e)}const Vb=J("ZodAny",(e,t)=>{X1.init(e,t),Qe.init(e,t)});function bt(){return Kw(Vb)}const Zb=J("ZodUnknown",(e,t)=>{ew.init(e,t),Qe.init(e,t)});function $e(){return Yw(Zb)}const Bb=J("ZodNever",(e,t)=>{tw.init(e,t),Qe.init(e,t)});function Hb(e){return Qw(Bb,e)}const Jb=J("ZodArray",(e,t)=>{rw.init(e,t),Qe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(qs(r,n)),e.nonempty=r=>e.check(qs(1,r)),e.max=(r,n)=>e.check(xp(r,n)),e.length=(r,n)=>e.check(Ep(r,n)),e.unwrap=()=>e.element});function q(e,t){return cb(Jb,e,t)}const jp=J("ZodObject",(e,t)=>{nw.init(e,t),Qe.init(e,t),ze(e,"shape",()=>t.shape),e.keyof=()=>me(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:Hb()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Ev(e,r),e.merge=r=>$v(e,r),e.pick=r=>Iv(e,r),e.omit=r=>xv(e,r),e.partial=(...r)=>Rv(zp,e,r[0]),e.required=(...r)=>Pv(Vp,e,r[0])});function C(e,t){const r={type:"object",get shape(){return Rs(this,"shape",{...e}),this.shape},...de(t)};return new jp(r)}function at(e,t){return new jp({type:"object",get shape(){return Rs(this,"shape",{...e}),this.shape},catchall:$e(),...de(t)})}const Up=J("ZodUnion",(e,t)=>{fp.init(e,t),Qe.init(e,t),e.options=t.options});function ae(e,t){return new Up({type:"union",options:e,...de(t)})}const Gb=J("ZodDiscriminatedUnion",(e,t)=>{Up.init(e,t),ow.init(e,t)});function je(e,t,r){return new Gb({type:"union",options:t,discriminator:e,...de(r)})}const Wb=J("ZodIntersection",(e,t)=>{sw.init(e,t),Qe.init(e,t)});function Yi(e,t){return new Wb({type:"intersection",left:e,right:t})}const Kb=J("ZodRecord",(e,t)=>{aw.init(e,t),Qe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ye(e,t,r){return new Kb({type:"record",keyType:e,valueType:t,...de(r)})}const Qi=J("ZodEnum",(e,t)=>{iw.init(e,t),Qe.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 Qi({...t,checks:[],...de(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 Qi({...t,checks:[],...de(o),entries:s})}});function me(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Qi({type:"enum",entries:r,...de(t)})}const Yb=J("ZodLiteral",(e,t)=>{lw.init(e,t),Qe.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function R(e,t){return new Yb({type:"literal",values:Array.isArray(e)?e:[e],...de(t)})}const Qb=J("ZodTransform",(e,t)=>{cw.init(e,t),Qe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(xo(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(xo(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Dp(e){return new Qb({type:"transform",transform:e})}const zp=J("ZodOptional",(e,t)=>{uw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ce(e){return new zp({type:"optional",innerType:e})}const Xb=J("ZodNullable",(e,t)=>{dw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Fp(e){return new Xb({type:"nullable",innerType:e})}const e3=J("ZodDefault",(e,t)=>{pw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function t3(e,t){return new e3({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const r3=J("ZodPrefault",(e,t)=>{fw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function n3(e,t){return new r3({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Vp=J("ZodNonOptional",(e,t)=>{hw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function o3(e,t){return new Vp({type:"nonoptional",innerType:e,...de(t)})}const s3=J("ZodCatch",(e,t)=>{mw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function a3(e,t){return new s3({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const i3=J("ZodPipe",(e,t)=>{gw.init(e,t),Qe.init(e,t),e.in=t.in,e.out=t.out});function Xi(e,t){return new i3({type:"pipe",in:e,out:t})}const l3=J("ZodReadonly",(e,t)=>{yw.init(e,t),Qe.init(e,t)});function c3(e){return new l3({type:"readonly",innerType:e})}const u3=J("ZodLazy",(e,t)=>{_w.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.getter()});function el(e){return new u3({type:"lazy",getter:e})}const tl=J("ZodCustom",(e,t)=>{vw.init(e,t),Qe.init(e,t)});function d3(e){const t=new zt({check:"custom"});return t._zod.check=e,t}function Zp(e,t){return ub(tl,e??(()=>!0),t)}function p3(e,t={}){return db(tl,e,t)}function f3(e){const t=d3(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(xo(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(xo(o))}},e(r.value,r)));return t}function Ds(e,t={error:`Input not instance of ${e.name}`}){const r=new tl({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...de(t)});return r._zod.bag.Class=e,r}function Bp(e,t){return Xi(Dp(e),t)}const Hp={custom:"custom"};function Jp(e){return Hw(Ki,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 i of o)s[i]=i;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(const a of s)i[a]=o[a];return e.objectValues(i)},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 i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(const i of o)if(s(i))return i},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(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Ue||(Ue={}));var Gp;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Gp||(Gp={}));const ue=Ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yr=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}},ne=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 Or 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 i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);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(this),n}static assert(t){if(!(t instanceof Or))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()}}Or.create=e=>new Or(e);const rl=(e,t)=>{let r;switch(e.code){case ne.invalid_type:e.received===ue.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ue.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ue.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ue.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${Ue.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.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 ne.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 ne.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 ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ue.assertNever(e)}return{message:r}};let h3=rl;function m3(){return h3}const g3=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}};function ie(e,t){const r=m3(),n=g3({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===rl?void 0:rl].filter(o=>!!o)});e.common.issues.push(n)}class Jt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return Ie;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,i=await o.value;n.push({key:s,value:i})}return Jt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return Ie;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}}const Ie=Object.freeze({status:"aborted"}),Ro=e=>({status:"dirty",value:e}),Qt=e=>({status:"valid",value:e}),Wp=e=>e.status==="aborted",Kp=e=>e.status==="dirty",Zn=e=>e.status==="valid",zs=e=>typeof Promise<"u"&&e instanceof Promise;var fe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(fe||(fe={}));class Qr{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 Yp=(e,t)=>{if(Zn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Or(e.common.issues);return this._error=r,this._error}}};function Me(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:(i,a)=>{const{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:o}}class qe{get description(){return this._def.description}_getType(t){return Yr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Yr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Jt,ctx:{common:t.parent.common,data:t.data,parsedType:Yr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(zs(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:Yr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Yp(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Yr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Zn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Zn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Yr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(zs(o)?o:Promise.resolve(o));return Yp(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 i=t(o),a=()=>s.addIssue({code:ne.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!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 Gn({schema:this,typeName:oe.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 tn.create(this,this._def)}nullable(){return Wn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tr.create(this)}promise(){return Bs.create(this,this._def)}or(t){return Vs.create([this,t],this._def)}and(t){return Zs.create(this,t,this._def)}transform(t){return new Gn({...Me(this._def),schema:this,typeName:oe.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new sl({...Me(this._def),innerType:this,defaultValue:r,typeName:oe.ZodDefault})}brand(){return new U3({typeName:oe.ZodBranded,type:this,...Me(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new al({...Me(this._def),innerType:this,catchValue:r,typeName:oe.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return il.create(this,t)}readonly(){return ll.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const y3=/^c[^\s-]{8,}$/i,_3=/^[0-9a-z]+$/,v3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,w3=/^[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,b3=/^[a-z0-9_-]{21}$/i,k3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,C3=/^[-+]?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)?)??$/,T3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,S3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let nl;const I3=/^(?:(?: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])$/,x3=/^(?:(?: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])$/,E3=/^(([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]))$/,$3=/^(([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])$/,R3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,P3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qp="((\\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])))",N3=new RegExp(`^${Qp}$`);function Xp(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 M3(e){return new RegExp(`^${Xp(e)}$`)}function O3(e){let t=`${Qp}T${Xp(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 A3(e,t){return!!((t==="v4"||!t)&&I3.test(e)||(t==="v6"||!t)&&E3.test(e))}function q3(e,t){if(!k3.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 L3(e,t){return!!((t==="v4"||!t)&&x3.test(e)||(t==="v6"||!t)&&$3.test(e))}class Xr extends qe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ue.string){const s=this._getOrReturnCtx(t);return ie(s,{code:ne.invalid_type,expected:ue.string,received:s.parsedType}),Ie}const n=new Jt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.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),ie(o,{code:ne.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?ie(o,{code:ne.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&ie(o,{code:ne.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")T3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"email",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")nl||(nl=new RegExp(S3,"u")),nl.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"emoji",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")w3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"uuid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")b3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"nanoid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")y3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")_3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid2",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")v3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ulid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ie(o,{validation:"url",code:ne.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),ie(o,{validation:"regex",code:ne.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),ie(o,{code:ne.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),ie(o,{code:ne.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?O3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?N3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?M3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?C3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"duration",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?A3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ip",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?q3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"jwt",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?L3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cidr",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?R3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?P3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64url",code:ne.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:ne.invalid_string,...fe.errToObj(n)})}_addCheck(t){return new Xr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...fe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...fe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...fe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...fe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...fe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...fe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...fe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...fe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...fe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...fe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...fe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...fe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...fe.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,...fe.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,...fe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...fe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...fe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...fe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...fe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...fe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...fe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...fe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...fe.errToObj(r)})}nonempty(t){return this.min(1,fe.errToObj(t))}trim(){return new Xr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Xr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Xr({...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}}Xr.create=e=>new Xr({checks:[],typeName:oe.ZodString,coerce:e?.coerce??!1,...Me(e)});function j3(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}class Bn extends qe{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 ie(s,{code:ne.invalid_type,expected:ue.number,received:s.parsedType}),Ie}let n;const o=new Jt;for(const s of this._def.checks)s.kind==="int"?Ue.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.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),ie(n,{code:ne.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),ie(n,{code:ne.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?j3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.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,fe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fe.toString(r))}setLimit(t,r,n,o){return new Bn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new Bn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:fe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:fe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:fe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:fe.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)}}Bn.create=e=>new Bn({checks:[],typeName:oe.ZodNumber,coerce:e?.coerce||!1,...Me(e)});class Po extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ue.bigint)return this._getInvalidInput(t);let n;const o=new Jt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.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),ie(n,{code:ne.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),ie(n,{code:ne.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 ie(r,{code:ne.invalid_type,expected:ue.bigint,received:r.parsedType}),Ie}gte(t,r){return this.setLimit("min",t,!0,fe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fe.toString(r))}setLimit(t,r,n,o){return new Po({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new Po({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.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}}Po.create=e=>new Po({checks:[],typeName:oe.ZodBigInt,coerce:e?.coerce??!1,...Me(e)});class ef extends qe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ue.boolean){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.boolean,received:n.parsedType}),Ie}return Qt(t.data)}}ef.create=e=>new ef({typeName:oe.ZodBoolean,coerce:e?.coerce||!1,...Me(e)});class Fs extends qe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ue.date){const s=this._getOrReturnCtx(t);return ie(s,{code:ne.invalid_type,expected:ue.date,received:s.parsedType}),Ie}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return ie(s,{code:ne.invalid_date}),Ie}const n=new Jt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.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),ie(o,{code:ne.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 Fs({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:fe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:fe.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}}Fs.create=e=>new Fs({checks:[],coerce:e?.coerce||!1,typeName:oe.ZodDate,...Me(e)});class tf extends qe{_parse(t){if(this._getType(t)!==ue.symbol){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.symbol,received:n.parsedType}),Ie}return Qt(t.data)}}tf.create=e=>new tf({typeName:oe.ZodSymbol,...Me(e)});class rf extends qe{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.undefined,received:n.parsedType}),Ie}return Qt(t.data)}}rf.create=e=>new rf({typeName:oe.ZodUndefined,...Me(e)});class nf extends qe{_parse(t){if(this._getType(t)!==ue.null){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.null,received:n.parsedType}),Ie}return Qt(t.data)}}nf.create=e=>new nf({typeName:oe.ZodNull,...Me(e)});class of extends qe{constructor(){super(...arguments),this._any=!0}_parse(t){return Qt(t.data)}}of.create=e=>new of({typeName:oe.ZodAny,...Me(e)});class sf extends qe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Qt(t.data)}}sf.create=e=>new sf({typeName:oe.ZodUnknown,...Me(e)});class en extends qe{_parse(t){const r=this._getOrReturnCtx(t);return ie(r,{code:ne.invalid_type,expected:ue.never,received:r.parsedType}),Ie}}en.create=e=>new en({typeName:oe.ZodNever,...Me(e)});class af extends qe{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.void,received:n.parsedType}),Ie}return Qt(t.data)}}af.create=e=>new af({typeName:oe.ZodVoid,...Me(e)});class Tr extends qe{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ue.array)return ie(r,{code:ne.invalid_type,expected:ue.array,received:r.parsedType}),Ie;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(ie(r,{code:i?ne.too_big:ne.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?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&&(ie(r,{code:ne.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&&(ie(r,{code:ne.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((i,a)=>o.type._parseAsync(new Qr(r,i,r.path,a)))).then(i=>Jt.mergeArray(n,i));const s=[...r.data].map((i,a)=>o.type._parseSync(new Qr(r,i,r.path,a)));return Jt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new Tr({...this._def,minLength:{value:t,message:fe.toString(r)}})}max(t,r){return new Tr({...this._def,maxLength:{value:t,message:fe.toString(r)}})}length(t,r){return new Tr({...this._def,exactLength:{value:t,message:fe.toString(r)}})}nonempty(t){return this.min(1,t)}}Tr.create=(e,t)=>new Tr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:oe.ZodArray,...Me(t)});function Hn(e){if(e instanceof gt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=tn.create(Hn(n))}return new gt({...e._def,shape:()=>t})}else return e instanceof Tr?new Tr({...e._def,type:Hn(e.element)}):e instanceof tn?tn.create(Hn(e.unwrap())):e instanceof Wn?Wn.create(Hn(e.unwrap())):e instanceof kn?kn.create(e.items.map(t=>Hn(t))):e}class gt extends qe{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 ie(c,{code:ne.invalid_type,expected:ue.object,received:c.parsedType}),Ie}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof en&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||a.push(c);const l=[];for(const c of i){const u=s[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Qr(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof en){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(ie(o,{code:ne.unrecognized_keys,keys:a}),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 a){const m=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Qr(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=>Jt.mergeObjectSync(n,c)):Jt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return fe.errToObj,new gt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:fe.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new gt({...this._def,unknownKeys:"strip"})}passthrough(){return new gt({...this._def,unknownKeys:"passthrough"})}extend(t){return new gt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new gt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:oe.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new gt({...this._def,catchall:t})}pick(t){const r={};for(const n of Ue.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new gt({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ue.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new gt({...this._def,shape:()=>r})}deepPartial(){return Hn(this)}partial(t){const r={};for(const n of Ue.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new gt({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ue.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof tn;)s=s._def.innerType;r[n]=s}return new gt({...this._def,shape:()=>r})}keyof(){return df(Ue.objectKeys(this.shape))}}gt.create=(e,t)=>new gt({shape:()=>e,unknownKeys:"strip",catchall:en.create(),typeName:oe.ZodObject,...Me(t)}),gt.strictCreate=(e,t)=>new gt({shape:()=>e,unknownKeys:"strict",catchall:en.create(),typeName:oe.ZodObject,...Me(t)}),gt.lazycreate=(e,t)=>new gt({shape:e,unknownKeys:"strip",catchall:en.create(),typeName:oe.ZodObject,...Me(t)});class Vs extends qe{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(const a of s)if(a.result.status==="valid")return a.result;for(const a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const i=s.map(a=>new Or(a.ctx.common.issues));return ie(r,{code:ne.invalid_union,unionErrors:i}),Ie}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];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&&i.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const a=i.map(l=>new Or(l));return ie(r,{code:ne.invalid_union,unionErrors:a}),Ie}}get options(){return this._def.options}}Vs.create=(e,t)=>new Vs({options:e,typeName:oe.ZodUnion,...Me(t)});function ol(e,t){const r=Yr(e),n=Yr(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(a=>o.indexOf(a)!==-1),i={...e,...t};for(const a of s){const l=ol(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}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 i=e[s],a=t[s],l=ol(i,a);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 qe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,i)=>{if(Wp(s)||Wp(i))return Ie;const a=ol(s.value,i.value);return a.valid?((Kp(s)||Kp(i))&&r.dirty(),{status:r.value,value:a.data}):(ie(n,{code:ne.invalid_intersection_types}),Ie)};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,i])=>o(s,i)):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:oe.ZodIntersection,...Me(r)});class kn extends qe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.array)return ie(n,{code:ne.invalid_type,expected:ue.array,received:n.parsedType}),Ie;if(n.data.length<this._def.items.length)return ie(n,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ie;!this._def.rest&&n.data.length>this._def.items.length&&(ie(n,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Qr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Jt.mergeArray(r,i)):Jt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new kn({...this._def,rest:t})}}kn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new kn({items:e,typeName:oe.ZodTuple,rest:null,...Me(t)})};class lf extends qe{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 ie(n,{code:ne.invalid_type,expected:ue.map,received:n.parsedType}),Ie;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,l],c)=>({key:o._parse(new Qr(n,a,n.path,[c,"key"])),value:s._parse(new Qr(n,l,n.path,[c,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return Ie;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const l of i){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return Ie;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}}lf.create=(e,t,r)=>new lf({valueType:t,keyType:e,typeName:oe.ZodMap,...Me(r)});class No extends qe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.set)return ie(n,{code:ne.invalid_type,expected:ue.set,received:n.parsedType}),Ie;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ie(n,{code:ne.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&&(ie(n,{code:ne.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function i(l){const c=new Set;for(const u of l){if(u.status==="aborted")return Ie;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>s._parse(new Qr(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,r){return new No({...this._def,minSize:{value:t,message:fe.toString(r)}})}max(t,r){return new No({...this._def,maxSize:{value:t,message:fe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}No.create=(e,t)=>new No({valueType:e,minSize:null,maxSize:null,typeName:oe.ZodSet,...Me(t)});class cf extends qe{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})}}cf.create=(e,t)=>new cf({getter:e,typeName:oe.ZodLazy,...Me(t)});class uf extends qe{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ie(r,{received:r.data,code:ne.invalid_literal,expected:this._def.value}),Ie}return{status:"valid",value:t.data}}get value(){return this._def.value}}uf.create=(e,t)=>new uf({value:e,typeName:oe.ZodLiteral,...Me(t)});function df(e,t){return new Jn({values:e,typeName:oe.ZodEnum,...Me(t)})}class Jn extends qe{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ie(r,{expected:Ue.joinValues(n),received:r.parsedType,code:ne.invalid_type}),Ie}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 ie(r,{received:r.data,code:ne.invalid_enum_value,options:n}),Ie}return Qt(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 Jn.create(t,{...this._def,...r})}exclude(t,r=this._def){return Jn.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}Jn.create=df;class pf extends qe{_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 ie(n,{expected:Ue.joinValues(o),received:n.parsedType,code:ne.invalid_type}),Ie}if(this._cache||(this._cache=new Set(Ue.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Ue.objectValues(r);return ie(n,{received:n.data,code:ne.invalid_enum_value,options:o}),Ie}return Qt(t.data)}get enum(){return this._def.values}}pf.create=(e,t)=>new pf({values:e,typeName:oe.ZodNativeEnum,...Me(t)});class Bs extends qe{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ue.promise&&r.common.async===!1)return ie(r,{code:ne.invalid_type,expected:ue.promise,received:r.parsedType}),Ie;const n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return Qt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Bs.create=(e,t)=>new Bs({type:e,typeName:oe.ZodPromise,...Me(t)});class Gn extends qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oe.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:i=>{ie(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return Ie;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?Ie:l.status==="dirty"||r.value==="dirty"?Ro(l.value):l});{if(r.value==="aborted")return Ie;const a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?Ie:a.status==="dirty"||r.value==="dirty"?Ro(a.value):a}}if(o.type==="refinement"){const i=a=>{const l=o.refinement(a,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 a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ie:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?Ie:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Zn(i))return Ie;const a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Zn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):Ie);Ue.assertNever(o)}}Gn.create=(e,t,r)=>new Gn({schema:e,typeName:oe.ZodEffects,effect:t,...Me(r)}),Gn.createWithPreprocess=(e,t,r)=>new Gn({schema:t,effect:{type:"preprocess",transform:e},typeName:oe.ZodEffects,...Me(r)});class tn extends qe{_parse(t){return this._getType(t)===ue.undefined?Qt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}tn.create=(e,t)=>new tn({innerType:e,typeName:oe.ZodOptional,...Me(t)});class Wn extends qe{_parse(t){return this._getType(t)===ue.null?Qt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Wn.create=(e,t)=>new Wn({innerType:e,typeName:oe.ZodNullable,...Me(t)});class sl extends qe{_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}}sl.create=(e,t)=>new sl({innerType:e,typeName:oe.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Me(t)});class al extends qe{_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 zs(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Or(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Or(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}al.create=(e,t)=>new al({innerType:e,typeName:oe.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Me(t)});class ff extends qe{_parse(t){if(this._getType(t)!==ue.nan){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.nan,received:n.parsedType}),Ie}return{status:"valid",value:t.data}}}ff.create=e=>new ff({typeName:oe.ZodNaN,...Me(e)});class U3 extends qe{_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 il extends qe{_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"?Ie:s.status==="dirty"?(r.dirty(),Ro(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"?Ie: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 il({in:t,out:r,typeName:oe.ZodPipeline})}}class ll extends qe{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Zn(o)&&(o.value=Object.freeze(o.value)),o);return zs(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}ll.create=(e,t)=>new ll({innerType:e,typeName:oe.ZodReadonly,...Me(t)});var oe;(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"})(oe||(oe={}));const Ke=Xr.create,Sr=Bn.create;en.create;const rn=Tr.create,ir=gt.create,cl=Vs.create;Zs.create,kn.create;const Hs=Jn.create;Bs.create,tn.create,Wn.create;class hf 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 ul(e){}function mf(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=ul,onError:r=ul,onRetry:n=ul,onComment:o}=e;let s="",i=!0,a,l="",c="";function u(v){const y=i?v.replace(/^\xEF\xBB\xBF/,""):v,[w,_]=D3(`${s}${y}`);for(const h of w)m(h);s=_,i=!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}
|
|
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]){i(u);continue}if(n.external){const f=n.external.registry.get(u[0])?.id;if(t!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(m.cycle){i(u);continue}if(m.count>1&&n.reused==="ref"){i(u);continue}}const a=(u,m)=>{const 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){a(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())a(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const m=u[1];m.def&&m.defId&&(c[m.defId]=m.def)}n.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function mb(e,t){if(e instanceof wp){const n=new $p(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 $p(t);return r.process(e),r.emit(e,t)}function vt(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 vt(o.element,r);case"object":{for(const s in o.shape)if(vt(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(vt(s,r))return!0;return!1}case"intersection":return vt(o.left,r)||vt(o.right,r);case"tuple":{for(const s of o.items)if(vt(s,r))return!0;return!!(o.rest&&vt(o.rest,r))}case"record":return vt(o.keyType,r)||vt(o.valueType,r);case"map":return vt(o.keyType,r)||vt(o.valueType,r);case"set":return vt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return vt(o.innerType,r);case"lazy":return vt(o.getter(),r);case"default":return vt(o.innerType,r);case"prefault":return vt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return vt(o.in,r)||vt(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const gb=J("ZodISODateTime",(e,t)=>{U1.init(e,t),st.init(e,t)});function Rp(e){return Zw(gb,e)}const yb=J("ZodISODate",(e,t)=>{D1.init(e,t),st.init(e,t)});function _b(e){return Bw(yb,e)}const vb=J("ZodISOTime",(e,t)=>{z1.init(e,t),st.init(e,t)});function wb(e){return Hw(vb,e)}const bb=J("ZodISODuration",(e,t)=>{F1.init(e,t),st.init(e,t)});function kb(e){return Jw(bb,e)}const Ls=J("ZodError",(e,t)=>{Kd.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>qv(e,r)},flatten:{value:r=>Av(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Cb=Lv(Ls),Tb=jv(Ls),Sb=Qd(Ls),Pp=ep(Ls),Qe=J("ZodType",(e,t)=>(We.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>wn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Cb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Sb(e,r,n),e.parseAsync=async(r,n)=>Tb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Pp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(m3(r,n)),e.superRefine=r=>e.check(g3(r)),e.overwrite=r=>e.check($o(r)),e.optional=()=>ce(e),e.nullable=()=>Fp(e),e.nullish=()=>ce(Fp(e)),e.nonoptional=r=>i3(e,r),e.array=()=>q(e),e.or=r=>ae([e,r]),e.and=r=>Qi(e,r),e.transform=r=>el(e,Dp(r)),e.default=r=>o3(e,r),e.prefault=r=>a3(e,r),e.catch=r=>c3(e,r),e.pipe=r=>el(e,r),e.readonly=()=>p3(e),e.describe=r=>{const n=e.clone();return Eo.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Eo.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Eo.get(e);const n=e.clone();return Eo.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Np=J("_ZodString",(e,t)=>{Ji.init(e,t),Qe.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(rb(...n)),e.includes=(...n)=>e.check(sb(...n)),e.startsWith=(...n)=>e.check(ab(...n)),e.endsWith=(...n)=>e.check(ib(...n)),e.min=(...n)=>e.check(qs(...n)),e.max=(...n)=>e.check(xp(...n)),e.length=(...n)=>e.check(Ep(...n)),e.nonempty=(...n)=>e.check(qs(1,...n)),e.lowercase=n=>e.check(nb(n)),e.uppercase=n=>e.check(ob(n)),e.trim=()=>e.check(cb()),e.normalize=(...n)=>e.check(lb(...n)),e.toLowerCase=()=>e.check(ub()),e.toUpperCase=()=>e.check(db())}),Ib=J("ZodString",(e,t)=>{Ji.init(e,t),Np.init(e,t),e.email=r=>e.check(Sw(xb,r)),e.url=r=>e.check(kp(Op,r)),e.jwt=r=>e.check(Vw(Fb,r)),e.emoji=r=>e.check(Rw($b,r)),e.guid=r=>e.check(bp(Mp,r)),e.uuid=r=>e.check(Iw(js,r)),e.uuidv4=r=>e.check(xw(js,r)),e.uuidv6=r=>e.check(Ew(js,r)),e.uuidv7=r=>e.check($w(js,r)),e.nanoid=r=>e.check(Pw(Rb,r)),e.guid=r=>e.check(bp(Mp,r)),e.cuid=r=>e.check(Nw(Pb,r)),e.cuid2=r=>e.check(Mw(Nb,r)),e.ulid=r=>e.check(Ow(Mb,r)),e.base64=r=>e.check(Cp(Ap,r)),e.base64url=r=>e.check(zw(Db,r)),e.xid=r=>e.check(Aw(Ob,r)),e.ksuid=r=>e.check(qw(Ab,r)),e.ipv4=r=>e.check(Lw(qb,r)),e.ipv6=r=>e.check(jw(Lb,r)),e.cidrv4=r=>e.check(Uw(jb,r)),e.cidrv6=r=>e.check(Dw(Ub,r)),e.e164=r=>e.check(Fw(zb,r)),e.datetime=r=>e.check(Rp(r)),e.date=r=>e.check(_b(r)),e.time=r=>e.check(wb(r)),e.duration=r=>e.check(kb(r))});function d(e){return Tw(Ib,e)}const st=J("ZodStringFormat",(e,t)=>{Xe.init(e,t),Np.init(e,t)}),xb=J("ZodEmail",(e,t)=>{R1.init(e,t),st.init(e,t)}),Mp=J("ZodGUID",(e,t)=>{E1.init(e,t),st.init(e,t)}),js=J("ZodUUID",(e,t)=>{$1.init(e,t),st.init(e,t)}),Op=J("ZodURL",(e,t)=>{P1.init(e,t),st.init(e,t)});function Eb(e){return kp(Op,e)}const $b=J("ZodEmoji",(e,t)=>{N1.init(e,t),st.init(e,t)}),Rb=J("ZodNanoID",(e,t)=>{M1.init(e,t),st.init(e,t)}),Pb=J("ZodCUID",(e,t)=>{O1.init(e,t),st.init(e,t)}),Nb=J("ZodCUID2",(e,t)=>{A1.init(e,t),st.init(e,t)}),Mb=J("ZodULID",(e,t)=>{q1.init(e,t),st.init(e,t)}),Ob=J("ZodXID",(e,t)=>{L1.init(e,t),st.init(e,t)}),Ab=J("ZodKSUID",(e,t)=>{j1.init(e,t),st.init(e,t)}),qb=J("ZodIPv4",(e,t)=>{V1.init(e,t),st.init(e,t)}),Lb=J("ZodIPv6",(e,t)=>{Z1.init(e,t),st.init(e,t)}),jb=J("ZodCIDRv4",(e,t)=>{B1.init(e,t),st.init(e,t)}),Ub=J("ZodCIDRv6",(e,t)=>{H1.init(e,t),st.init(e,t)}),Ap=J("ZodBase64",(e,t)=>{J1.init(e,t),st.init(e,t)});function qp(e){return Cp(Ap,e)}const Db=J("ZodBase64URL",(e,t)=>{W1.init(e,t),st.init(e,t)}),zb=J("ZodE164",(e,t)=>{K1.init(e,t),st.init(e,t)}),Fb=J("ZodJWT",(e,t)=>{Q1.init(e,t),st.init(e,t)}),Yi=J("ZodNumber",(e,t)=>{cp.init(e,t),Qe.init(e,t),e.gt=(n,o)=>e.check(Sp(n,o)),e.gte=(n,o)=>e.check(Ki(n,o)),e.min=(n,o)=>e.check(Ki(n,o)),e.lt=(n,o)=>e.check(Tp(n,o)),e.lte=(n,o)=>e.check(Wi(n,o)),e.max=(n,o)=>e.check(Wi(n,o)),e.int=n=>e.check(Lp(n)),e.safe=n=>e.check(Lp(n)),e.positive=n=>e.check(Sp(0,n)),e.nonnegative=n=>e.check(Ki(0,n)),e.negative=n=>e.check(Tp(0,n)),e.nonpositive=n=>e.check(Wi(0,n)),e.multipleOf=(n,o)=>e.check(Ip(n,o)),e.step=(n,o)=>e.check(Ip(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 U(e){return Gw(Yi,e)}const Vb=J("ZodNumberFormat",(e,t)=>{X1.init(e,t),Yi.init(e,t)});function Lp(e){return Kw(Vb,e)}const Zb=J("ZodBoolean",(e,t)=>{ew.init(e,t),Qe.init(e,t)});function he(e){return Yw(Zb,e)}const Bb=J("ZodNull",(e,t)=>{tw.init(e,t),Qe.init(e,t)});function Us(e){return Qw(Bb,e)}const Hb=J("ZodAny",(e,t)=>{rw.init(e,t),Qe.init(e,t)});function bt(){return Xw(Hb)}const Jb=J("ZodUnknown",(e,t)=>{nw.init(e,t),Qe.init(e,t)});function $e(){return eb(Jb)}const Gb=J("ZodNever",(e,t)=>{ow.init(e,t),Qe.init(e,t)});function Wb(e){return tb(Gb,e)}const Kb=J("ZodArray",(e,t)=>{sw.init(e,t),Qe.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(qs(r,n)),e.nonempty=r=>e.check(qs(1,r)),e.max=(r,n)=>e.check(xp(r,n)),e.length=(r,n)=>e.check(Ep(r,n)),e.unwrap=()=>e.element});function q(e,t){return pb(Kb,e,t)}const jp=J("ZodObject",(e,t)=>{aw.init(e,t),Qe.init(e,t),ze(e,"shape",()=>t.shape),e.keyof=()=>me(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:Wb()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Pv(e,r),e.merge=r=>Nv(e,r),e.pick=r=>$v(e,r),e.omit=r=>Rv(e,r),e.partial=(...r)=>Mv(zp,e,r[0]),e.required=(...r)=>Ov(Vp,e,r[0])});function C(e,t){const r={type:"object",get shape(){return Rs(this,"shape",{...e}),this.shape},...de(t)};return new jp(r)}function at(e,t){return new jp({type:"object",get shape(){return Rs(this,"shape",{...e}),this.shape},catchall:$e(),...de(t)})}const Up=J("ZodUnion",(e,t)=>{fp.init(e,t),Qe.init(e,t),e.options=t.options});function ae(e,t){return new Up({type:"union",options:e,...de(t)})}const Yb=J("ZodDiscriminatedUnion",(e,t)=>{Up.init(e,t),iw.init(e,t)});function je(e,t,r){return new Yb({type:"union",options:t,discriminator:e,...de(r)})}const Qb=J("ZodIntersection",(e,t)=>{lw.init(e,t),Qe.init(e,t)});function Qi(e,t){return new Qb({type:"intersection",left:e,right:t})}const Xb=J("ZodRecord",(e,t)=>{cw.init(e,t),Qe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ye(e,t,r){return new Xb({type:"record",keyType:e,valueType:t,...de(r)})}const Xi=J("ZodEnum",(e,t)=>{uw.init(e,t),Qe.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 Xi({...t,checks:[],...de(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 Xi({...t,checks:[],...de(o),entries:s})}});function me(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Xi({type:"enum",entries:r,...de(t)})}const e3=J("ZodLiteral",(e,t)=>{dw.init(e,t),Qe.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function R(e,t){return new e3({type:"literal",values:Array.isArray(e)?e:[e],...de(t)})}const t3=J("ZodTransform",(e,t)=>{pw.init(e,t),Qe.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(xo(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(xo(i))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Dp(e){return new t3({type:"transform",transform:e})}const zp=J("ZodOptional",(e,t)=>{fw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ce(e){return new zp({type:"optional",innerType:e})}const r3=J("ZodNullable",(e,t)=>{hw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Fp(e){return new r3({type:"nullable",innerType:e})}const n3=J("ZodDefault",(e,t)=>{mw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function o3(e,t){return new n3({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const s3=J("ZodPrefault",(e,t)=>{gw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function a3(e,t){return new s3({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Vp=J("ZodNonOptional",(e,t)=>{yw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType});function i3(e,t){return new Vp({type:"nonoptional",innerType:e,...de(t)})}const l3=J("ZodCatch",(e,t)=>{_w.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function c3(e,t){return new l3({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const u3=J("ZodPipe",(e,t)=>{vw.init(e,t),Qe.init(e,t),e.in=t.in,e.out=t.out});function el(e,t){return new u3({type:"pipe",in:e,out:t})}const d3=J("ZodReadonly",(e,t)=>{ww.init(e,t),Qe.init(e,t)});function p3(e){return new d3({type:"readonly",innerType:e})}const f3=J("ZodLazy",(e,t)=>{bw.init(e,t),Qe.init(e,t),e.unwrap=()=>e._zod.def.getter()});function tl(e){return new f3({type:"lazy",getter:e})}const rl=J("ZodCustom",(e,t)=>{kw.init(e,t),Qe.init(e,t)});function h3(e){const t=new zt({check:"custom"});return t._zod.check=e,t}function Zp(e,t){return fb(rl,e??(()=>!0),t)}function m3(e,t={}){return hb(rl,e,t)}function g3(e){const t=h3(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(xo(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(xo(o))}},e(r.value,r)));return t}function Ds(e,t={error:`Input not instance of ${e.name}`}){const r=new rl({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...de(t)});return r._zod.bag.Class=e,r}function Bp(e,t){return el(Dp(e),t)}const Hp={custom:"custom"};function Jp(e){return Ww(Yi,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 i of o)s[i]=i;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(const a of s)i[a]=o[a];return e.objectValues(i)},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 i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(const i of o)if(s(i))return i},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(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Ue||(Ue={}));var Gp;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Gp||(Gp={}));const ue=Ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yr=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}},ne=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 Or 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 i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);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(this),n}static assert(t){if(!(t instanceof Or))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()}}Or.create=e=>new Or(e);const nl=(e,t)=>{let r;switch(e.code){case ne.invalid_type:e.received===ue.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ue.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ue.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ue.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${Ue.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.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 ne.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 ne.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 ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ue.assertNever(e)}return{message:r}};let y3=nl;function _3(){return y3}const v3=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}};function ie(e,t){const r=_3(),n=v3({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===nl?void 0:nl].filter(o=>!!o)});e.common.issues.push(n)}class Jt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return Ie;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,i=await o.value;n.push({key:s,value:i})}return Jt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return Ie;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}}const Ie=Object.freeze({status:"aborted"}),Ro=e=>({status:"dirty",value:e}),Qt=e=>({status:"valid",value:e}),Wp=e=>e.status==="aborted",Kp=e=>e.status==="dirty",Zn=e=>e.status==="valid",zs=e=>typeof Promise<"u"&&e instanceof Promise;var fe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(fe||(fe={}));class Qr{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 Yp=(e,t)=>{if(Zn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Or(e.common.issues);return this._error=r,this._error}}};function Me(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:(i,a)=>{const{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:o}}class qe{get description(){return this._def.description}_getType(t){return Yr(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Yr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Jt,ctx:{common:t.parent.common,data:t.data,parsedType:Yr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(zs(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:Yr(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Yp(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Yr(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Zn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Zn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Yr(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(zs(o)?o:Promise.resolve(o));return Yp(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 i=t(o),a=()=>s.addIssue({code:ne.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!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 Gn({schema:this,typeName:oe.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 tn.create(this,this._def)}nullable(){return Wn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Tr.create(this)}promise(){return Bs.create(this,this._def)}or(t){return Vs.create([this,t],this._def)}and(t){return Zs.create(this,t,this._def)}transform(t){return new Gn({...Me(this._def),schema:this,typeName:oe.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new al({...Me(this._def),innerType:this,defaultValue:r,typeName:oe.ZodDefault})}brand(){return new F3({typeName:oe.ZodBranded,type:this,...Me(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new il({...Me(this._def),innerType:this,catchValue:r,typeName:oe.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return ll.create(this,t)}readonly(){return cl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const w3=/^c[^\s-]{8,}$/i,b3=/^[0-9a-z]+$/,k3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C3=/^[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,T3=/^[a-z0-9_-]{21}$/i,S3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,I3=/^[-+]?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)?)??$/,x3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,E3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ol;const $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])$/,R3=/^(?:(?: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])$/,P3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,N3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,M3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,O3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qp="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",A3=new RegExp(`^${Qp}$`);function Xp(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 q3(e){return new RegExp(`^${Xp(e)}$`)}function L3(e){let t=`${Qp}T${Xp(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 j3(e,t){return!!((t==="v4"||!t)&&$3.test(e)||(t==="v6"||!t)&&P3.test(e))}function U3(e,t){if(!S3.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function D3(e,t){return!!((t==="v4"||!t)&&R3.test(e)||(t==="v6"||!t)&&N3.test(e))}class Xr extends qe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ue.string){const s=this._getOrReturnCtx(t);return ie(s,{code:ne.invalid_type,expected:ue.string,received:s.parsedType}),Ie}const n=new Jt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.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),ie(o,{code:ne.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?ie(o,{code:ne.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&ie(o,{code:ne.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")x3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"email",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ol||(ol=new RegExp(E3,"u")),ol.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"emoji",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")C3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"uuid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")T3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"nanoid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")w3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")b3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cuid2",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")k3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ulid",code:ne.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ie(o,{validation:"url",code:ne.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),ie(o,{validation:"regex",code:ne.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),ie(o,{code:ne.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),ie(o,{code:ne.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?L3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?A3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?q3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?I3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"duration",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?j3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"ip",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?U3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"jwt",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?D3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"cidr",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?M3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64",code:ne.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?O3.test(t.data)||(o=this._getOrReturnCtx(t,o),ie(o,{validation:"base64url",code:ne.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:ne.invalid_string,...fe.errToObj(n)})}_addCheck(t){return new Xr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...fe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...fe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...fe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...fe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...fe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...fe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...fe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...fe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...fe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...fe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...fe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...fe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...fe.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,...fe.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,...fe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...fe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...fe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...fe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...fe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...fe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...fe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...fe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...fe.errToObj(r)})}nonempty(t){return this.min(1,fe.errToObj(t))}trim(){return new Xr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Xr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Xr({...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}}Xr.create=e=>new Xr({checks:[],typeName:oe.ZodString,coerce:e?.coerce??!1,...Me(e)});function z3(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}class Bn extends qe{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 ie(s,{code:ne.invalid_type,expected:ue.number,received:s.parsedType}),Ie}let n;const o=new Jt;for(const s of this._def.checks)s.kind==="int"?Ue.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.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),ie(n,{code:ne.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),ie(n,{code:ne.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?z3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.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,fe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fe.toString(r))}setLimit(t,r,n,o){return new Bn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new Bn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:fe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:fe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:fe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:fe.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)}}Bn.create=e=>new Bn({checks:[],typeName:oe.ZodNumber,coerce:e?.coerce||!1,...Me(e)});class Po extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ue.bigint)return this._getInvalidInput(t);let n;const o=new Jt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),ie(n,{code:ne.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),ie(n,{code:ne.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),ie(n,{code:ne.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 ie(r,{code:ne.invalid_type,expected:ue.bigint,received:r.parsedType}),Ie}gte(t,r){return this.setLimit("min",t,!0,fe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,fe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,fe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,fe.toString(r))}setLimit(t,r,n,o){return new Po({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new Po({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.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}}Po.create=e=>new Po({checks:[],typeName:oe.ZodBigInt,coerce:e?.coerce??!1,...Me(e)});class ef extends qe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ue.boolean){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.boolean,received:n.parsedType}),Ie}return Qt(t.data)}}ef.create=e=>new ef({typeName:oe.ZodBoolean,coerce:e?.coerce||!1,...Me(e)});class Fs extends qe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ue.date){const s=this._getOrReturnCtx(t);return ie(s,{code:ne.invalid_type,expected:ue.date,received:s.parsedType}),Ie}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return ie(s,{code:ne.invalid_date}),Ie}const n=new Jt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),ie(o,{code:ne.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),ie(o,{code:ne.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 Fs({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:fe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:fe.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}}Fs.create=e=>new Fs({checks:[],coerce:e?.coerce||!1,typeName:oe.ZodDate,...Me(e)});class tf extends qe{_parse(t){if(this._getType(t)!==ue.symbol){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.symbol,received:n.parsedType}),Ie}return Qt(t.data)}}tf.create=e=>new tf({typeName:oe.ZodSymbol,...Me(e)});class rf extends qe{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.undefined,received:n.parsedType}),Ie}return Qt(t.data)}}rf.create=e=>new rf({typeName:oe.ZodUndefined,...Me(e)});class nf extends qe{_parse(t){if(this._getType(t)!==ue.null){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.null,received:n.parsedType}),Ie}return Qt(t.data)}}nf.create=e=>new nf({typeName:oe.ZodNull,...Me(e)});class of extends qe{constructor(){super(...arguments),this._any=!0}_parse(t){return Qt(t.data)}}of.create=e=>new of({typeName:oe.ZodAny,...Me(e)});class sf extends qe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Qt(t.data)}}sf.create=e=>new sf({typeName:oe.ZodUnknown,...Me(e)});class en extends qe{_parse(t){const r=this._getOrReturnCtx(t);return ie(r,{code:ne.invalid_type,expected:ue.never,received:r.parsedType}),Ie}}en.create=e=>new en({typeName:oe.ZodNever,...Me(e)});class af extends qe{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.void,received:n.parsedType}),Ie}return Qt(t.data)}}af.create=e=>new af({typeName:oe.ZodVoid,...Me(e)});class Tr extends qe{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ue.array)return ie(r,{code:ne.invalid_type,expected:ue.array,received:r.parsedType}),Ie;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(ie(r,{code:i?ne.too_big:ne.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?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&&(ie(r,{code:ne.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&&(ie(r,{code:ne.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((i,a)=>o.type._parseAsync(new Qr(r,i,r.path,a)))).then(i=>Jt.mergeArray(n,i));const s=[...r.data].map((i,a)=>o.type._parseSync(new Qr(r,i,r.path,a)));return Jt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new Tr({...this._def,minLength:{value:t,message:fe.toString(r)}})}max(t,r){return new Tr({...this._def,maxLength:{value:t,message:fe.toString(r)}})}length(t,r){return new Tr({...this._def,exactLength:{value:t,message:fe.toString(r)}})}nonempty(t){return this.min(1,t)}}Tr.create=(e,t)=>new Tr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:oe.ZodArray,...Me(t)});function Hn(e){if(e instanceof gt){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=tn.create(Hn(n))}return new gt({...e._def,shape:()=>t})}else return e instanceof Tr?new Tr({...e._def,type:Hn(e.element)}):e instanceof tn?tn.create(Hn(e.unwrap())):e instanceof Wn?Wn.create(Hn(e.unwrap())):e instanceof kn?kn.create(e.items.map(t=>Hn(t))):e}class gt extends qe{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 ie(c,{code:ne.invalid_type,expected:ue.object,received:c.parsedType}),Ie}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof en&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||a.push(c);const l=[];for(const c of i){const u=s[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Qr(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof en){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(ie(o,{code:ne.unrecognized_keys,keys:a}),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 a){const m=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Qr(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=>Jt.mergeObjectSync(n,c)):Jt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return fe.errToObj,new gt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:fe.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new gt({...this._def,unknownKeys:"strip"})}passthrough(){return new gt({...this._def,unknownKeys:"passthrough"})}extend(t){return new gt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new gt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:oe.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new gt({...this._def,catchall:t})}pick(t){const r={};for(const n of Ue.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new gt({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ue.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new gt({...this._def,shape:()=>r})}deepPartial(){return Hn(this)}partial(t){const r={};for(const n of Ue.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new gt({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ue.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof tn;)s=s._def.innerType;r[n]=s}return new gt({...this._def,shape:()=>r})}keyof(){return df(Ue.objectKeys(this.shape))}}gt.create=(e,t)=>new gt({shape:()=>e,unknownKeys:"strip",catchall:en.create(),typeName:oe.ZodObject,...Me(t)}),gt.strictCreate=(e,t)=>new gt({shape:()=>e,unknownKeys:"strict",catchall:en.create(),typeName:oe.ZodObject,...Me(t)}),gt.lazycreate=(e,t)=>new gt({shape:e,unknownKeys:"strip",catchall:en.create(),typeName:oe.ZodObject,...Me(t)});class Vs extends qe{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(const a of s)if(a.result.status==="valid")return a.result;for(const a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;const i=s.map(a=>new Or(a.ctx.common.issues));return ie(r,{code:ne.invalid_union,unionErrors:i}),Ie}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];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&&i.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const a=i.map(l=>new Or(l));return ie(r,{code:ne.invalid_union,unionErrors:a}),Ie}}get options(){return this._def.options}}Vs.create=(e,t)=>new Vs({options:e,typeName:oe.ZodUnion,...Me(t)});function sl(e,t){const r=Yr(e),n=Yr(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(a=>o.indexOf(a)!==-1),i={...e,...t};for(const a of s){const l=sl(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}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 i=e[s],a=t[s],l=sl(i,a);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 qe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,i)=>{if(Wp(s)||Wp(i))return Ie;const a=sl(s.value,i.value);return a.valid?((Kp(s)||Kp(i))&&r.dirty(),{status:r.value,value:a.data}):(ie(n,{code:ne.invalid_intersection_types}),Ie)};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,i])=>o(s,i)):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:oe.ZodIntersection,...Me(r)});class kn extends qe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.array)return ie(n,{code:ne.invalid_type,expected:ue.array,received:n.parsedType}),Ie;if(n.data.length<this._def.items.length)return ie(n,{code:ne.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ie;!this._def.rest&&n.data.length>this._def.items.length&&(ie(n,{code:ne.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Qr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Jt.mergeArray(r,i)):Jt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new kn({...this._def,rest:t})}}kn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new kn({items:e,typeName:oe.ZodTuple,rest:null,...Me(t)})};class lf extends qe{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 ie(n,{code:ne.invalid_type,expected:ue.map,received:n.parsedType}),Ie;const o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,l],c)=>({key:o._parse(new Qr(n,a,n.path,[c,"key"])),value:s._parse(new Qr(n,l,n.path,[c,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return Ie;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{const a=new Map;for(const l of i){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return Ie;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}}lf.create=(e,t,r)=>new lf({valueType:t,keyType:e,typeName:oe.ZodMap,...Me(r)});class No extends qe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.set)return ie(n,{code:ne.invalid_type,expected:ue.set,received:n.parsedType}),Ie;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ie(n,{code:ne.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&&(ie(n,{code:ne.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function i(l){const c=new Set;for(const u of l){if(u.status==="aborted")return Ie;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>s._parse(new Qr(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,r){return new No({...this._def,minSize:{value:t,message:fe.toString(r)}})}max(t,r){return new No({...this._def,maxSize:{value:t,message:fe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}No.create=(e,t)=>new No({valueType:e,minSize:null,maxSize:null,typeName:oe.ZodSet,...Me(t)});class cf extends qe{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})}}cf.create=(e,t)=>new cf({getter:e,typeName:oe.ZodLazy,...Me(t)});class uf extends qe{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return ie(r,{received:r.data,code:ne.invalid_literal,expected:this._def.value}),Ie}return{status:"valid",value:t.data}}get value(){return this._def.value}}uf.create=(e,t)=>new uf({value:e,typeName:oe.ZodLiteral,...Me(t)});function df(e,t){return new Jn({values:e,typeName:oe.ZodEnum,...Me(t)})}class Jn extends qe{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return ie(r,{expected:Ue.joinValues(n),received:r.parsedType,code:ne.invalid_type}),Ie}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 ie(r,{received:r.data,code:ne.invalid_enum_value,options:n}),Ie}return Qt(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 Jn.create(t,{...this._def,...r})}exclude(t,r=this._def){return Jn.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}Jn.create=df;class pf extends qe{_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 ie(n,{expected:Ue.joinValues(o),received:n.parsedType,code:ne.invalid_type}),Ie}if(this._cache||(this._cache=new Set(Ue.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Ue.objectValues(r);return ie(n,{received:n.data,code:ne.invalid_enum_value,options:o}),Ie}return Qt(t.data)}get enum(){return this._def.values}}pf.create=(e,t)=>new pf({values:e,typeName:oe.ZodNativeEnum,...Me(t)});class Bs extends qe{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ue.promise&&r.common.async===!1)return ie(r,{code:ne.invalid_type,expected:ue.promise,received:r.parsedType}),Ie;const n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return Qt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Bs.create=(e,t)=>new Bs({type:e,typeName:oe.ZodPromise,...Me(t)});class Gn extends qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===oe.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:i=>{ie(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return Ie;const l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?Ie:l.status==="dirty"||r.value==="dirty"?Ro(l.value):l});{if(r.value==="aborted")return Ie;const a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?Ie:a.status==="dirty"||r.value==="dirty"?Ro(a.value):a}}if(o.type==="refinement"){const i=a=>{const l=o.refinement(a,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 a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ie:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?Ie:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Zn(i))return Ie;const a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Zn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):Ie);Ue.assertNever(o)}}Gn.create=(e,t,r)=>new Gn({schema:e,typeName:oe.ZodEffects,effect:t,...Me(r)}),Gn.createWithPreprocess=(e,t,r)=>new Gn({schema:t,effect:{type:"preprocess",transform:e},typeName:oe.ZodEffects,...Me(r)});class tn extends qe{_parse(t){return this._getType(t)===ue.undefined?Qt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}tn.create=(e,t)=>new tn({innerType:e,typeName:oe.ZodOptional,...Me(t)});class Wn extends qe{_parse(t){return this._getType(t)===ue.null?Qt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Wn.create=(e,t)=>new Wn({innerType:e,typeName:oe.ZodNullable,...Me(t)});class al extends qe{_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}}al.create=(e,t)=>new al({innerType:e,typeName:oe.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Me(t)});class il extends qe{_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 zs(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Or(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Or(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}il.create=(e,t)=>new il({innerType:e,typeName:oe.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Me(t)});class ff extends qe{_parse(t){if(this._getType(t)!==ue.nan){const n=this._getOrReturnCtx(t);return ie(n,{code:ne.invalid_type,expected:ue.nan,received:n.parsedType}),Ie}return{status:"valid",value:t.data}}}ff.create=e=>new ff({typeName:oe.ZodNaN,...Me(e)});class F3 extends qe{_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 ll extends qe{_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"?Ie:s.status==="dirty"?(r.dirty(),Ro(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"?Ie: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 ll({in:t,out:r,typeName:oe.ZodPipeline})}}class cl extends qe{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Zn(o)&&(o.value=Object.freeze(o.value)),o);return zs(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}}cl.create=(e,t)=>new cl({innerType:e,typeName:oe.ZodReadonly,...Me(t)});var oe;(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"})(oe||(oe={}));const Ke=Xr.create,Sr=Bn.create;en.create;const rn=Tr.create,ir=gt.create,ul=Vs.create;Zs.create,kn.create;const Hs=Jn.create;Bs.create,tn.create,Wn.create;class hf 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 dl(e){}function mf(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=dl,onError:r=dl,onRetry:n=dl,onComment:o}=e;let s="",i=!0,a,l="",c="";function u(v){const y=i?v.replace(/^\xEF\xBB\xBF/,""):v,[w,_]=V3(`${s}${y}`);for(const h of w)m(h);s=_,i=!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
31
|
`;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new hf(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new hf(`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:a,event:c||void 0,data:l.endsWith(`
|
|
32
|
-
`)?l.slice(0,-1):l}),a=void 0,l="",c=""}function g(v={}){s&&v.consume&&m(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:g}}function
|
|
32
|
+
`)?l.slice(0,-1):l}),a=void 0,l="",c=""}function g(v={}){s&&v.consume&&m(s),i=!0,a=void 0,l="",c="",s=""}return{feed:u,reset:g}}function V3(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
|
|
33
33
|
`,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]===`
|
|
34
|
-
`&&n++}}return[t,r]}class Kn extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=mf({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)}})}}function Mt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function z3({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},s={};for(const i of e)if(i.type==="provider"){const a=(n=r?.(i))!=null?n:i.id in t?t[i.id]:void 0;if(a==null)continue;o[i.name]=a,s[a]=i.name}return{toProviderToolName:i=>{var a;return(a=o[i])!=null?a:i},toCustomToolName:i=>{var a;return(a=s[i])!=null?a:i}}}async function F3(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(gf());return}const s=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(s),r?.removeEventListener("abort",a)},a=()=>{i(),o(gf())};r?.addEventListener("abort",a)})}function gf(){return new DOMException("Delay was aborted","AbortError")}var Mo=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 Yn(e){return Object.fromEntries([...e.headers])}var{btoa:V3,atob:Z3}=globalThis;function Qn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=Z3(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Xn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return V3(t)}function eo(e){return e instanceof Uint8Array?Xn(e):e}function B3(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 i=r?`${o}[]`:o;for(const a of s)n.append(i,a);continue}n.append(o,s)}return n}var yf="AI_DownloadError",_f=`vercel.ai.error.${yf}`,H3=Symbol.for(_f),vf,wf,Ft=class extends(wf=ge,vf=H3,wf){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:yf,message:o,cause:n}),this[vf]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ge.hasMarker(e,_f)}},dl=2*1024*1024*1024;async function bf({response:e,url:t,maxBytes:r=dl}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Ft({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(),i=[];let a=0;try{for(;;){const{done:u,value:m}=await s.read();if(u)break;if(a+=m.length,a>r)throw new Ft({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});i.push(m)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(a);let c=0;for(const u of i)l.set(u,c),c+=u.length;return l}function kf(e){let t;try{t=new URL(e)}catch{throw new Ft({url:e,message:`Invalid URL: ${e}`})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Ft({url:e,message:`URL scheme must be http or https, got ${t.protocol}`});const r=t.hostname;if(!r)throw new Ft({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Ft({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(J3(n))throw new Ft({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(Cf(r)){if(pl(r))throw new Ft({url:e,message:`URL with IP address ${r} is not allowed`});return}}function Cf(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function pl(e){const t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function J3(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(Cf(r))return pl(r);const n=r.split(":");if(n.length===2){const o=parseInt(n[0],16),s=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(s)){const i=o>>8&255,a=o&255,l=s>>8&255,c=s&255;return pl(`${i}.${a}.${l}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}async function Tf(e,t){var r,n;kf(e);try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new Ft({url:e,statusCode:o.status,statusText:o.statusText});const s=await bf({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:dl}),i=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],i?{type:i}:void 0)}catch(o){throw Ft.isInstance(o)?o:new Ft({url:e,cause:o})}}var Oo=({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 gd({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},qt=Oo();function fl(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Cn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var G3=["fetch failed","failed to fetch"],W3=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function K3(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&W3.includes(t))}function Sf({error:e,url:t,requestBodyValues:r}){if(Cn(e))return e;if(e instanceof TypeError&&G3.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ot({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return K3(e)?new ot({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Ao(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 Y3(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 nn(e,...t){const r=new Headers(Y3(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var If="4.0.19",Q3=()=>globalThis.fetch,xf=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=Q3()})=>{try{const i=await s(e,{method:"GET",headers:nn(t,`ai-sdk/provider-utils/${If}`,Ao()),signal:o}),a=Yn(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw Cn(c)||ot.isInstance(c)?c:new ot({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Cn(l)||ot.isInstance(l))?l:new ot({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}}catch(i){throw Sf({error:i,url:e,requestBodyValues:{}})}};function Ef(e){return e!=null}function X3({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function e9({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new $s({message:`${n} API key must be a string.`});if(typeof process>"u")throw new $s({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 $s({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new $s({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function to({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function t9(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 r9=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,n9=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function $f(e){const t=JSON.parse(e);return t===null||typeof t!="object"||r9.test(e)===!1&&n9.test(e)===!1?t:o9(t)}function o9(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")&&n.constructor!==null&&typeof n.constructor=="object"&&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 hl(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return $f(e)}try{return $f(e)}finally{Error.stackTraceLimit=t}}function ml(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]=Tn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Tn):Tn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Tn)),e.allOf!=null&&(e.allOf=e.allOf.map(Tn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Tn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Tn(t[r]);return e}function Tn(e){return typeof e=="boolean"?e:ml(e)}var s9=Symbol("Let zodToJsonSchema decide on which parser to use"),Rf={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"},a9=e=>typeof e=="string"?{...Rf,name:e}:{...Rf,...e};function Gt(){return{}}function i9(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)!==oe.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 l9(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 c9(){return{type:"boolean"}}function Pf(e,t){return Ve(e.type._def,t)}var u9=(e,t)=>Ve(e.innerType._def,t);function Nf(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Nf(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 d9(e)}}var d9=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 p9(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function f9(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Gt()}function h9(e){return{type:"string",enum:Array.from(e.values)}}var m9=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function g9(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(m9(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 y9(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 gl=void 0,lr={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:()=>(gl===void 0&&(gl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gl),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 Mf(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":cr(r,"email",n.message,t);break;case"format:idn-email":cr(r,"idn-email",n.message,t);break;case"pattern:zod":Lt(r,lr.email,n.message,t);break}break;case"url":cr(r,"uri",n.message,t);break;case"uuid":cr(r,"uuid",n.message,t);break;case"regex":Lt(r,n.regex,n.message,t);break;case"cuid":Lt(r,lr.cuid,n.message,t);break;case"cuid2":Lt(r,lr.cuid2,n.message,t);break;case"startsWith":Lt(r,RegExp(`^${yl(n.value,t)}`),n.message,t);break;case"endsWith":Lt(r,RegExp(`${yl(n.value,t)}$`),n.message,t);break;case"datetime":cr(r,"date-time",n.message,t);break;case"date":cr(r,"date",n.message,t);break;case"time":cr(r,"time",n.message,t);break;case"duration":cr(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":{Lt(r,RegExp(yl(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&cr(r,"ipv4",n.message,t),n.version!=="v4"&&cr(r,"ipv6",n.message,t);break}case"base64url":Lt(r,lr.base64url,n.message,t);break;case"jwt":Lt(r,lr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Lt(r,lr.ipv4Cidr,n.message,t),n.version!=="v4"&&Lt(r,lr.ipv6Cidr,n.message,t);break}case"emoji":Lt(r,lr.emoji(),n.message,t);break;case"ulid":{Lt(r,lr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{cr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Lt(r,lr.base64,n.message,t);break}}break}case"nanoid":Lt(r,lr.nanoid,n.message,t)}return r}function yl(e,t){return t.patternStrategy==="escape"?v9(e):e}var _9=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function v9(e){let t="";for(let r=0;r<e.length;r++)_9.has(e[r])||(t+="\\"),t+=e[r];return t}function cr(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 Lt(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:Of(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Of(t,n)}function Of(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
|
|
34
|
+
`&&n++}}return[t,r]}class Kn extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=mf({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)}})}}function Mt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Z3({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},s={};for(const i of e)if(i.type==="provider"){const a=(n=r?.(i))!=null?n:i.id in t?t[i.id]:void 0;if(a==null)continue;o[i.name]=a,s[a]=i.name}return{toProviderToolName:i=>{var a;return(a=o[i])!=null?a:i},toCustomToolName:i=>{var a;return(a=s[i])!=null?a:i}}}async function B3(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(gf());return}const s=setTimeout(()=>{i(),n()},e),i=()=>{clearTimeout(s),r?.removeEventListener("abort",a)},a=()=>{i(),o(gf())};r?.addEventListener("abort",a)})}function gf(){return new DOMException("Delay was aborted","AbortError")}var Mo=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 Yn(e){return Object.fromEntries([...e.headers])}var{btoa:H3,atob:J3}=globalThis;function Qn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=J3(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Xn(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return H3(t)}function eo(e){return e instanceof Uint8Array?Xn(e):e}function G3(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 i=r?`${o}[]`:o;for(const a of s)n.append(i,a);continue}n.append(o,s)}return n}var yf="AI_DownloadError",_f=`vercel.ai.error.${yf}`,W3=Symbol.for(_f),vf,wf,Ft=class extends(wf=ge,vf=W3,wf){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:yf,message:o,cause:n}),this[vf]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ge.hasMarker(e,_f)}},pl=2*1024*1024*1024;async function bf({response:e,url:t,maxBytes:r=pl}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new Ft({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(),i=[];let a=0;try{for(;;){const{done:u,value:m}=await s.read();if(u)break;if(a+=m.length,a>r)throw new Ft({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});i.push(m)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(a);let c=0;for(const u of i)l.set(u,c),c+=u.length;return l}function kf(e){let t;try{t=new URL(e)}catch{throw new Ft({url:e,message:`Invalid URL: ${e}`})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Ft({url:e,message:`URL scheme must be http or https, got ${t.protocol}`});const r=t.hostname;if(!r)throw new Ft({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new Ft({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(K3(n))throw new Ft({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(Cf(r)){if(fl(r))throw new Ft({url:e,message:`URL with IP address ${r} is not allowed`});return}}function Cf(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function fl(e){const t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function K3(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(Cf(r))return fl(r);const n=r.split(":");if(n.length===2){const o=parseInt(n[0],16),s=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(s)){const i=o>>8&255,a=o&255,l=s>>8&255,c=s&255;return fl(`${i}.${a}.${l}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}async function Tf(e,t){var r,n;kf(e);try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new Ft({url:e,statusCode:o.status,statusText:o.statusText});const s=await bf({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:pl}),i=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],i?{type:i}:void 0)}catch(o){throw Ft.isInstance(o)?o:new Ft({url:e,cause:o})}}var Oo=({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 gd({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},qt=Oo();function hl(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Cn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Y3=["fetch failed","failed to fetch"],Q3=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function X3(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&Q3.includes(t))}function Sf({error:e,url:t,requestBodyValues:r}){if(Cn(e))return e;if(e instanceof TypeError&&Y3.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ot({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return X3(e)?new ot({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function Ao(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 e9(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 nn(e,...t){const r=new Headers(e9(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var If="4.0.19",t9=()=>globalThis.fetch,xf=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=t9()})=>{try{const i=await s(e,{method:"GET",headers:nn(t,`ai-sdk/provider-utils/${If}`,Ao()),signal:o}),a=Yn(i);if(!i.ok){let l;try{l=await n({response:i,url:e,requestBodyValues:{}})}catch(c){throw Cn(c)||ot.isInstance(c)?c:new ot({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await r({response:i,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Cn(l)||ot.isInstance(l))?l:new ot({message:"Failed to process successful response",cause:l,statusCode:i.status,url:e,responseHeaders:a,requestBodyValues:{}})}}catch(i){throw Sf({error:i,url:e,requestBodyValues:{}})}};function Ef(e){return e!=null}function r9({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 n9({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new $s({message:`${n} API key must be a string.`});if(typeof process>"u")throw new $s({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 $s({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new $s({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function to({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function o9(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 s9=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,a9=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function $f(e){const t=JSON.parse(e);return t===null||typeof t!="object"||s9.test(e)===!1&&a9.test(e)===!1?t:i9(t)}function i9(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")&&n.constructor!==null&&typeof n.constructor=="object"&&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 ml(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return $f(e)}try{return $f(e)}finally{Error.stackTraceLimit=t}}function gl(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]=Tn(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(Tn):Tn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(Tn)),e.allOf!=null&&(e.allOf=e.allOf.map(Tn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(Tn));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=Tn(t[r]);return e}function Tn(e){return typeof e=="boolean"?e:gl(e)}var l9=Symbol("Let zodToJsonSchema decide on which parser to use"),Rf={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"},c9=e=>typeof e=="string"?{...Rf,name:e}:{...Rf,...e};function Gt(){return{}}function u9(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)!==oe.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 d9(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 p9(){return{type:"boolean"}}function Pf(e,t){return Ve(e.type._def,t)}var f9=(e,t)=>Ve(e.innerType._def,t);function Nf(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Nf(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 h9(e)}}var h9=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 m9(e,t){return{...Ve(e.innerType._def,t),default:e.defaultValue()}}function g9(e,t){return t.effectStrategy==="input"?Ve(e.schema._def,t):Gt()}function y9(e){return{type:"string",enum:Array.from(e.values)}}var _9=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function v9(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(_9(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 w9(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 yl=void 0,lr={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:()=>(yl===void 0&&(yl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),yl),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 Mf(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":cr(r,"email",n.message,t);break;case"format:idn-email":cr(r,"idn-email",n.message,t);break;case"pattern:zod":Lt(r,lr.email,n.message,t);break}break;case"url":cr(r,"uri",n.message,t);break;case"uuid":cr(r,"uuid",n.message,t);break;case"regex":Lt(r,n.regex,n.message,t);break;case"cuid":Lt(r,lr.cuid,n.message,t);break;case"cuid2":Lt(r,lr.cuid2,n.message,t);break;case"startsWith":Lt(r,RegExp(`^${_l(n.value,t)}`),n.message,t);break;case"endsWith":Lt(r,RegExp(`${_l(n.value,t)}$`),n.message,t);break;case"datetime":cr(r,"date-time",n.message,t);break;case"date":cr(r,"date",n.message,t);break;case"time":cr(r,"time",n.message,t);break;case"duration":cr(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":{Lt(r,RegExp(_l(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&cr(r,"ipv4",n.message,t),n.version!=="v4"&&cr(r,"ipv6",n.message,t);break}case"base64url":Lt(r,lr.base64url,n.message,t);break;case"jwt":Lt(r,lr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Lt(r,lr.ipv4Cidr,n.message,t),n.version!=="v4"&&Lt(r,lr.ipv6Cidr,n.message,t);break}case"emoji":Lt(r,lr.emoji(),n.message,t);break;case"ulid":{Lt(r,lr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{cr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Lt(r,lr.base64,n.message,t);break}}break}case"nanoid":Lt(r,lr.nanoid,n.message,t)}return r}function _l(e,t){return t.patternStrategy==="escape"?k9(e):e}var b9=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function k9(e){let t="";for(let r=0;r<e.length;r++)b9.has(e[r])||(t+="\\"),t+=e[r];return t}function cr(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 Lt(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:Of(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=Of(t,n)}function Of(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let s="",i=!1,a=!1,l=!1;for(let c=0;c<o.length;c++){if(i){s+=o[c],i=!1;continue}if(n.i){if(a){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
|
|
35
35
|
]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
|
|
36
36
|
]))`;continue}}if(n.s&&o[c]==="."){s+=a?`${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 Af(e,t){var r,n,o,s,i,a;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)===oe.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Mf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===oe.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===oe.ZodBranded&&e.keyType._def.type._def.typeName===oe.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=Pf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function w9(e,t){if(t.mapStrategy==="record")return Af(e,t);const r=Ve(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Gt(),n=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Gt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function b9(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 k9(){return{not:Gt()}}function C9(){return{type:"null"}}var _l={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function T9(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in _l&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const i=_l[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 S9(e,t)}var S9=(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 I9(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[_l[e.innerType._def.typeName],"null"]};const r=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function x9(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 E9(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=R9(a),c=Ve(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=$9(e,t);return s!==void 0&&(r.additionalProperties=s),r}function $9(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 R9(e){try{return e.isOptional()}catch{return!0}}var P9=(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:Gt()},n]}:Gt()},N9=(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 M9(e,t){return Ve(e.type._def,t)}function O9(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 A9(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 q9(){return{not:Gt()}}function L9(){return Gt()}var j9=(e,t)=>Ve(e.innerType._def,t),U9=(e,t,r)=>{switch(t){case oe.ZodString:return Mf(e,r);case oe.ZodNumber:return x9(e);case oe.ZodObject:return E9(e,r);case oe.ZodBigInt:return l9(e);case oe.ZodBoolean:return c9();case oe.ZodDate:return Nf(e,r);case oe.ZodUndefined:return q9();case oe.ZodNull:return C9();case oe.ZodArray:return i9(e,r);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return T9(e,r);case oe.ZodIntersection:return g9(e,r);case oe.ZodTuple:return A9(e,r);case oe.ZodRecord:return Af(e,r);case oe.ZodLiteral:return y9(e);case oe.ZodEnum:return h9(e);case oe.ZodNativeEnum:return b9(e);case oe.ZodNullable:return I9(e,r);case oe.ZodOptional:return P9(e,r);case oe.ZodMap:return w9(e,r);case oe.ZodSet:return O9(e,r);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return M9(e,r);case oe.ZodNaN:case oe.ZodNever:return k9();case oe.ZodEffects:return f9(e,r);case oe.ZodAny:return Gt();case oe.ZodUnknown:return L9();case oe.ZodDefault:return p9(e,r);case oe.ZodBranded:return Pf(e,r);case oe.ZodReadonly:return j9(e,r);case oe.ZodCatch:return u9(e,r);case oe.ZodPipeline:return N9(e,r);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(n=>{})()}},D9=(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!==s9)return l}if(o&&!r){const l=z9(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=U9(e,e.typeName,t),a=typeof i=="function"?Ve(i(),t):i;if(a&&F9(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var z9=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:D9(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`),Gt()):t.$refStrategy==="seen"?Gt():void 0}},F9=(e,t,r)=>(e.description&&(r.description=e.description),r),V9=e=>{const t=a9(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}]))}},Z9=(e,t)=>{var r;const n=V9(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:Gt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Ve(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:Gt(),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},vl=Symbol.for("vercel.ai.schema");function ve(e){let t;return()=>(t==null&&(t=e()),t)}function ro(e,{validate:t}={}){return{[vl]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function B9(e){return typeof e=="object"&&e!==null&&vl in e&&e[vl]===!0&&"jsonSchema"in e&&"validate"in e}function Sn(e){return e==null?ro({properties:{},additionalProperties:!1}):B9(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?_e(e):H9(e):e()}function H9(e){return ro(()=>ml(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 vn({value:t,cause:r.issues})}}})}function J9(e,t){var r;const n=(r=void 0)!=null?r:!1;return ro(()=>Z9(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 G9(e,t){var r;const n=(r=void 0)!=null?r:!1;return ro(()=>ml(pb(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Pp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function W9(e){return"_zod"in e}function _e(e,t){return W9(e)?G9(e):J9(e)}async function kt({value:e,schema:t,context:r}){const n=await Xt({value:e,schema:t,context:r});if(!n.success)throw vn.wrap({value:e,cause:n.error,context:r});return n.value}async function Xt({value:e,schema:t,context:r}){const n=Sn(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:vn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:vn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function K9({text:e,schema:t}){try{const r=hl(e);return t==null?r:kt({value:r,schema:t})}catch(r){throw Es.isInstance(r)||vn.isInstance(r)?r:new Es({text:e,cause:r})}}async function er({text:e,schema:t}){try{const r=hl(e);return t==null?{success:!0,value:r,rawValue:r}:await Xt({value:r,schema:t})}catch(r){return{success:!1,error:Es.isInstance(r)?r:new Es({text:e,cause:r}),rawValue:void 0}}}function qf(e){try{return hl(e),!0}catch{return!1}}function Lf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await er({text:r,schema:t}))}}))}async function Ar({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Xt({value:t[e],schema:r});if(!n.success)throw new gd({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Y9=()=>globalThis.fetch,Vt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Uf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),jf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Uf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Uf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=Y9()})=>{try{const a=await i(e,{method:"POST",headers:nn(t,`ai-sdk/provider-utils/${If}`,Ao()),body:r.content,signal:s}),l=Yn(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw Cn(u)||ot.isInstance(u)?u:new ot({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:a,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Cn(c)||ot.isInstance(c))?c:new ot({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw Sf({error:a,url:e,requestBodyValues:r.values})}};function VE(e){return e}function Df(e){return{...e,type:"dynamic"}}function Q9({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l})}function ur({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:i,onInputStart:a,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:i,onInputStart:a,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Zt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var on=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=Yn(n);if(i.trim()==="")return{responseHeaders:a,value:new ot({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await K9({text:i,schema:e});return{responseHeaders:a,value:new ot({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:a,value:new ot({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},Js=e=>async({response:t})=>{const r=Yn(t);if(t.body==null)throw new uv({});return{responseHeaders:r,value:Lf({stream:t.body,schema:e})}},tr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await er({text:o,schema:e}),i=Yn(t);if(!s.success)throw new ot({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}},X9=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Yn(e);if(!e.body)throw new ot({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 ot({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function zf(e){return e?.replace(/\/$/,"")}function e4(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*t4({execute:e,input:t,options:r}){const n=e(t,r);if(e4(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 wl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var bl,Ff;function r4(){if(Ff)return bl;Ff=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},i=u=>s(e({},"__esModule",{value:!0}),u),a={};o(a,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),bl=i(a);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return bl}var kl,Vf;function n4(){if(Vf)return kl;Vf=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},i=m=>s(e({},"__esModule",{value:!0}),m),a={};o(a,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),kl=i(a);var l=r4();async function c(){return""}function u(){return""}return kl}var Zf=n4(),o4="vercel.ai.gateway.error",Cl=Symbol.for(o4),Bf,Hf,jt=class nv extends(Hf=Error,Bf=Cl,Hf){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[Bf]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return nv.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Cl in t&&t[Cl]===!0}},Jf="GatewayAuthenticationError",s4=`vercel.ai.gateway.error.${Jf}`,Gf=Symbol.for(s4),Wf,Kf,Tl=class ov extends(Kf=jt,Wf=Gf,Kf){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Wf]=!0,this.name=Jf,this.type="authentication_error"}static isInstance(t){return jt.hasMarker(t)&&Gf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:i}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
|
|
38
|
+
]`;continue}s+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function Af(e,t){var r,n,o,s,i,a;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)===oe.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=Mf(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===oe.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===oe.ZodBranded&&e.keyType._def.type._def.typeName===oe.ZodString&&((a=e.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...u}=Pf(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function C9(e,t){if(t.mapStrategy==="record")return Af(e,t);const r=Ve(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Gt(),n=Ve(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Gt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function T9(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 S9(){return{not:Gt()}}function I9(){return{type:"null"}}var vl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function x9(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in vl&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const i=vl[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 E9(e,t)}var E9=(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 $9(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[vl[e.innerType._def.typeName],"null"]};const r=Ve(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function R9(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 P9(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=M9(a),c=Ve(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=N9(e,t);return s!==void 0&&(r.additionalProperties=s),r}function N9(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 M9(e){try{return e.isOptional()}catch{return!0}}var O9=(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:Gt()},n]}:Gt()},A9=(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 q9(e,t){return Ve(e.type._def,t)}function L9(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 j9(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 U9(){return{not:Gt()}}function D9(){return Gt()}var z9=(e,t)=>Ve(e.innerType._def,t),F9=(e,t,r)=>{switch(t){case oe.ZodString:return Mf(e,r);case oe.ZodNumber:return R9(e);case oe.ZodObject:return P9(e,r);case oe.ZodBigInt:return d9(e);case oe.ZodBoolean:return p9();case oe.ZodDate:return Nf(e,r);case oe.ZodUndefined:return U9();case oe.ZodNull:return I9();case oe.ZodArray:return u9(e,r);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return x9(e,r);case oe.ZodIntersection:return v9(e,r);case oe.ZodTuple:return j9(e,r);case oe.ZodRecord:return Af(e,r);case oe.ZodLiteral:return w9(e);case oe.ZodEnum:return y9(e);case oe.ZodNativeEnum:return T9(e);case oe.ZodNullable:return $9(e,r);case oe.ZodOptional:return O9(e,r);case oe.ZodMap:return C9(e,r);case oe.ZodSet:return L9(e,r);case oe.ZodLazy:return()=>e.getter()._def;case oe.ZodPromise:return q9(e,r);case oe.ZodNaN:case oe.ZodNever:return S9();case oe.ZodEffects:return g9(e,r);case oe.ZodAny:return Gt();case oe.ZodUnknown:return D9();case oe.ZodDefault:return m9(e,r);case oe.ZodBranded:return Pf(e,r);case oe.ZodReadonly:return z9(e,r);case oe.ZodCatch:return f9(e,r);case oe.ZodPipeline:return A9(e,r);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(n=>{})()}},V9=(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!==l9)return l}if(o&&!r){const l=Z9(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=F9(e,e.typeName,t),a=typeof i=="function"?Ve(i(),t):i;if(a&&B9(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return s.jsonSchema=a,l}return s.jsonSchema=a,a}var Z9=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:V9(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`),Gt()):t.$refStrategy==="seen"?Gt():void 0}},B9=(e,t,r)=>(e.description&&(r.description=e.description),r),H9=e=>{const t=c9(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}]))}},J9=(e,t)=>{var r;const n=H9(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:Gt()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=(r=Ve(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:Gt(),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},wl=Symbol.for("vercel.ai.schema");function ve(e){let t;return()=>(t==null&&(t=e()),t)}function ro(e,{validate:t}={}){return{[wl]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function G9(e){return typeof e=="object"&&e!==null&&wl in e&&e[wl]===!0&&"jsonSchema"in e&&"validate"in e}function Sn(e){return e==null?ro({properties:{},additionalProperties:!1}):G9(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?_e(e):W9(e):e()}function W9(e){return ro(()=>gl(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 vn({value:t,cause:r.issues})}}})}function K9(e,t){var r;const n=(r=void 0)!=null?r:!1;return ro(()=>J9(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 Y9(e,t){var r;const n=(r=void 0)!=null?r:!1;return ro(()=>gl(mb(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Pp(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Q9(e){return"_zod"in e}function _e(e,t){return Q9(e)?Y9(e):K9(e)}async function kt({value:e,schema:t,context:r}){const n=await Xt({value:e,schema:t,context:r});if(!n.success)throw vn.wrap({value:e,cause:n.error,context:r});return n.value}async function Xt({value:e,schema:t,context:r}){const n=Sn(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:vn.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:vn.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function X9({text:e,schema:t}){try{const r=ml(e);return t==null?r:kt({value:r,schema:t})}catch(r){throw Es.isInstance(r)||vn.isInstance(r)?r:new Es({text:e,cause:r})}}async function er({text:e,schema:t}){try{const r=ml(e);return t==null?{success:!0,value:r,rawValue:r}:await Xt({value:r,schema:t})}catch(r){return{success:!1,error:Es.isInstance(r)?r:new Es({text:e,cause:r}),rawValue:void 0}}}function qf(e){try{return ml(e),!0}catch{return!1}}function Lf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await er({text:r,schema:t}))}}))}async function Ar({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Xt({value:t[e],schema:r});if(!n.success)throw new gd({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var e4=()=>globalThis.fetch,Vt=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Uf({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),jf=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Uf({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Uf=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=e4()})=>{try{const a=await i(e,{method:"POST",headers:nn(t,`ai-sdk/provider-utils/${If}`,Ao()),body:r.content,signal:s}),l=Yn(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw Cn(u)||ot.isInstance(u)?u:new ot({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:a,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Cn(c)||ot.isInstance(c))?c:new ot({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw Sf({error:a,url:e,requestBodyValues:r.values})}};function VE(e){return e}function Df(e){return{...e,type:"dynamic"}}function t4({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:s,onInputStart:i,onInputDelta:a,onInputAvailable:l})}function ur({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:i,onInputStart:a,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:i,onInputStart:a,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Zt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var on=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=Yn(n);if(i.trim()==="")return{responseHeaders:a,value:new ot({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await X9({text:i,schema:e});return{responseHeaders:a,value:new ot({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:a,value:new ot({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},Js=e=>async({response:t})=>{const r=Yn(t);if(t.body==null)throw new fv({});return{responseHeaders:r,value:Lf({stream:t.body,schema:e})}},tr=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await er({text:o,schema:e}),i=Yn(t);if(!s.success)throw new ot({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:i,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:i,value:s.value,rawValue:s.rawValue}},r4=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Yn(e);if(!e.body)throw new ot({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 ot({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function zf(e){return e?.replace(/\/$/,"")}function n4(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*o4({execute:e,input:t,options:r}){const n=e(t,r);if(n4(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 bl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var kl,Ff;function s4(){if(Ff)return kl;Ff=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},i=u=>s(e({},"__esModule",{value:!0}),u),a={};o(a,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),kl=i(a);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return kl}var Cl,Vf;function a4(){if(Vf)return Cl;Vf=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},i=m=>s(e({},"__esModule",{value:!0}),m),a={};o(a,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Cl=i(a);var l=s4();async function c(){return""}function u(){return""}return Cl}var Zf=a4(),i4="vercel.ai.gateway.error",Tl=Symbol.for(i4),Bf,Hf,jt=class av extends(Hf=Error,Bf=Tl,Hf){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[Bf]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return av.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Tl in t&&t[Tl]===!0}},Jf="GatewayAuthenticationError",l4=`vercel.ai.gateway.error.${Jf}`,Gf=Symbol.for(l4),Wf,Kf,Sl=class iv extends(Kf=jt,Wf=Gf,Kf){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Wf]=!0,this.name=Jf,this.type="authentication_error"}static isInstance(t){return jt.hasMarker(t)&&Gf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:i}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
|
|
39
39
|
|
|
40
40
|
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
41
41
|
|
|
@@ -50,9 +50,9 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
|
50
50
|
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
51
51
|
|
|
52
52
|
Option 2 - OIDC token:
|
|
53
|
-
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new
|
|
53
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new iv({message:a,statusCode:o,cause:s,generationId:i})}},Yf="GatewayInvalidRequestError",c4=`vercel.ai.gateway.error.${Yf}`,Qf=Symbol.for(c4),Xf,eh,u4=class extends(eh=jt,Xf=Qf,eh){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Xf]=!0,this.name=Yf,this.type="invalid_request_error"}static isInstance(e){return jt.hasMarker(e)&&Qf in e}},th="GatewayRateLimitError",d4=`vercel.ai.gateway.error.${th}`,rh=Symbol.for(d4),nh,oh,p4=class extends(oh=jt,nh=rh,oh){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[nh]=!0,this.name=th,this.type="rate_limit_exceeded"}static isInstance(e){return jt.hasMarker(e)&&rh in e}},sh="GatewayModelNotFoundError",f4=`vercel.ai.gateway.error.${sh}`,ah=Symbol.for(f4),h4=ve(()=>_e(C({modelId:d()}))),ih,lh,m4=class extends(lh=jt,ih=ah,lh){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[ih]=!0,this.name=sh,this.type="model_not_found",this.modelId=r}static isInstance(e){return jt.hasMarker(e)&&ah in e}},ch="GatewayInternalServerError",g4=`vercel.ai.gateway.error.${ch}`,uh=Symbol.for(g4),dh,ph,fh=class extends(ph=jt,dh=uh,ph){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[dh]=!0,this.name=ch,this.type="internal_server_error"}static isInstance(e){return jt.hasMarker(e)&&uh in e}},hh="GatewayResponseError",y4=`vercel.ai.gateway.error.${hh}`,mh=Symbol.for(y4),gh,yh,_4=class extends(yh=jt,gh=mh,yh){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[gh]=!0,this.name=hh,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return jt.hasMarker(e)&&mh in e}};async function _h({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const i=await Xt({value:e,schema:v4});if(!i.success){const m=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new _4({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:i.error,cause:n,generationId:m})}const a=i.value,l=a.error.type,c=a.error.message,u=(s=a.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Sl.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new u4({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new p4({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const m=await Xt({value:a.error.param,schema:h4});return new m4({message:c,statusCode:t,modelId:m.success?m.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new fh({message:c,statusCode:t,cause:n,generationId:u});default:return new fh({message:c,statusCode:t,cause:n,generationId:u})}}var v4=ve(()=>_e(C({error:C({message:d(),type:d().nullish(),param:$e().nullish(),code:ae([d(),U()]).nullish()}),generationId:d().nullish()}))),vh="GatewayTimeoutError",w4=`vercel.ai.gateway.error.${vh}`,wh=Symbol.for(w4),bh,kh,Ch=class lv extends(kh=jt,bh=wh,kh){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[bh]=!0,this.name=vh,this.type="timeout_error"}static isInstance(t){return jt.hasMarker(t)&&wh in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
|
|
54
54
|
|
|
55
|
-
This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new sv({message:s,statusCode:r,cause:n,generationId:o})}};function Th(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 qr(e,t){var r;return jt.isInstance(e)?e:Th(e)?Ch.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ot.isInstance(e)?e.cause&&Th(e.cause)?Ch.createTimeoutError({originalMessage:e.message,cause:e}):await _h({response:_4(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await _h({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function _4(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Sh="ai-gateway-auth-method";async function In(e){const t=await Xt({value:e[Sh],schema:v4});return t.success?t.value:void 0}var v4=ve(()=>_e(ae([R("api-key"),R("oidc")]))),Ih=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await xf({url:`${this.config.baseURL}/config`,headers:await Zt(this.config.headers()),successfulResponseHandler:tr(w4),failedResponseHandler:on({errorSchema:bt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await qr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await xf({url:`${e.origin}/v1/credits`,headers:await Zt(this.config.headers()),successfulResponseHandler:tr(b4),failedResponseHandler:on({errorSchema:bt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await qr(e)}}},w4=ve(()=>_e(C({models:q(C({id:d(),name:d(),description:d().nullish(),pricing:C({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:R("v3"),provider:d(),modelId:d()}),modelType:me(["embedding","image","language","video"]).nullish()}))}))),b4=ve(()=>_e(C({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),k4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Zt(this.config.headers());try{const{responseHeaders:s,value:i,rawValue:a}=await Vt({url:this.getUrl(),headers:Mt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Zt(this.config.o11yHeaders)),body:t,successfulResponseHandler:tr(bt()),failedResponseHandler:on({errorSchema:bt(),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 qr(s,await In(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Zt(this.config.headers());try{const{value:s,responseHeaders:i}=await Vt({url:this.getUrl(),headers:Mt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Zt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Js(bt()),failedResponseHandler:on({errorSchema:bt(),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 qr(s,await In(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)}}},C4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Zt(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:l}=await Vt({url:this.getUrl(),headers:Mt(s,t??{},this.getModelConfigHeaders(),await Zt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:tr(T4),failedResponseHandler:on({errorSchema:bt(),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},warnings:[]}}catch(i){throw await qr(i,await In(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},T4=ve(()=>_e(C({embeddings:q(q(U())),usage:C({tokens:U()}).nullish(),providerMetadata:ye(d(),ye(d(),$e())).optional()}))),S4=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:i,providerOptions:a,headers:l,abortSignal:c}){var u,m,p,f;const g=await Zt(this.config.headers());try{const{responseHeaders:v,value:y,rawValue:w}=await Vt({url:this.getUrl(),headers:Mt(g,l??{},this.getModelConfigHeaders(),await Zt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...a&&{providerOptions:a},...s&&{files:s.map(_=>xh(_))},...i&&{mask:xh(i)}},successfulResponseHandler:tr($4),failedResponseHandler:on({errorSchema:bt(),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 qr(v,await In(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function xh(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Xn(e.data)}:e}var I4=C({images:q($e()).optional()}).catchall($e()),x4=je("type",[C({type:R("unsupported"),feature:d(),details:d().optional()}),C({type:R("compatibility"),feature:d(),details:d().optional()}),C({type:R("other"),message:d()})]),E4=C({inputTokens:U().nullish(),outputTokens:U().nullish(),totalTokens:U().nullish()}),$4=C({images:q(d()),warnings:q(x4).optional(),providerMetadata:ye(d(),I4).optional(),usage:E4.optional()}),R4=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:i,image:a,providerOptions:l,headers:c,abortSignal:u}){var m;const p=await Zt(this.config.headers());try{const{responseHeaders:f,value:g}=await Vt({url:this.getUrl(),headers:Mt(p,c??{},this.getModelConfigHeaders(),await Zt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...i&&{seed:i},...l&&{providerOptions:l},...a&&{image:P4(a)}},successfulResponseHandler:async({response:v,url:y,requestBodyValues:w})=>{if(v.body==null)throw new ot({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:v.status});const h=Lf({stream:v.body,schema:A4}).getReader(),{done:T,value:b}=await h.read();if(h.releaseLock(),T||!b)throw new ot({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:v.status});if(!b.success)throw new ot({message:"Failed to parse video SSE event",cause:b.error,url:y,requestBodyValues:w,statusCode:v.status});const k=b.value;if(k.type==="error")throw new ot({message:k.message,statusCode:k.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([...v.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...v.headers])}},failedResponseHandler:on({errorSchema:bt(),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 qr(f,await In(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function P4(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Xn(e.data)}:e}var N4=C({videos:q($e()).optional()}).catchall($e()),M4=ae([C({type:R("url"),url:d(),mediaType:d()}),C({type:R("base64"),data:d(),mediaType:d()})]),O4=je("type",[C({type:R("unsupported"),feature:d(),details:d().optional()}),C({type:R("compatibility"),feature:d(),details:d().optional()}),C({type:R("other"),message:d()})]),A4=je("type",[C({type:R("result"),videos:q(M4),warnings:q(O4).optional(),providerMetadata:ye(d(),N4).optional()}),C({type:R("error"),message:d(),errorType:d(),statusCode:U(),param:$e().nullable()})]),q4=ve(()=>_e(ir({objective:Ke().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:rn(Ke()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Hs(["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:Sr().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:ir({include_domains:rn(Ke()).optional().describe("List of domains to include in search results."),exclude_domains:rn(Ke()).optional().describe("List of domains to exclude from search results."),after_date:Ke().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:ir({max_chars_per_result:Sr().optional().describe("Maximum characters per result."),max_chars_total:Sr().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:ir({max_age_seconds:Sr().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.")}))),L4=ve(()=>_e(cl([ir({searchId:Ke(),results:rn(ir({url:Ke(),title:Ke(),excerpt:Ke(),publishDate:Ke().nullable().optional(),relevanceScore:Sr().optional()}))}),ir({error:Hs(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Sr().optional(),message:Ke()})]))),j4=ur({id:"gateway.parallel_search",inputSchema:q4,outputSchema:L4}),U4=(e={})=>j4(e),D4=ve(()=>_e(ir({query:cl([Ke(),rn(Ke())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Sr().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Sr().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Sr().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ke().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:rn(Ke()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:rn(Ke()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ke().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Ke().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Ke().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Ke().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Hs(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),z4=ve(()=>_e(cl([ir({results:rn(ir({title:Ke(),url:Ke(),snippet:Ke(),date:Ke().optional(),lastUpdated:Ke().optional()})),id:Ke()}),ir({error:Hs(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Sr().optional(),message:Ke()})]))),F4=ur({id:"gateway.perplexity_search",inputSchema:D4,outputSchema:z4}),V4=(e={})=>F4(e),Z4={parallelSearch:U4,perplexitySearch:V4};async function B4(){var e;return(e=Zf.getContext().headers)==null?void 0:e["x-vercel-id"]}var H4="3.0.66",J4="0.0.1";function G4(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=zf(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const v=await K4(e);return nn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":J4,[Sh]:v.authMethod,...e.headers},`ai-sdk/gateway/${H4}`)}catch(v){throw Tl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},c=()=>{const v=to({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=to({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=to({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),_=to({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const h=await B4();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 k4(v,{provider:"gateway",baseURL:a,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||_-i>s)&&(i=_,n=new Ih({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(h=>(o=h,h)).catch(async h=>{throw await qr(h,await In(await l()))})),o?Promise.resolve(o):n},p=async()=>new Ih({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await qr(v,await In(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 S4(v,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const g=v=>new C4(v,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=g,f.textEmbeddingModel=g,f.videoModel=v=>new R4(v,{provider:"gateway",baseURL:a,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=Z4,f}var W4=G4();async function K4(e){const t=to({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Zf.getVercelOidcToken(),authMethod:"oidc"}}var Y4=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},xn="1.9.0",Eh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Q4(e){var t=new Set([e]),r=new Set,n=e.match(Eh);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(Eh);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 X4=Q4(xn),e6=xn.split(".")[0],qo=Symbol.for("opentelemetry.js.api."+e6),Lo=Y4;function jo(e,t,r,n){var o;n===void 0&&(n=!1);var s=Lo[qo]=(o=Lo[qo])!==null&&o!==void 0?o:{version:xn};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!==xn){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+xn);return r.error(i.stack||i.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+xn+"."),!0}function En(e){var t,r,n=(t=Lo[qo])===null||t===void 0?void 0:t.version;if(!(!n||!X4(n)))return(r=Lo[qo])===null||r===void 0?void 0:r[e]}function Uo(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+xn+".");var r=Lo[qo];r&&delete r[e]}var t6=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},r6=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))},n6=(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 Do("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("verbose",this._namespace,t)},e})();function Do(e,t,r){var n=En("diag");if(n)return r.unshift(t),n[e].apply(n,r6([],t6(r),!1))}var Wt;(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"})(Wt||(Wt={}));function o6(e,t){e<Wt.NONE?e=Wt.NONE:e>Wt.ALL&&(e=Wt.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",Wt.ERROR),warn:r("warn",Wt.WARN),info:r("info",Wt.INFO),debug:r("debug",Wt.DEBUG),verbose:r("verbose",Wt.VERBOSE)}}var s6=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},a6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},i6="diag",Ir=(function(){function e(){function t(o){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=En("diag");if(a)return a[o].apply(a,a6([],s6(s),!1))}}var r=this,n=function(o,s){var i,a,l;if(s===void 0&&(s={logLevel:Wt.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=En("diag"),m=o6((a=s.logLevel)!==null&&a!==void 0?a:Wt.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 jo("diag",m,r,!0)};r.setLogger=n,r.disable=function(){Uo(i6,r)},r.createComponentLogger=function(o){return new n6(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})(),l6=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},c6=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.")},u6=(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=l6(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=c6(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})();Ir.instance();function d6(e){return e===void 0&&(e={}),new u6(new Map(Object.entries(e)))}function $h(e){return Symbol.for(e)}var p6=(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})(),f6=new p6,$n=(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)}})(),h6=(function(){function e(){}return e.prototype.createGauge=function(t,r){return T6},e.prototype.createHistogram=function(t,r){return S6},e.prototype.createCounter=function(t,r){return C6},e.prototype.createUpDownCounter=function(t,r){return I6},e.prototype.createObservableGauge=function(t,r){return E6},e.prototype.createObservableCounter=function(t,r){return x6},e.prototype.createObservableUpDownCounter=function(t,r){return $6},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Gs=(function(){function e(){}return e})(),m6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Gs),g6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Gs),y6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Gs),_6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Gs),Sl=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),v6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Sl),w6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Sl),b6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Sl),k6=new h6,C6=new m6,T6=new y6,S6=new _6,I6=new g6,x6=new v6,E6=new w6,$6=new b6,R6={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},P6={set:function(e,t,r){e!=null&&(e[t]=r)}},N6=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},M6=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))},O6=(function(){function e(){}return e.prototype.active=function(){return f6},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,M6([n],N6(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),A6=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},q6=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))},Il="context",L6=new O6,Ws=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return jo(Il,t,Ir.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,q6([t,r,n],A6(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return En(Il)||L6},e.prototype.disable=function(){this._getContextManager().disable(),Uo(Il,Ir.instance())},e})(),xl;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(xl||(xl={}));var Rh="0000000000000000",Ph="00000000000000000000000000000000",j6={traceId:Ph,spanId:Rh,traceFlags:xl.NONE},zo=(function(){function e(t){t===void 0&&(t=j6),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})(),El=$h("OpenTelemetry Context Key SPAN");function $l(e){return e.getValue(El)||void 0}function U6(){return $l(Ws.getInstance().active())}function Rl(e,t){return e.setValue(El,t)}function D6(e){return e.deleteValue(El)}function z6(e,t){return Rl(e,new zo(t))}function Nh(e){var t;return(t=$l(e))===null||t===void 0?void 0:t.spanContext()}var F6=/^([0-9a-f]{32})$/i,V6=/^[0-9a-f]{16}$/i;function Z6(e){return F6.test(e)&&e!==Ph}function B6(e){return V6.test(e)&&e!==Rh}function Mh(e){return Z6(e.traceId)&&B6(e.spanId)}function H6(e){return new zo(e)}var Pl=Ws.getInstance(),Oh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Pl.active());var o=!!r?.root;if(o)return new zo;var s=n&&Nh(n);return J6(s)&&Mh(s)?new zo(s):new zo},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??Pl.active(),c=this.startSpan(t,s,l),u=Rl(l,c);return Pl.with(u,a,void 0,c)}},e})();function J6(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var G6=new Oh,W6=(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):G6},e})(),K6=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Oh},e})(),Y6=new K6,Ah=(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 W6(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Y6},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})(),Ks;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ks||(Ks={}));var qh=Ws.getInstance();Ir.instance();var Q6=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return k6},e})(),X6=new Q6,Nl="metrics",ek=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return jo(Nl,t,Ir.instance())},e.prototype.getMeterProvider=function(){return En(Nl)||X6},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Uo(Nl,Ir.instance())},e})();ek.getInstance();var tk=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Ml=$h("OpenTelemetry Baggage Key");function Lh(e){return e.getValue(Ml)||void 0}function rk(){return Lh(Ws.getInstance().active())}function nk(e,t){return e.setValue(Ml,t)}function ok(e){return e.deleteValue(Ml)}var Ol="propagation",sk=new tk,ak=(function(){function e(){this.createBaggage=d6,this.getBaggage=Lh,this.getActiveBaggage=rk,this.setBaggage=nk,this.deleteBaggage=ok}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return jo(Ol,t,Ir.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=P6),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=R6),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Uo(Ol,Ir.instance())},e.prototype._getGlobalPropagator=function(){return En(Ol)||sk},e})();ak.getInstance();var Al="trace",ik=(function(){function e(){this._proxyTracerProvider=new Ah,this.wrapSpanContext=H6,this.isSpanContextValid=Mh,this.deleteSpan=D6,this.getSpan=$l,this.getActiveSpan=U6,this.getSpanContext=Nh,this.setSpan=Rl,this.setSpanContext=z6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=jo(Al,this._proxyTracerProvider,Ir.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return En(Al)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Uo(Al,Ir.instance()),this._proxyTracerProvider=new Ah},e})(),lk=ik.getInstance(),ck=Object.defineProperty,uk=(e,t)=>{for(var r in t)ck(e,r,{get:t[r],enumerable:!0})},jh="AI_InvalidArgumentError",Uh=`vercel.ai.error.${jh}`,dk=Symbol.for(Uh),Dh,xr=class extends ge{constructor({parameter:t,value:r,message:n}){super({name:jh,message:`Invalid argument for parameter ${t}: ${n}`}),this[Dh]=!0,this.parameter=t,this.value=r}static isInstance(t){return ge.hasMarker(t,Uh)}};Dh=dk;var zh="AI_InvalidToolApprovalError",Fh=`vercel.ai.error.${zh}`,pk=Symbol.for(Fh),Vh,fk=class extends ge{constructor({approvalId:e}){super({name:zh,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[Vh]=!0,this.approvalId=e}static isInstance(e){return ge.hasMarker(e,Fh)}};Vh=pk;var Zh="AI_InvalidToolInputError",Bh=`vercel.ai.error.${Zh}`,hk=Symbol.for(Bh),Hh,ql=class extends ge{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${yn(r)}`}){super({name:Zh,message:n,cause:r}),this[Hh]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ge.hasMarker(e,Bh)}};Hh=hk;var Jh="AI_ToolCallNotFoundForApprovalError",Gh=`vercel.ai.error.${Jh}`,mk=Symbol.for(Gh),Wh,Ll=class extends ge{constructor({toolCallId:e,approvalId:t}){super({name:Jh,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Wh]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ge.hasMarker(e,Gh)}};Wh=mk;var Kh="AI_MissingToolResultsError",Yh=`vercel.ai.error.${Kh}`,gk=Symbol.for(Yh),Qh,Xh=class extends ge{constructor({toolCallIds:e}){super({name:Kh,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Qh]=!0,this.toolCallIds=e}static isInstance(e){return ge.hasMarker(e,Yh)}};Qh=gk;var e0="AI_NoObjectGeneratedError",t0=`vercel.ai.error.${e0}`,yk=Symbol.for(t0),r0,sn=class extends ge{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:e0,message:e,cause:t}),this[r0]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ge.hasMarker(e,t0)}};r0=yk;var n0="AI_NoOutputGeneratedError",o0=`vercel.ai.error.${n0}`,_k=Symbol.for(o0),s0,a0=class extends ge{constructor({message:e="No output generated.",cause:t}={}){super({name:n0,message:e,cause:t}),this[s0]=!0}static isInstance(e){return ge.hasMarker(e,o0)}};s0=_k;var i0="AI_NoSuchToolError",l0=`vercel.ai.error.${i0}`,vk=Symbol.for(l0),c0,jl=class extends ge{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:i0,message:r}),this[c0]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ge.hasMarker(e,l0)}};c0=vk;var u0="AI_ToolCallRepairError",d0=`vercel.ai.error.${u0}`,wk=Symbol.for(d0),p0,bk=class extends ge{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${yn(e)}`}){super({name:u0,message:r,cause:e}),this[p0]=!0,this.originalError=t}static isInstance(e){return ge.hasMarker(e,d0)}};p0=wk;var kk=class extends ge{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},f0="AI_UIMessageStreamError",h0=`vercel.ai.error.${f0}`,Ck=Symbol.for(h0),m0,no=class extends ge{constructor({chunkType:e,chunkId:t,message:r}){super({name:f0,message:r}),this[m0]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ge.hasMarker(e,h0)}};m0=Ck;var g0="AI_InvalidMessageRoleError",y0=`vercel.ai.error.${g0}`,Tk=Symbol.for(y0),_0,Sk=class extends ge{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:g0,message:t}),this[_0]=!0,this.role=e}static isInstance(e){return ge.hasMarker(e,y0)}};_0=Tk;var v0="AI_RetryError",w0=`vercel.ai.error.${v0}`,Ik=Symbol.for(w0),b0,k0=class extends ge{constructor({message:e,reason:t,errors:r}){super({name:v0,message:e}),this[b0]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ge.hasMarker(e,w0)}};b0=Ik;function Rn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function dr(e){for(const t of Rn(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function xk({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 Ek="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",C0=!1,Ul=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}C0||(C0=!0,console.info(Ek));for(const r of e.warnings)console.warn(xk({warning:r,provider:e.provider,model:e.model}))}};function $k({provider:e,modelId:t}){Ul({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function Rk(e){return e.specificationVersion==="v3"?e:($k({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:T0(o.finishReason),usage:S0(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:Pk(o.stream)}};default:return t[r]}}}))}function Pk(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:T0(t.finishReason),usage:S0(t.usage)});break;default:r.enqueue(t);break}}}))}function T0(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function S0(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 Ys(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new kk({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return Rk(e)}return Nk().languageModel(e)}function Nk(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:W4}function Dl(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function I0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function Mk(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var Ok=[{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]}],Ak=e=>{const t=typeof e=="string"?Qn(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function qk(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Ak(e):e}function Lk({data:e,signatures:t}){const r=qk(e),n=typeof r=="string"?Qn(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 x0="6.0.116",jk=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();kf(o);try{const s=await fetch(o,{headers:nn({},`ai-sdk/${x0}`,Ao()),signal:r});if(!s.ok)throw new Ft({url:o,statusCode:s.status,statusText:s.statusText});return{data:await bf({response:s,url:o,maxBytes:t??dl}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Ft.isInstance(s)?s:new Ft({url:o,cause:s})}},Uk=(e=jk)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function Dk(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 E0=ae([d(),Ds(Uint8Array),Ds(ArrayBuffer),Zp(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function $0(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}=Dk(e.toString());if(t==null||r==null)throw new ge({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function zk(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Xn(new Uint8Array(e)):Xn(e)}async function R0({prompt:e,supportedUrls:t,download:r=Uk()}){const n=await Vk(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 i=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Rn(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>Fk({message:c,downloadedAssets:n}))],a=[];for(const c of i){if(c.role!=="tool"){a.push(c);continue}const u=a.at(-1);u?.role==="tool"?u.content.push(...c.content):a.push(c)}const l=new Set;for(const c of a)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 Xh({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Xh({toolCallIds:Array.from(l)});return a.filter(c=>c.role!=="tool"||c.content.length>0)}function Fk({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=>Zk(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:i}=$0(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:P0(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:P0(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 Sk({role:n})}}}async function Vk(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&&X3({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 Zk(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}=$0(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=Lk({data:l,signatures:Ok}))!=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 P0(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 Fo({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:yn(r)}:o==="json"?{type:"error-json",value:N0(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:N0(r)}}function N0(e){return e===void 0?null:e}function zl({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 xr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new xr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new xr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new xr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new xr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new xr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new xr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new xr({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 Bk(e){return e!=null&&Object.keys(e).length>0}async function M0({tools:e,toolChoice:t,activeTools:r}){if(!Bk(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,i]of n){const a=i.type;switch(a){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:i.description,inputSchema:await Sn(i.inputSchema).jsonSchema,...i.inputExamples!=null?{inputExamples:i.inputExamples}:{},providerOptions:i.providerOptions,...i.strict!=null?{strict:i.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:i.id,args:i.args});break;default:{const l=a;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 Vo=el(()=>ae([Us(),d(),U(),he(),ye(d(),Vo.optional()),q(Vo)])),it=ye(d(),ye(d(),Vo.optional())),O0=C({type:R("text"),text:d(),providerOptions:it.optional()}),Hk=C({type:R("image"),image:ae([E0,Ds(URL)]),mediaType:d().optional(),providerOptions:it.optional()}),A0=C({type:R("file"),data:ae([E0,Ds(URL)]),filename:d().optional(),mediaType:d(),providerOptions:it.optional()}),Jk=C({type:R("reasoning"),text:d(),providerOptions:it.optional()}),Gk=C({type:R("tool-call"),toolCallId:d(),toolName:d(),input:$e(),providerOptions:it.optional(),providerExecuted:he().optional()}),Wk=je("type",[C({type:R("text"),value:d(),providerOptions:it.optional()}),C({type:R("json"),value:Vo,providerOptions:it.optional()}),C({type:R("execution-denied"),reason:d().optional(),providerOptions:it.optional()}),C({type:R("error-text"),value:d(),providerOptions:it.optional()}),C({type:R("error-json"),value:Vo,providerOptions:it.optional()}),C({type:R("content"),value:q(ae([C({type:R("text"),text:d(),providerOptions:it.optional()}),C({type:R("media"),data:d(),mediaType:d()}),C({type:R("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:it.optional()}),C({type:R("file-url"),url:d(),providerOptions:it.optional()}),C({type:R("file-id"),fileId:ae([d(),ye(d(),d())]),providerOptions:it.optional()}),C({type:R("image-data"),data:d(),mediaType:d(),providerOptions:it.optional()}),C({type:R("image-url"),url:d(),providerOptions:it.optional()}),C({type:R("image-file-id"),fileId:ae([d(),ye(d(),d())]),providerOptions:it.optional()}),C({type:R("custom"),providerOptions:it.optional()})]))})]),q0=C({type:R("tool-result"),toolCallId:d(),toolName:d(),output:Wk,providerOptions:it.optional()}),Kk=C({type:R("tool-approval-request"),approvalId:d(),toolCallId:d()}),Yk=C({type:R("tool-approval-response"),approvalId:d(),approved:he(),reason:d().optional()}),Qk=C({role:R("system"),content:d(),providerOptions:it.optional()}),Xk=C({role:R("user"),content:ae([d(),q(ae([O0,Hk,A0]))]),providerOptions:it.optional()}),eC=C({role:R("assistant"),content:ae([d(),q(ae([O0,A0,Jk,Gk,q0,Kk]))]),providerOptions:it.optional()}),tC=C({role:R("tool"),content:q(ae([q0,Yk])),providerOptions:it.optional()}),rC=ae([Qk,Xk,eC,tC]);async function L0(e){if(e.prompt==null&&e.messages==null)throw new _n({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new _n({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Rn(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new _n({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 _n({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new _n({prompt:e,message:"messages must not be empty"});const r=await Xt({value:t,schema:q(rC)});if(!r.success)throw new _n({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function j0(e){if(!Tl.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 ge({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
55
|
+
This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new lv({message:s,statusCode:r,cause:n,generationId:o})}};function Th(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 qr(e,t){var r;return jt.isInstance(e)?e:Th(e)?Ch.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ot.isInstance(e)?e.cause&&Th(e.cause)?Ch.createTimeoutError({originalMessage:e.message,cause:e}):await _h({response:b4(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await _h({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function b4(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Sh="ai-gateway-auth-method";async function In(e){const t=await Xt({value:e[Sh],schema:k4});return t.success?t.value:void 0}var k4=ve(()=>_e(ae([R("api-key"),R("oidc")]))),Ih=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await xf({url:`${this.config.baseURL}/config`,headers:await Zt(this.config.headers()),successfulResponseHandler:tr(C4),failedResponseHandler:on({errorSchema:bt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await qr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await xf({url:`${e.origin}/v1/credits`,headers:await Zt(this.config.headers()),successfulResponseHandler:tr(T4),failedResponseHandler:on({errorSchema:bt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await qr(e)}}},C4=ve(()=>_e(C({models:q(C({id:d(),name:d(),description:d().nullish(),pricing:C({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:R("v3"),provider:d(),modelId:d()}),modelType:me(["embedding","image","language","video"]).nullish()}))}))),T4=ve(()=>_e(C({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),S4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Zt(this.config.headers());try{const{responseHeaders:s,value:i,rawValue:a}=await Vt({url:this.getUrl(),headers:Mt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Zt(this.config.o11yHeaders)),body:t,successfulResponseHandler:tr(bt()),failedResponseHandler:on({errorSchema:bt(),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 qr(s,await In(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Zt(this.config.headers());try{const{value:s,responseHeaders:i}=await Vt({url:this.getUrl(),headers:Mt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Zt(this.config.o11yHeaders)),body:t,successfulResponseHandler:Js(bt()),failedResponseHandler:on({errorSchema:bt(),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 qr(s,await In(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)}}},I4=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Zt(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:l}=await Vt({url:this.getUrl(),headers:Mt(s,t??{},this.getModelConfigHeaders(),await Zt(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:tr(x4),failedResponseHandler:on({errorSchema:bt(),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},warnings:[]}}catch(i){throw await qr(i,await In(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},x4=ve(()=>_e(C({embeddings:q(q(U())),usage:C({tokens:U()}).nullish(),providerMetadata:ye(d(),ye(d(),$e())).optional()}))),E4=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:i,providerOptions:a,headers:l,abortSignal:c}){var u,m,p,f;const g=await Zt(this.config.headers());try{const{responseHeaders:v,value:y,rawValue:w}=await Vt({url:this.getUrl(),headers:Mt(g,l??{},this.getModelConfigHeaders(),await Zt(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...a&&{providerOptions:a},...s&&{files:s.map(_=>xh(_))},...i&&{mask:xh(i)}},successfulResponseHandler:tr(N4),failedResponseHandler:on({errorSchema:bt(),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 qr(v,await In(g))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function xh(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Xn(e.data)}:e}var $4=C({images:q($e()).optional()}).catchall($e()),R4=je("type",[C({type:R("unsupported"),feature:d(),details:d().optional()}),C({type:R("compatibility"),feature:d(),details:d().optional()}),C({type:R("other"),message:d()})]),P4=C({inputTokens:U().nullish(),outputTokens:U().nullish(),totalTokens:U().nullish()}),N4=C({images:q(d()),warnings:q(R4).optional(),providerMetadata:ye(d(),$4).optional(),usage:P4.optional()}),M4=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:i,image:a,providerOptions:l,headers:c,abortSignal:u}){var m;const p=await Zt(this.config.headers());try{const{responseHeaders:f,value:g}=await Vt({url:this.getUrl(),headers:Mt(p,c??{},this.getModelConfigHeaders(),await Zt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...i&&{seed:i},...l&&{providerOptions:l},...a&&{image:O4(a)}},successfulResponseHandler:async({response:v,url:y,requestBodyValues:w})=>{if(v.body==null)throw new ot({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:v.status});const h=Lf({stream:v.body,schema:j4}).getReader(),{done:T,value:b}=await h.read();if(h.releaseLock(),T||!b)throw new ot({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:v.status});if(!b.success)throw new ot({message:"Failed to parse video SSE event",cause:b.error,url:y,requestBodyValues:w,statusCode:v.status});const k=b.value;if(k.type==="error")throw new ot({message:k.message,statusCode:k.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([...v.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([...v.headers])}},failedResponseHandler:on({errorSchema:bt(),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 qr(f,await In(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function O4(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Xn(e.data)}:e}var A4=C({videos:q($e()).optional()}).catchall($e()),q4=ae([C({type:R("url"),url:d(),mediaType:d()}),C({type:R("base64"),data:d(),mediaType:d()})]),L4=je("type",[C({type:R("unsupported"),feature:d(),details:d().optional()}),C({type:R("compatibility"),feature:d(),details:d().optional()}),C({type:R("other"),message:d()})]),j4=je("type",[C({type:R("result"),videos:q(q4),warnings:q(L4).optional(),providerMetadata:ye(d(),A4).optional()}),C({type:R("error"),message:d(),errorType:d(),statusCode:U(),param:$e().nullable()})]),U4=ve(()=>_e(ir({objective:Ke().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:rn(Ke()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Hs(["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:Sr().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:ir({include_domains:rn(Ke()).optional().describe("List of domains to include in search results."),exclude_domains:rn(Ke()).optional().describe("List of domains to exclude from search results."),after_date:Ke().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:ir({max_chars_per_result:Sr().optional().describe("Maximum characters per result."),max_chars_total:Sr().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:ir({max_age_seconds:Sr().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),D4=ve(()=>_e(ul([ir({searchId:Ke(),results:rn(ir({url:Ke(),title:Ke(),excerpt:Ke(),publishDate:Ke().nullable().optional(),relevanceScore:Sr().optional()}))}),ir({error:Hs(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Sr().optional(),message:Ke()})]))),z4=ur({id:"gateway.parallel_search",inputSchema:U4,outputSchema:D4}),F4=(e={})=>z4(e),V4=ve(()=>_e(ir({query:ul([Ke(),rn(Ke())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Sr().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Sr().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Sr().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ke().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:rn(Ke()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:rn(Ke()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ke().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Ke().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Ke().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Ke().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Hs(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),Z4=ve(()=>_e(ul([ir({results:rn(ir({title:Ke(),url:Ke(),snippet:Ke(),date:Ke().optional(),lastUpdated:Ke().optional()})),id:Ke()}),ir({error:Hs(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Sr().optional(),message:Ke()})]))),B4=ur({id:"gateway.perplexity_search",inputSchema:V4,outputSchema:Z4}),H4=(e={})=>B4(e),J4={parallelSearch:F4,perplexitySearch:H4};async function G4(){var e;return(e=Zf.getContext().headers)==null?void 0:e["x-vercel-id"]}var W4="3.0.66",K4="0.0.1";function Y4(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=zf(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const v=await X4(e);return nn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":K4,[Sh]:v.authMethod,...e.headers},`ai-sdk/gateway/${W4}`)}catch(v){throw Sl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},c=()=>{const v=to({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=to({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),w=to({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),_=to({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const h=await G4();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 S4(v,{provider:"gateway",baseURL:a,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||_-i>s)&&(i=_,n=new Ih({baseURL:a,headers:l,fetch:e.fetch}).getAvailableModels().then(h=>(o=h,h)).catch(async h=>{throw await qr(h,await In(await l()))})),o?Promise.resolve(o):n},p=async()=>new Ih({baseURL:a,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await qr(v,await In(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 E4(v,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()}),f.languageModel=u;const g=v=>new I4(v,{provider:"gateway",baseURL:a,headers:l,fetch:e.fetch,o11yHeaders:c()});return f.embeddingModel=g,f.textEmbeddingModel=g,f.videoModel=v=>new M4(v,{provider:"gateway",baseURL:a,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=J4,f}var Q4=Y4();async function X4(e){const t=to({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Zf.getVercelOidcToken(),authMethod:"oidc"}}var e6=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},xn="1.9.0",Eh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function t6(e){var t=new Set([e]),r=new Set,n=e.match(Eh);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(Eh);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 r6=t6(xn),n6=xn.split(".")[0],qo=Symbol.for("opentelemetry.js.api."+n6),Lo=e6;function jo(e,t,r,n){var o;n===void 0&&(n=!1);var s=Lo[qo]=(o=Lo[qo])!==null&&o!==void 0?o:{version:xn};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!==xn){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+xn);return r.error(i.stack||i.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+xn+"."),!0}function En(e){var t,r,n=(t=Lo[qo])===null||t===void 0?void 0:t.version;if(!(!n||!r6(n)))return(r=Lo[qo])===null||r===void 0?void 0:r[e]}function Uo(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+xn+".");var r=Lo[qo];r&&delete r[e]}var o6=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},s6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},a6=(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 Do("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Do("verbose",this._namespace,t)},e})();function Do(e,t,r){var n=En("diag");if(n)return r.unshift(t),n[e].apply(n,s6([],o6(r),!1))}var Wt;(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"})(Wt||(Wt={}));function i6(e,t){e<Wt.NONE?e=Wt.NONE:e>Wt.ALL&&(e=Wt.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",Wt.ERROR),warn:r("warn",Wt.WARN),info:r("info",Wt.INFO),debug:r("debug",Wt.DEBUG),verbose:r("verbose",Wt.VERBOSE)}}var l6=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},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))},u6="diag",Ir=(function(){function e(){function t(o){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=En("diag");if(a)return a[o].apply(a,c6([],l6(s),!1))}}var r=this,n=function(o,s){var i,a,l;if(s===void 0&&(s={logLevel:Wt.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=En("diag"),m=i6((a=s.logLevel)!==null&&a!==void 0?a:Wt.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 jo("diag",m,r,!0)};r.setLogger=n,r.disable=function(){Uo(u6,r)},r.createComponentLogger=function(o){return new a6(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})(),d6=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},p6=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.")},f6=(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=d6(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=p6(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})();Ir.instance();function h6(e){return e===void 0&&(e={}),new f6(new Map(Object.entries(e)))}function $h(e){return Symbol.for(e)}var m6=(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})(),g6=new m6,$n=(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)}})(),y6=(function(){function e(){}return e.prototype.createGauge=function(t,r){return x6},e.prototype.createHistogram=function(t,r){return E6},e.prototype.createCounter=function(t,r){return I6},e.prototype.createUpDownCounter=function(t,r){return $6},e.prototype.createObservableGauge=function(t,r){return P6},e.prototype.createObservableCounter=function(t,r){return R6},e.prototype.createObservableUpDownCounter=function(t,r){return N6},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Gs=(function(){function e(){}return e})(),_6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Gs),v6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Gs),w6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Gs),b6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Gs),Il=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),k6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Il),C6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Il),T6=(function(e){$n(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Il),S6=new y6,I6=new _6,x6=new w6,E6=new b6,$6=new v6,R6=new k6,P6=new C6,N6=new T6,M6={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},O6={set:function(e,t,r){e!=null&&(e[t]=r)}},A6=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],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},q6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},L6=(function(){function e(){}return e.prototype.active=function(){return g6},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,q6([n],A6(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),j6=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},U6=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},xl="context",D6=new L6,Ws=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return jo(xl,t,Ir.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,U6([t,r,n],j6(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return En(xl)||D6},e.prototype.disable=function(){this._getContextManager().disable(),Uo(xl,Ir.instance())},e})(),El;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(El||(El={}));var Rh="0000000000000000",Ph="00000000000000000000000000000000",z6={traceId:Ph,spanId:Rh,traceFlags:El.NONE},zo=(function(){function e(t){t===void 0&&(t=z6),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})(),$l=$h("OpenTelemetry Context Key SPAN");function Rl(e){return e.getValue($l)||void 0}function F6(){return Rl(Ws.getInstance().active())}function Pl(e,t){return e.setValue($l,t)}function V6(e){return e.deleteValue($l)}function Z6(e,t){return Pl(e,new zo(t))}function Nh(e){var t;return(t=Rl(e))===null||t===void 0?void 0:t.spanContext()}var B6=/^([0-9a-f]{32})$/i,H6=/^[0-9a-f]{16}$/i;function J6(e){return B6.test(e)&&e!==Ph}function G6(e){return H6.test(e)&&e!==Rh}function Mh(e){return J6(e.traceId)&&G6(e.spanId)}function W6(e){return new zo(e)}var Nl=Ws.getInstance(),Oh=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=Nl.active());var o=!!r?.root;if(o)return new zo;var s=n&&Nh(n);return K6(s)&&Mh(s)?new zo(s):new zo},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??Nl.active(),c=this.startSpan(t,s,l),u=Pl(l,c);return Nl.with(u,a,void 0,c)}},e})();function K6(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var Y6=new Oh,Q6=(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):Y6},e})(),X6=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new Oh},e})(),ek=new X6,Ah=(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 Q6(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:ek},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})(),Ks;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ks||(Ks={}));var qh=Ws.getInstance();Ir.instance();var tk=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return S6},e})(),rk=new tk,Ml="metrics",nk=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return jo(Ml,t,Ir.instance())},e.prototype.getMeterProvider=function(){return En(Ml)||rk},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){Uo(Ml,Ir.instance())},e})();nk.getInstance();var ok=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),Ol=$h("OpenTelemetry Baggage Key");function Lh(e){return e.getValue(Ol)||void 0}function sk(){return Lh(Ws.getInstance().active())}function ak(e,t){return e.setValue(Ol,t)}function ik(e){return e.deleteValue(Ol)}var Al="propagation",lk=new ok,ck=(function(){function e(){this.createBaggage=h6,this.getBaggage=Lh,this.getActiveBaggage=sk,this.setBaggage=ak,this.deleteBaggage=ik}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return jo(Al,t,Ir.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=O6),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=M6),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Uo(Al,Ir.instance())},e.prototype._getGlobalPropagator=function(){return En(Al)||lk},e})();ck.getInstance();var ql="trace",uk=(function(){function e(){this._proxyTracerProvider=new Ah,this.wrapSpanContext=W6,this.isSpanContextValid=Mh,this.deleteSpan=V6,this.getSpan=Rl,this.getActiveSpan=F6,this.getSpanContext=Nh,this.setSpan=Pl,this.setSpanContext=Z6}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=jo(ql,this._proxyTracerProvider,Ir.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return En(ql)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){Uo(ql,Ir.instance()),this._proxyTracerProvider=new Ah},e})(),dk=uk.getInstance(),pk=Object.defineProperty,fk=(e,t)=>{for(var r in t)pk(e,r,{get:t[r],enumerable:!0})},jh="AI_InvalidArgumentError",Uh=`vercel.ai.error.${jh}`,hk=Symbol.for(Uh),Dh,xr=class extends ge{constructor({parameter:t,value:r,message:n}){super({name:jh,message:`Invalid argument for parameter ${t}: ${n}`}),this[Dh]=!0,this.parameter=t,this.value=r}static isInstance(t){return ge.hasMarker(t,Uh)}};Dh=hk;var zh="AI_InvalidToolApprovalError",Fh=`vercel.ai.error.${zh}`,mk=Symbol.for(Fh),Vh,gk=class extends ge{constructor({approvalId:e}){super({name:zh,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[Vh]=!0,this.approvalId=e}static isInstance(e){return ge.hasMarker(e,Fh)}};Vh=mk;var Zh="AI_InvalidToolInputError",Bh=`vercel.ai.error.${Zh}`,yk=Symbol.for(Bh),Hh,Ll=class extends ge{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${yn(r)}`}){super({name:Zh,message:n,cause:r}),this[Hh]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ge.hasMarker(e,Bh)}};Hh=yk;var Jh="AI_ToolCallNotFoundForApprovalError",Gh=`vercel.ai.error.${Jh}`,_k=Symbol.for(Gh),Wh,jl=class extends ge{constructor({toolCallId:e,approvalId:t}){super({name:Jh,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Wh]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ge.hasMarker(e,Gh)}};Wh=_k;var Kh="AI_MissingToolResultsError",Yh=`vercel.ai.error.${Kh}`,vk=Symbol.for(Yh),Qh,Xh=class extends ge{constructor({toolCallIds:e}){super({name:Kh,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Qh]=!0,this.toolCallIds=e}static isInstance(e){return ge.hasMarker(e,Yh)}};Qh=vk;var e0="AI_NoObjectGeneratedError",t0=`vercel.ai.error.${e0}`,wk=Symbol.for(t0),r0,sn=class extends ge{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:e0,message:e,cause:t}),this[r0]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ge.hasMarker(e,t0)}};r0=wk;var n0="AI_NoOutputGeneratedError",o0=`vercel.ai.error.${n0}`,bk=Symbol.for(o0),s0,a0=class extends ge{constructor({message:e="No output generated.",cause:t}={}){super({name:n0,message:e,cause:t}),this[s0]=!0}static isInstance(e){return ge.hasMarker(e,o0)}};s0=bk;var i0="AI_NoSuchToolError",l0=`vercel.ai.error.${i0}`,kk=Symbol.for(l0),c0,Ul=class extends ge{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:i0,message:r}),this[c0]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ge.hasMarker(e,l0)}};c0=kk;var u0="AI_ToolCallRepairError",d0=`vercel.ai.error.${u0}`,Ck=Symbol.for(d0),p0,Tk=class extends ge{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${yn(e)}`}){super({name:u0,message:r,cause:e}),this[p0]=!0,this.originalError=t}static isInstance(e){return ge.hasMarker(e,d0)}};p0=Ck;var Sk=class extends ge{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},f0="AI_UIMessageStreamError",h0=`vercel.ai.error.${f0}`,Ik=Symbol.for(h0),m0,no=class extends ge{constructor({chunkType:e,chunkId:t,message:r}){super({name:f0,message:r}),this[m0]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ge.hasMarker(e,h0)}};m0=Ik;var g0="AI_InvalidMessageRoleError",y0=`vercel.ai.error.${g0}`,xk=Symbol.for(y0),_0,Ek=class extends ge{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:g0,message:t}),this[_0]=!0,this.role=e}static isInstance(e){return ge.hasMarker(e,y0)}};_0=xk;var v0="AI_RetryError",w0=`vercel.ai.error.${v0}`,$k=Symbol.for(w0),b0,k0=class extends ge{constructor({message:e,reason:t,errors:r}){super({name:v0,message:e}),this[b0]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ge.hasMarker(e,w0)}};b0=$k;function Rn(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function dr(e){for(const t of Rn(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function Rk({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 Pk="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",C0=!1,Dl=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}C0||(C0=!0,console.info(Pk));for(const r of e.warnings)console.warn(Rk({warning:r,provider:e.provider,model:e.model}))}};function Nk({provider:e,modelId:t}){Dl({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function Mk(e){return e.specificationVersion==="v3"?e:(Nk({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:T0(o.finishReason),usage:S0(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:Ok(o.stream)}};default:return t[r]}}}))}function Ok(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:T0(t.finishReason),usage:S0(t.usage)});break;default:r.enqueue(t);break}}}))}function T0(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function S0(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 Ys(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new Sk({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return Mk(e)}return Ak().languageModel(e)}function Ak(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Q4}function zl(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function I0(e){if(!(e==null||typeof e=="number"))return e.stepMs}function qk(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var Lk=[{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]}],jk=e=>{const t=typeof e=="string"?Qn(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function Uk(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?jk(e):e}function Dk({data:e,signatures:t}){const r=Uk(e),n=typeof r=="string"?Qn(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 x0="6.0.116",zk=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();kf(o);try{const s=await fetch(o,{headers:nn({},`ai-sdk/${x0}`,Ao()),signal:r});if(!s.ok)throw new Ft({url:o,statusCode:s.status,statusText:s.statusText});return{data:await bf({response:s,url:o,maxBytes:t??pl}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw Ft.isInstance(s)?s:new Ft({url:o,cause:s})}},Fk=(e=zk)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function Vk(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 E0=ae([d(),Ds(Uint8Array),Ds(ArrayBuffer),Zp(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function $0(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}=Vk(e.toString());if(t==null||r==null)throw new ge({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function Zk(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Xn(new Uint8Array(e)):Xn(e)}async function R0({prompt:e,supportedUrls:t,download:r=Fk()}){const n=await Hk(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 i=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:Rn(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>Bk({message:c,downloadedAssets:n}))],a=[];for(const c of i){if(c.role!=="tool"){a.push(c);continue}const u=a.at(-1);u?.role==="tool"?u.content.push(...c.content):a.push(c)}const l=new Set;for(const c of a)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 Xh({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Xh({toolCallIds:Array.from(l)});return a.filter(c=>c.role!=="tool"||c.content.length>0)}function Bk({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=>Jk(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:i}=$0(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:P0(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:P0(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 Ek({role:n})}}}async function Hk(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&&r9({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 Jk(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}=$0(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=Dk({data:l,signatures:Lk}))!=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 P0(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 Fo({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:yn(r)}:o==="json"?{type:"error-json",value:N0(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:N0(r)}}function N0(e){return e===void 0?null:e}function Fl({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 xr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new xr({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new xr({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new xr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new xr({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new xr({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new xr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(i!=null&&!Number.isInteger(i))throw new xr({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 Gk(e){return e!=null&&Object.keys(e).length>0}async function M0({tools:e,toolChoice:t,activeTools:r}){if(!Gk(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,i]of n){const a=i.type;switch(a){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:i.description,inputSchema:await Sn(i.inputSchema).jsonSchema,...i.inputExamples!=null?{inputExamples:i.inputExamples}:{},providerOptions:i.providerOptions,...i.strict!=null?{strict:i.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:i.id,args:i.args});break;default:{const l=a;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 Vo=tl(()=>ae([Us(),d(),U(),he(),ye(d(),Vo.optional()),q(Vo)])),it=ye(d(),ye(d(),Vo.optional())),O0=C({type:R("text"),text:d(),providerOptions:it.optional()}),Wk=C({type:R("image"),image:ae([E0,Ds(URL)]),mediaType:d().optional(),providerOptions:it.optional()}),A0=C({type:R("file"),data:ae([E0,Ds(URL)]),filename:d().optional(),mediaType:d(),providerOptions:it.optional()}),Kk=C({type:R("reasoning"),text:d(),providerOptions:it.optional()}),Yk=C({type:R("tool-call"),toolCallId:d(),toolName:d(),input:$e(),providerOptions:it.optional(),providerExecuted:he().optional()}),Qk=je("type",[C({type:R("text"),value:d(),providerOptions:it.optional()}),C({type:R("json"),value:Vo,providerOptions:it.optional()}),C({type:R("execution-denied"),reason:d().optional(),providerOptions:it.optional()}),C({type:R("error-text"),value:d(),providerOptions:it.optional()}),C({type:R("error-json"),value:Vo,providerOptions:it.optional()}),C({type:R("content"),value:q(ae([C({type:R("text"),text:d(),providerOptions:it.optional()}),C({type:R("media"),data:d(),mediaType:d()}),C({type:R("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:it.optional()}),C({type:R("file-url"),url:d(),providerOptions:it.optional()}),C({type:R("file-id"),fileId:ae([d(),ye(d(),d())]),providerOptions:it.optional()}),C({type:R("image-data"),data:d(),mediaType:d(),providerOptions:it.optional()}),C({type:R("image-url"),url:d(),providerOptions:it.optional()}),C({type:R("image-file-id"),fileId:ae([d(),ye(d(),d())]),providerOptions:it.optional()}),C({type:R("custom"),providerOptions:it.optional()})]))})]),q0=C({type:R("tool-result"),toolCallId:d(),toolName:d(),output:Qk,providerOptions:it.optional()}),Xk=C({type:R("tool-approval-request"),approvalId:d(),toolCallId:d()}),eC=C({type:R("tool-approval-response"),approvalId:d(),approved:he(),reason:d().optional()}),tC=C({role:R("system"),content:d(),providerOptions:it.optional()}),rC=C({role:R("user"),content:ae([d(),q(ae([O0,Wk,A0]))]),providerOptions:it.optional()}),nC=C({role:R("assistant"),content:ae([d(),q(ae([O0,A0,Kk,Yk,q0,Xk]))]),providerOptions:it.optional()}),oC=C({role:R("tool"),content:q(ae([q0,eC])),providerOptions:it.optional()}),sC=ae([tC,rC,nC,oC]);async function L0(e){if(e.prompt==null&&e.messages==null)throw new _n({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new _n({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!Rn(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new _n({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 _n({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new _n({prompt:e,message:"messages must not be empty"});const r=await Xt({value:t,schema:q(sC)});if(!r.success)throw new _n({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function j0(e){if(!Sl.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 ge({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
56
56
|
|
|
57
57
|
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
58
58
|
|
|
@@ -60,13 +60,13 @@ Alternatively, you can use a provider module instead of the AI Gateway.
|
|
|
60
60
|
|
|
61
61
|
Learn more: \x1B[34m${r}\x1B[0m
|
|
62
62
|
|
|
63
|
-
`),{name:"GatewayAuthenticationError"})}function 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 U0({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])=>{if(i==="timeout"){const l=
|
|
64
|
-
`)}function K0(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Y0=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=Xn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Qn(this.base64Data)),this.uint8ArrayData}},lC=class extends Y0{constructor(e){super(e),this.type="file"}};async function Q0({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 cC={};uk(cC,{array:()=>pC,choice:()=>fC,json:()=>hC,object:()=>dC,text:()=>ta});function uC(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(n,l+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let a=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?a+="true".slice(u.length):"false".startsWith(u)?a+="false".slice(u.length):"null".startsWith(u)&&(a+="null".slice(u.length))}}return a}async function Ho(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await er({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await er({text:uC(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var ta=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),dC=({schema:e,name:t,description:r})=>{const n=Sn(e);return{name:"object",responseFormat:Zt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const i=await er({text:o});if(!i.success)throw new sn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=await Xt({value:i.value,schema:n});if(!a.success)throw new sn({message:"No object generated: response did not match schema.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return a.value},async parsePartialOutput({text:o}){const s=await Ho(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},pC=({element:e,name:t,description:r})=>{const n=Sn(e);return{name:"array",responseFormat:Zt(n.jsonSchema).then(o=>{const{$schema:s,...i}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:i}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const i=await er({text:o});if(!i.success)throw new sn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=i.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))throw new sn({message:"No object generated: response did not match schema.",cause:new vn({value:a,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 a.elements){const c=await Xt({value:l,schema:n});if(!c.success)throw new sn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return a.elements},async parsePartialOutput({text:o}){const s=await Ho(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const i=s.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))return;const a=s.state==="repaired-parse"&&i.elements.length>0?i.elements.slice(0,-1):i.elements,l=[];for(const c of a){const u=await Xt({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},i){if(s!=null)for(;o<s.length;o++)i.enqueue(s[o])}})}}},fC=({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 er({text:n});if(!s.success)throw new sn({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=s.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string"||!e.includes(i.result))throw new sn({message:"No object generated: response did not match schema.",cause:new vn({value:i,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.result},async parsePartialOutput({text:n}){const o=await Ho(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 i=e.filter(a=>a.startsWith(s.result));return o.state==="successful-parse"?i.includes(s.result)?{partial:s.result}:void 0:i.length===1?{partial:i[0]}:void 0}}},createElementStreamTransform(){}}),hC=({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 er({text:r});if(!o.success)throw new sn({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 Ho(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 X0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await em(e);throw new jl({toolName:e.toolName})}try{return await tm({toolCall:e,tools:t})}catch(i){if(r==null||!(jl.isInstance(i)||ql.isInstance(i)))throw i;let a=null;try{a=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await Sn(c).jsonSchema},system:n,messages:o,error:i})}catch(l){throw new bk({cause:l,originalError:i})}if(a==null)throw i;return await tm({toolCall:a,tools:t})}}catch(i){const a=await er({text:e.input}),l=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:i,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function em(e){const t=e.input.trim()===""?{success:!0,value:{}}:await er({text:e.input});if(t.success===!1)throw new ql({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 tm({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await em(e);throw new jl({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Sn(n.inputSchema),s=e.input.trim()===""?await Xt({value:{},schema:o}):await er({text:e.input,schema:o});if(s.success===!1)throw new ql({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 rm=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:i,rawFinishReason:a,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=i,this.rawFinishReason=a,this.usage=l,this.warnings=c,this.request=u,this.response=m,this.providerMetadata=p}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function Zl(e){return({steps:t})=>t.length===e}async function nm({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Bl({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 i=await Fo({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:i,providerOptions:s.providerMetadata});break}case"tool-error":{const i=await Fo({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:i,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 i=await Fo({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:i,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function om(...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 mC=Oo({prefix:"aitxt",size:24});async function sm({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=Zl(1),experimental_output:m,output:p=m,experimental_telemetry:f,providerOptions:g,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:w,prepareStep:_=w,experimental_repairToolCall:h,experimental_download:T,experimental_context:b,experimental_include:k,_internal:{generateId:S=mC}={},experimental_onStart:I,experimental_onStepStart:x,experimental_onToolCallStart:j,experimental_onToolCallFinish:M,onStepFinish:D,onFinish:A,...O}){const H=Ys(e),Q=V0(),Y=Rn(u),W=Dl(l),pe=I0(l),Z=pe!=null?new AbortController:void 0,P=om(a,W!=null?AbortSignal.timeout(W):void 0,Z?.signal),{maxRetries:B,retry:F}=J0({maxRetries:i,abortSignal:P}),E=zl(O),N=nn(c??{},`ai/${x0}`),L=U0({model:H,telemetry:f,headers:N,settings:{...E,maxRetries:B}}),G={provider:H.provider,modelId:H.modelId},ee=await L0({system:n,prompt:o,messages:s}),se=Q(f?.integrations);await dr({event:{model:G,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:E.maxOutputTokens,temperature:E.temperature,topP:E.topP,topK:E.topK,presencePenalty:E.presencePenalty,frequencyPenalty:E.frequencyPenalty,stopSequences:E.stopSequences,seed:E.seed,maxRetries:B,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:a,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[I,se.onStart]});const ke=D0(f);try{return await Bo({name:"ai.generateText",attributes:Er({telemetry:f,attributes:{...Zo({operationId:"ai.generateText",telemetry:f}),...L,"ai.model.provider":H.provider,"ai.model.id":H.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:ke,fn:async z=>{var V,K,X,le,Te,Fe,tt,ut,Ye,$,re,Ae,yt;const Dt=ee.messages,Be=[],{approvedToolApprovals:Br,deniedToolApprovals:dt}=G0({messages:Dt}),sr=Br.filter(nt=>!nt.toolCall.providerExecuted);if(dt.length>0||sr.length>0){const nt=await am({toolCalls:sr.map(Ce=>Ce.toolCall),tools:t,tracer:ke,telemetry:f,messages:Dt,abortSignal:P,experimental_context:b,stepNumber:0,model:G,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[M,se.onToolCallFinish]}),St=[];for(const Ce of nt){const Ot=await Fo({toolCallId:Ce.toolCallId,input:Ce.input,tool:t?.[Ce.toolName],output:Ce.type==="tool-result"?Ce.output:Ce.error,errorMode:Ce.type==="tool-error"?"text":"none"});St.push({type:"tool-result",toolCallId:Ce.toolCallId,toolName:Ce.toolName,output:Ot})}for(const Ce of dt)St.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}}}}});Be.push({role:"tool",content:St})}const hn=[...Br,...dt].filter(nt=>nt.toolCall.providerExecuted);hn.length>0&&Be.push({role:"tool",content:hn.map(nt=>({type:"tool-approval-response",approvalId:nt.approvalResponse.approvalId,approved:nt.approvalResponse.approved,reason:nt.approvalResponse.reason,providerExecuted:!0}))});const pt=zl(O);let Ee,rt=[],Se=[];const Je=[],wr=new Map;do{const nt=pe!=null?setTimeout(()=>Z.abort(),pe):void 0;try{const St=[...Dt,...Be],Ce=await _?.({model:H,steps:Je,stepNumber:Je.length,messages:St,experimental_context:b}),Ot=Ys((V=Ce?.model)!=null?V:H),ft={provider:Ot.provider,modelId:Ot.modelId},It=await R0({prompt:{system:(K=Ce?.system)!=null?K:ee.system,messages:(X=Ce?.messages)!=null?X:St},supportedUrls:await Ot.supportedUrls,download:T});b=(le=Ce?.experimental_context)!=null?le:b;const lt=(Te=Ce?.activeTools)!=null?Te:y,{toolChoice:Hr,tools:wo}=await M0({tools:t,toolChoice:(Fe=Ce?.toolChoice)!=null?Fe:r,activeTools:lt}),Mi=(tt=Ce?.messages)!=null?tt:St,Oi=(ut=Ce?.system)!=null?ut:ee.system,_s=Xs(g,Ce?.providerOptions);await dr({event:{stepNumber:Je.length,model:ft,system:Oi,messages:Mi,tools:t,toolChoice:Hr,activeTools:lt,steps:[...Je],providerOptions:_s,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:a,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[x,se.onStepStart]}),Ee=await F(()=>{var Ne;return Bo({name:"ai.generateText.doGenerate",attributes:Er({telemetry:f,attributes:{...Zo({operationId:"ai.generateText.doGenerate",telemetry:f}),...L,"ai.model.provider":Ot.provider,"ai.model.id":Ot.modelId,"ai.prompt.messages":{input:()=>F0(It)},"ai.prompt.tools":{input:()=>wo?.map(At=>JSON.stringify(At))},"ai.prompt.toolChoice":{input:()=>Hr!=null?JSON.stringify(Hr):void 0},"gen_ai.system":Ot.provider,"gen_ai.request.model":Ot.modelId,"gen_ai.request.frequency_penalty":O.frequencyPenalty,"gen_ai.request.max_tokens":O.maxOutputTokens,"gen_ai.request.presence_penalty":O.presencePenalty,"gen_ai.request.stop_sequences":O.stopSequences,"gen_ai.request.temperature":(Ne=O.temperature)!=null?Ne:void 0,"gen_ai.request.top_k":O.topK,"gen_ai.request.top_p":O.topP}}),tracer:ke,fn:async At=>{var gn,Jr,qi,Li,ks,ji,Cs,bo;const ct=await Ot.doGenerate({...pt,tools:wo,toolChoice:Hr,responseFormat:await p?.responseFormat,prompt:It,providerOptions:_s,abortSignal:P,headers:N}),Gr={id:(Jr=(gn=ct.response)==null?void 0:gn.id)!=null?Jr:S(),timestamp:(Li=(qi=ct.response)==null?void 0:qi.timestamp)!=null?Li:new Date,modelId:(ji=(ks=ct.response)==null?void 0:ks.modelId)!=null?ji:Ot.modelId,headers:(Cs=ct.response)==null?void 0:Cs.headers,body:(bo=ct.response)==null?void 0:bo.body};return At.setAttributes(await Er({telemetry:f,attributes:{"ai.response.finishReason":ct.finishReason.unified,"ai.response.text":{output:()=>K0(ct.content)},"ai.response.reasoning":{output:()=>W0(ct.content)},"ai.response.toolCalls":{output:()=>{const Ui=im(ct.content);return Ui==null?void 0:JSON.stringify(Ui)}},"ai.response.id":Gr.id,"ai.response.model":Gr.modelId,"ai.response.timestamp":Gr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ct.providerMetadata),"ai.usage.promptTokens":ct.usage.inputTokens.total,"ai.usage.completionTokens":ct.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ct.finishReason.unified],"gen_ai.response.id":Gr.id,"gen_ai.response.model":Gr.modelId,"gen_ai.usage.input_tokens":ct.usage.inputTokens.total,"gen_ai.usage.output_tokens":ct.usage.outputTokens.total}})),{...ct,response:Gr}}})});const ar=await Promise.all(Ee.content.filter(Ne=>Ne.type==="tool-call").map(Ne=>X0({toolCall:Ne,tools:t,repairToolCall:h,system:n,messages:St}))),vs={};for(const Ne of ar){if(Ne.invalid)continue;const At=t?.[Ne.toolName];At!=null&&(At?.onInputAvailable!=null&&await At.onInputAvailable({input:Ne.input,toolCallId:Ne.toolCallId,messages:St,abortSignal:P,experimental_context:b}),await Q0({tool:At,toolCall:Ne,messages:St,experimental_context:b})&&(vs[Ne.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Ne}))}const Ai=ar.filter(Ne=>Ne.invalid&&Ne.dynamic);Se=[];for(const Ne of Ai)Se.push({type:"tool-error",toolCallId:Ne.toolCallId,toolName:Ne.toolName,input:Ne.input,error:fl(Ne.error),dynamic:!0});rt=ar.filter(Ne=>!Ne.providerExecuted),t!=null&&Se.push(...await am({toolCalls:rt.filter(Ne=>!Ne.invalid&&vs[Ne.toolCallId]==null),tools:t,tracer:ke,telemetry:f,messages:St,abortSignal:P,experimental_context:b,stepNumber:Je.length,model:ft,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[M,se.onToolCallFinish]}));for(const Ne of ar){if(!Ne.providerExecuted)continue;const At=t?.[Ne.toolName];At?.type==="provider"&&At.supportsDeferredResults&&(Ee.content.some(Jr=>Jr.type==="tool-result"&&Jr.toolCallId===Ne.toolCallId)||wr.set(Ne.toolCallId,{toolName:Ne.toolName}))}for(const Ne of Ee.content)Ne.type==="tool-result"&&wr.delete(Ne.toolCallId);const ws=yC({content:Ee.content,toolCalls:ar,toolOutputs:Se,toolApprovalRequests:Object.values(vs),tools:t});Be.push(...await Bl({content:ws,tools:t}));const mn=(Ye=k?.requestBody)==null||Ye?($=Ee.request)!=null?$:{}:{...Ee.request,body:void 0},_t={...Ee.response,messages:structuredClone(Be),body:(re=k?.responseBody)==null||re?(Ae=Ee.response)==null?void 0:Ae.body:void 0},Rr=Je.length,bs=new rm({stepNumber:Rr,model:ft,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b,content:ws,finishReason:Ee.finishReason.unified,rawFinishReason:Ee.finishReason.raw,usage:Z0(Ee.usage),warnings:Ee.warnings,providerMetadata:Ee.providerMetadata,request:mn,response:_t});Ul({warnings:(yt=Ee.warnings)!=null?yt:[],provider:ft.provider,model:ft.modelId}),Je.push(bs),await dr({event:bs,callbacks:[D,se.onStepFinish]})}finally{nt!=null&&clearTimeout(nt)}}while((rt.length>0&&Se.length===rt.length||wr.size>0)&&!await nm({stopConditions:Y,steps:Je}));z.setAttributes(await Er({telemetry:f,attributes:{"ai.response.finishReason":Ee.finishReason.unified,"ai.response.text":{output:()=>K0(Ee.content)},"ai.response.reasoning":{output:()=>W0(Ee.content)},"ai.response.toolCalls":{output:()=>{const nt=im(Ee.content);return nt==null?void 0:JSON.stringify(nt)}},"ai.response.providerMetadata":JSON.stringify(Ee.providerMetadata),"ai.usage.promptTokens":Ee.usage.inputTokens.total,"ai.usage.completionTokens":Ee.usage.outputTokens.total}}));const te=Je[Je.length-1],Ge=Je.reduce((nt,St)=>B0(nt,St.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await dr({event:{stepNumber:te.stepNumber,model:te.model,functionId:te.functionId,metadata:te.metadata,experimental_context:te.experimental_context,finishReason:te.finishReason,rawFinishReason:te.rawFinishReason,usage:te.usage,content:te.content,text:te.text,reasoningText:te.reasoningText,reasoning:te.reasoning,files:te.files,sources:te.sources,toolCalls:te.toolCalls,staticToolCalls:te.staticToolCalls,dynamicToolCalls:te.dynamicToolCalls,toolResults:te.toolResults,staticToolResults:te.staticToolResults,dynamicToolResults:te.dynamicToolResults,request:te.request,response:te.response,warnings:te.warnings,providerMetadata:te.providerMetadata,steps:Je,totalUsage:Ge},callbacks:[A,se.onFinish]});let br;return te.finishReason==="stop"&&(br=await(p??ta()).parseCompleteOutput({text:te.text},{response:te.response,usage:te.usage,finishReason:te.finishReason})),new gC({steps:Je,totalUsage:Ge,output:br})}})}catch(z){throw j0(z)}}async function am({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>Vl({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var gC=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 a0;return this._output}};function im(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 yC({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const i of e)switch(i.type){case"text":case"reasoning":case"source":s.push(i);break;case"file":{s.push({type:"file",file:new Y0(i),...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(a=>a.toolCallId===i.toolCallId));break}case"tool-result":{const a=t.find(l=>l.toolCallId===i.toolCallId);if(a==null){const l=o?.[i.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${i.toolCallId} not found.`);i.isError?s.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,error:i.result,providerExecuted:!0,dynamic:i.dynamic}):s.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,output:i.result,providerExecuted:!0,dynamic:i.dynamic});break}i.isError?s.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:a.input,error:i.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:a.input,output:i.result,providerExecuted:!0,dynamic:a.dynamic});break}case"tool-approval-request":{const a=t.find(l=>l.toolCallId===i.toolCallId);if(a==null)throw new Ll({toolCallId:i.toolCallId,approvalId:i.approvalId});s.push({type:"tool-approval-request",approvalId:i.approvalId,toolCall:a});break}}return[...s,...r,...n]}function ra(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 _C({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:ra(r,{"content-type":"text/plain; charset=utf-8"})})}function lm({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 i=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await i.read();if(l)break;e.write(c)||await new Promise(m=>{e.once("drain",m)})}}catch(l){throw l}finally{e.end()}})()}function vC({response:e,status:t,statusText:r,headers:n,textStream:o}){lm({response:e,status:t,statusText:r,headers:Object.fromEntries(ra(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var cm=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
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 U0({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])=>{if(i==="timeout"){const l=zl(a);l!=null&&(s[`ai.settings.${i}`]=l)}else s[`ai.settings.${i}`]=a;return 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 aC={startSpan(){return Qs},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Qs);if(typeof r=="function")return r(Qs);if(typeof n=="function")return n(Qs)}},Qs={spanContext(){return iC},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}},iC={traceId:"",spanId:"",traceFlags:0};function D0({isEnabled:e=!1,tracer:t}={}){return e?t||dk.getTracer("ai"):aC}async function Bo({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const i=qh.active();try{const a=await qh.with(i,()=>n(s));return o&&s.end(),a}catch(a){try{z0(s,a)}finally{s.end()}throw a}})}function z0(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Ks.ERROR,message:t.message})):e.setStatus({code:Ks.ERROR})}async function Er({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 F0(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?Zk(r.data):r.data}:r)})))}function lC(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function V0(){const e=lC();return t=>{const r=Rn(t),n=[...e,...r];function o(s){const i=n.map(s).filter(Boolean);return async a=>{for(const l of i)try{await l(a)}catch{}}}return{onStart:o(s=>s.onStart),onStepStart:o(s=>s.onStepStart),onToolCallStart:o(s=>s.onToolCallStart),onToolCallFinish:o(s=>s.onToolCallFinish),onStepFinish:o(s=>s.onStepFinish),onFinish:o(s=>s.onFinish)}}}function Z0(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:pr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function Vl(){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 B0(e,t){var r,n,o,s,i,a,l,c,u,m;return{inputTokens:pr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:pr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:pr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:pr((i=e.inputTokenDetails)==null?void 0:i.cacheWriteTokens,(a=t.inputTokenDetails)==null?void 0:a.cacheWriteTokens)},outputTokens:pr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:pr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:pr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(m=t.outputTokenDetails)==null?void 0:m.reasoningTokens)},totalTokens:pr(e.totalTokens,t.totalTokens),reasoningTokens:pr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:pr(e.cachedInputTokens,t.cachedInputTokens)}}function pr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Xs(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]=Xs(s,o):r[n]=o}return r}function cC({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 uC=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>H0(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function H0(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(i){if(Cn(i)||t===0)throw i;const a=hl(i),l=[...s,i],c=l.length;if(c>t)throw new k0({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:l});if(i instanceof Error&&ot.isInstance(i)&&i.isRetryable===!0&&c<=t)return await B3(cC({error:i,exponentialBackoffDelay:r}),{abortSignal:o}),H0(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?i:new k0({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:l})}}function J0({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new xr({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new xr({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:uC({maxRetries:r,abortSignal:t})}}function G0({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=[],i=[],a=t.content.filter(l=>l.type==="tool-approval-response");for(const l of a){const c=n[l.approvalId];if(c==null)throw new gk({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new jl({toolCallId:c.toolCallId,approvalId:c.approvalId});const m={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(m):i.push(m)}return{approvedToolApprovals:s,deniedToolApprovals:i}}function ea(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function Zl({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,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:a,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:i};return Bo({name:"ai.toolCall",attributes:Er({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 _;await dr({event:y,callbacks:u});const h=ea();try{const b=o4({execute:v.execute.bind(v),input:g,options:{toolCallId:f,messages:o,abortSignal:s,experimental_context:i}});for await(const k of b)k.type==="preliminary"?c?.({...e,type:"tool-result",output:k.output,preliminary:!0}):_=k.output}catch(b){const k=ea()-h;return await dr({event:{...y,success:!1,error:b,durationMs:k},callbacks:m}),z0(w,b),{type:"tool-error",toolCallId:f,toolName:p,input:g,error:b,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const T=ea()-h;await dr({event:{...y,success:!0,output:_,durationMs:T},callbacks:m});try{w.setAttributes(await Er({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 W0(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
|
|
64
|
+
`)}function K0(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var Y0=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=Xn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Qn(this.base64Data)),this.uint8ArrayData}},dC=class extends Y0{constructor(e){super(e),this.type="file"}};async function Q0({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 pC={};fk(pC,{array:()=>mC,choice:()=>gC,json:()=>yC,object:()=>hC,text:()=>ta});function fC(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const m=e.substring(n,l+1);!"false".startsWith(m)&&!"true".startsWith(m)&&!"null".startsWith(m)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let a=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?a+="true".slice(u.length):"false".startsWith(u)?a+="false".slice(u.length):"null".startsWith(u)&&(a+="null".slice(u.length))}}return a}async function Ho(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await er({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await er({text:fC(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var ta=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),hC=({schema:e,name:t,description:r})=>{const n=Sn(e);return{name:"object",responseFormat:Zt(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const i=await er({text:o});if(!i.success)throw new sn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=await Xt({value:i.value,schema:n});if(!a.success)throw new sn({message:"No object generated: response did not match schema.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return a.value},async parsePartialOutput({text:o}){const s=await Ho(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},mC=({element:e,name:t,description:r})=>{const n=Sn(e);return{name:"array",responseFormat:Zt(n.jsonSchema).then(o=>{const{$schema:s,...i}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:i}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const i=await er({text:o});if(!i.success)throw new sn({message:"No object generated: could not parse the response.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=i.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))throw new sn({message:"No object generated: response did not match schema.",cause:new vn({value:a,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 a.elements){const c=await Xt({value:l,schema:n});if(!c.success)throw new sn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return a.elements},async parsePartialOutput({text:o}){const s=await Ho(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const i=s.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))return;const a=s.state==="repaired-parse"&&i.elements.length>0?i.elements.slice(0,-1):i.elements,l=[];for(const c of a){const u=await Xt({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},i){if(s!=null)for(;o<s.length;o++)i.enqueue(s[o])}})}}},gC=({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 er({text:n});if(!s.success)throw new sn({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const i=s.value;if(i==null||typeof i!="object"||!("result"in i)||typeof i.result!="string"||!e.includes(i.result))throw new sn({message:"No object generated: response did not match schema.",cause:new vn({value:i,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.result},async parsePartialOutput({text:n}){const o=await Ho(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 i=e.filter(a=>a.startsWith(s.result));return o.state==="successful-parse"?i.includes(s.result)?{partial:s.result}:void 0:i.length===1?{partial:i[0]}:void 0}}},createElementStreamTransform(){}}),yC=({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 er({text:r});if(!o.success)throw new sn({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 Ho(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 X0({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await em(e);throw new Ul({toolName:e.toolName})}try{return await tm({toolCall:e,tools:t})}catch(i){if(r==null||!(Ul.isInstance(i)||Ll.isInstance(i)))throw i;let a=null;try{a=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await Sn(c).jsonSchema},system:n,messages:o,error:i})}catch(l){throw new Tk({cause:l,originalError:i})}if(a==null)throw i;return await tm({toolCall:a,tools:t})}}catch(i){const a=await er({text:e.input}),l=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:i,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function em(e){const t=e.input.trim()===""?{success:!0,value:{}}:await er({text:e.input});if(t.success===!1)throw new Ll({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 tm({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await em(e);throw new Ul({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Sn(n.inputSchema),s=e.input.trim()===""?await Xt({value:{},schema:o}):await er({text:e.input,schema:o});if(s.success===!1)throw new Ll({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 rm=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:i,rawFinishReason:a,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=i,this.rawFinishReason=a,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 Bl(e){return({steps:t})=>t.length===e}async function nm({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Hl({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 i=await Fo({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:i,providerOptions:s.providerMetadata});break}case"tool-error":{const i=await Fo({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:i,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 i=await Fo({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:i,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function om(...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 _C=Oo({prefix:"aitxt",size:24});async function sm({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=Bl(1),experimental_output:m,output:p=m,experimental_telemetry:f,providerOptions:g,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:w,prepareStep:_=w,experimental_repairToolCall:h,experimental_download:T,experimental_context:b,experimental_include:k,_internal:{generateId:S=_C}={},experimental_onStart:I,experimental_onStepStart:x,experimental_onToolCallStart:j,experimental_onToolCallFinish:M,onStepFinish:D,onFinish:A,...O}){const H=Ys(e),Q=V0(),Y=Rn(u),W=zl(l),pe=I0(l),Z=pe!=null?new AbortController:void 0,P=om(a,W!=null?AbortSignal.timeout(W):void 0,Z?.signal),{maxRetries:B,retry:F}=J0({maxRetries:i,abortSignal:P}),E=Fl(O),N=nn(c??{},`ai/${x0}`),L=U0({model:H,telemetry:f,headers:N,settings:{...E,maxRetries:B}}),G={provider:H.provider,modelId:H.modelId},ee=await L0({system:n,prompt:o,messages:s}),se=Q(f?.integrations);await dr({event:{model:G,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:E.maxOutputTokens,temperature:E.temperature,topP:E.topP,topK:E.topK,presencePenalty:E.presencePenalty,frequencyPenalty:E.frequencyPenalty,stopSequences:E.stopSequences,seed:E.seed,maxRetries:B,timeout:l,headers:c,providerOptions:g,stopWhen:u,output:p,abortSignal:a,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[I,se.onStart]});const ke=D0(f);try{return await Bo({name:"ai.generateText",attributes:Er({telemetry:f,attributes:{...Zo({operationId:"ai.generateText",telemetry:f}),...L,"ai.model.provider":H.provider,"ai.model.id":H.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:ke,fn:async z=>{var V,K,X,le,Te,Fe,tt,ut,Ye,$,re,Ae,yt;const Dt=ee.messages,Be=[],{approvedToolApprovals:Br,deniedToolApprovals:dt}=G0({messages:Dt}),sr=Br.filter(nt=>!nt.toolCall.providerExecuted);if(dt.length>0||sr.length>0){const nt=await am({toolCalls:sr.map(Ce=>Ce.toolCall),tools:t,tracer:ke,telemetry:f,messages:Dt,abortSignal:P,experimental_context:b,stepNumber:0,model:G,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[M,se.onToolCallFinish]}),St=[];for(const Ce of nt){const Ot=await Fo({toolCallId:Ce.toolCallId,input:Ce.input,tool:t?.[Ce.toolName],output:Ce.type==="tool-result"?Ce.output:Ce.error,errorMode:Ce.type==="tool-error"?"text":"none"});St.push({type:"tool-result",toolCallId:Ce.toolCallId,toolName:Ce.toolName,output:Ot})}for(const Ce of dt)St.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}}}}});Be.push({role:"tool",content:St})}const hn=[...Br,...dt].filter(nt=>nt.toolCall.providerExecuted);hn.length>0&&Be.push({role:"tool",content:hn.map(nt=>({type:"tool-approval-response",approvalId:nt.approvalResponse.approvalId,approved:nt.approvalResponse.approved,reason:nt.approvalResponse.reason,providerExecuted:!0}))});const pt=Fl(O);let Ee,rt=[],Se=[];const Je=[],wr=new Map;do{const nt=pe!=null?setTimeout(()=>Z.abort(),pe):void 0;try{const St=[...Dt,...Be],Ce=await _?.({model:H,steps:Je,stepNumber:Je.length,messages:St,experimental_context:b}),Ot=Ys((V=Ce?.model)!=null?V:H),ft={provider:Ot.provider,modelId:Ot.modelId},It=await R0({prompt:{system:(K=Ce?.system)!=null?K:ee.system,messages:(X=Ce?.messages)!=null?X:St},supportedUrls:await Ot.supportedUrls,download:T});b=(le=Ce?.experimental_context)!=null?le:b;const lt=(Te=Ce?.activeTools)!=null?Te:y,{toolChoice:Hr,tools:wo}=await M0({tools:t,toolChoice:(Fe=Ce?.toolChoice)!=null?Fe:r,activeTools:lt}),Oi=(tt=Ce?.messages)!=null?tt:St,Ai=(ut=Ce?.system)!=null?ut:ee.system,_s=Xs(g,Ce?.providerOptions);await dr({event:{stepNumber:Je.length,model:ft,system:Ai,messages:Oi,tools:t,toolChoice:Hr,activeTools:lt,steps:[...Je],providerOptions:_s,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:a,include:k,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b},callbacks:[x,se.onStepStart]}),Ee=await F(()=>{var Ne;return Bo({name:"ai.generateText.doGenerate",attributes:Er({telemetry:f,attributes:{...Zo({operationId:"ai.generateText.doGenerate",telemetry:f}),...L,"ai.model.provider":Ot.provider,"ai.model.id":Ot.modelId,"ai.prompt.messages":{input:()=>F0(It)},"ai.prompt.tools":{input:()=>wo?.map(At=>JSON.stringify(At))},"ai.prompt.toolChoice":{input:()=>Hr!=null?JSON.stringify(Hr):void 0},"gen_ai.system":Ot.provider,"gen_ai.request.model":Ot.modelId,"gen_ai.request.frequency_penalty":O.frequencyPenalty,"gen_ai.request.max_tokens":O.maxOutputTokens,"gen_ai.request.presence_penalty":O.presencePenalty,"gen_ai.request.stop_sequences":O.stopSequences,"gen_ai.request.temperature":(Ne=O.temperature)!=null?Ne:void 0,"gen_ai.request.top_k":O.topK,"gen_ai.request.top_p":O.topP}}),tracer:ke,fn:async At=>{var gn,Jr,Li,ji,ks,Ui,Cs,bo;const ct=await Ot.doGenerate({...pt,tools:wo,toolChoice:Hr,responseFormat:await p?.responseFormat,prompt:It,providerOptions:_s,abortSignal:P,headers:N}),Gr={id:(Jr=(gn=ct.response)==null?void 0:gn.id)!=null?Jr:S(),timestamp:(ji=(Li=ct.response)==null?void 0:Li.timestamp)!=null?ji:new Date,modelId:(Ui=(ks=ct.response)==null?void 0:ks.modelId)!=null?Ui:Ot.modelId,headers:(Cs=ct.response)==null?void 0:Cs.headers,body:(bo=ct.response)==null?void 0:bo.body};return At.setAttributes(await Er({telemetry:f,attributes:{"ai.response.finishReason":ct.finishReason.unified,"ai.response.text":{output:()=>K0(ct.content)},"ai.response.reasoning":{output:()=>W0(ct.content)},"ai.response.toolCalls":{output:()=>{const Di=im(ct.content);return Di==null?void 0:JSON.stringify(Di)}},"ai.response.id":Gr.id,"ai.response.model":Gr.modelId,"ai.response.timestamp":Gr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ct.providerMetadata),"ai.usage.promptTokens":ct.usage.inputTokens.total,"ai.usage.completionTokens":ct.usage.outputTokens.total,"gen_ai.response.finish_reasons":[ct.finishReason.unified],"gen_ai.response.id":Gr.id,"gen_ai.response.model":Gr.modelId,"gen_ai.usage.input_tokens":ct.usage.inputTokens.total,"gen_ai.usage.output_tokens":ct.usage.outputTokens.total}})),{...ct,response:Gr}}})});const ar=await Promise.all(Ee.content.filter(Ne=>Ne.type==="tool-call").map(Ne=>X0({toolCall:Ne,tools:t,repairToolCall:h,system:n,messages:St}))),vs={};for(const Ne of ar){if(Ne.invalid)continue;const At=t?.[Ne.toolName];At!=null&&(At?.onInputAvailable!=null&&await At.onInputAvailable({input:Ne.input,toolCallId:Ne.toolCallId,messages:St,abortSignal:P,experimental_context:b}),await Q0({tool:At,toolCall:Ne,messages:St,experimental_context:b})&&(vs[Ne.toolCallId]={type:"tool-approval-request",approvalId:S(),toolCall:Ne}))}const qi=ar.filter(Ne=>Ne.invalid&&Ne.dynamic);Se=[];for(const Ne of qi)Se.push({type:"tool-error",toolCallId:Ne.toolCallId,toolName:Ne.toolName,input:Ne.input,error:hl(Ne.error),dynamic:!0});rt=ar.filter(Ne=>!Ne.providerExecuted),t!=null&&Se.push(...await am({toolCalls:rt.filter(Ne=>!Ne.invalid&&vs[Ne.toolCallId]==null),tools:t,tracer:ke,telemetry:f,messages:St,abortSignal:P,experimental_context:b,stepNumber:Je.length,model:ft,onToolCallStart:[j,se.onToolCallStart],onToolCallFinish:[M,se.onToolCallFinish]}));for(const Ne of ar){if(!Ne.providerExecuted)continue;const At=t?.[Ne.toolName];At?.type==="provider"&&At.supportsDeferredResults&&(Ee.content.some(Jr=>Jr.type==="tool-result"&&Jr.toolCallId===Ne.toolCallId)||wr.set(Ne.toolCallId,{toolName:Ne.toolName}))}for(const Ne of Ee.content)Ne.type==="tool-result"&&wr.delete(Ne.toolCallId);const ws=wC({content:Ee.content,toolCalls:ar,toolOutputs:Se,toolApprovalRequests:Object.values(vs),tools:t});Be.push(...await Hl({content:ws,tools:t}));const mn=(Ye=k?.requestBody)==null||Ye?($=Ee.request)!=null?$:{}:{...Ee.request,body:void 0},_t={...Ee.response,messages:structuredClone(Be),body:(re=k?.responseBody)==null||re?(Ae=Ee.response)==null?void 0:Ae.body:void 0},Rr=Je.length,bs=new rm({stepNumber:Rr,model:ft,functionId:f?.functionId,metadata:f?.metadata,experimental_context:b,content:ws,finishReason:Ee.finishReason.unified,rawFinishReason:Ee.finishReason.raw,usage:Z0(Ee.usage),warnings:Ee.warnings,providerMetadata:Ee.providerMetadata,request:mn,response:_t});Dl({warnings:(yt=Ee.warnings)!=null?yt:[],provider:ft.provider,model:ft.modelId}),Je.push(bs),await dr({event:bs,callbacks:[D,se.onStepFinish]})}finally{nt!=null&&clearTimeout(nt)}}while((rt.length>0&&Se.length===rt.length||wr.size>0)&&!await nm({stopConditions:Y,steps:Je}));z.setAttributes(await Er({telemetry:f,attributes:{"ai.response.finishReason":Ee.finishReason.unified,"ai.response.text":{output:()=>K0(Ee.content)},"ai.response.reasoning":{output:()=>W0(Ee.content)},"ai.response.toolCalls":{output:()=>{const nt=im(Ee.content);return nt==null?void 0:JSON.stringify(nt)}},"ai.response.providerMetadata":JSON.stringify(Ee.providerMetadata),"ai.usage.promptTokens":Ee.usage.inputTokens.total,"ai.usage.completionTokens":Ee.usage.outputTokens.total}}));const te=Je[Je.length-1],Ge=Je.reduce((nt,St)=>B0(nt,St.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await dr({event:{stepNumber:te.stepNumber,model:te.model,functionId:te.functionId,metadata:te.metadata,experimental_context:te.experimental_context,finishReason:te.finishReason,rawFinishReason:te.rawFinishReason,usage:te.usage,content:te.content,text:te.text,reasoningText:te.reasoningText,reasoning:te.reasoning,files:te.files,sources:te.sources,toolCalls:te.toolCalls,staticToolCalls:te.staticToolCalls,dynamicToolCalls:te.dynamicToolCalls,toolResults:te.toolResults,staticToolResults:te.staticToolResults,dynamicToolResults:te.dynamicToolResults,request:te.request,response:te.response,warnings:te.warnings,providerMetadata:te.providerMetadata,steps:Je,totalUsage:Ge},callbacks:[A,se.onFinish]});let br;return te.finishReason==="stop"&&(br=await(p??ta()).parseCompleteOutput({text:te.text},{response:te.response,usage:te.usage,finishReason:te.finishReason})),new vC({steps:Je,totalUsage:Ge,output:br})}})}catch(z){throw j0(z)}}async function am({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>Zl({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:i,stepNumber:a,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var vC=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 a0;return this._output}};function im(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 wC({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const i of e)switch(i.type){case"text":case"reasoning":case"source":s.push(i);break;case"file":{s.push({type:"file",file:new Y0(i),...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(a=>a.toolCallId===i.toolCallId));break}case"tool-result":{const a=t.find(l=>l.toolCallId===i.toolCallId);if(a==null){const l=o?.[i.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${i.toolCallId} not found.`);i.isError?s.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,error:i.result,providerExecuted:!0,dynamic:i.dynamic}):s.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:void 0,output:i.result,providerExecuted:!0,dynamic:i.dynamic});break}i.isError?s.push({type:"tool-error",toolCallId:i.toolCallId,toolName:i.toolName,input:a.input,error:i.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,input:a.input,output:i.result,providerExecuted:!0,dynamic:a.dynamic});break}case"tool-approval-request":{const a=t.find(l=>l.toolCallId===i.toolCallId);if(a==null)throw new jl({toolCallId:i.toolCallId,approvalId:i.approvalId});s.push({type:"tool-approval-request",approvalId:i.approvalId,toolCall:a});break}}return[...s,...r,...n]}function ra(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 bC({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:ra(r,{"content-type":"text/plain; charset=utf-8"})})}function lm({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 i=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await i.read();if(l)break;e.write(c)||await new Promise(m=>{e.once("drain",m)})}}catch(l){throw l}finally{e.end()}})()}function kC({response:e,status:t,statusText:r,headers:n,textStream:o}){lm({response:e,status:t,statusText:r,headers:Object.fromEntries(ra(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var cm=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
65
65
|
|
|
66
66
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
67
67
|
|
|
68
|
-
`)}})}},um={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function wC({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new cm);if(o){const[i,a]=s.tee();s=i,o({stream:a})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:ra(r,um)})}function bC({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 kC(e){return e.type.startsWith("data-")}function Hl(e){return e.type.startsWith("tool-")}function CC(e){return e.type==="dynamic-tool"}function dm(e){return Hl(e)||CC(e)}function pm(e){return e.type.split("-").slice(1).join("-")}function TC({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function SC({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await n(async({state:c,write:u})=>{var m,p,f,g;function v(h){const b=c.message.parts.filter(dm).find(k=>k.toolCallId===h);if(b==null)throw new no({chunkType:"tool-invocation",chunkId:h,message:`No tool invocation found for tool call ID "${h}".`});return b}function y(h){var T;const b=c.message.parts.find(I=>Hl(I)&&I.toolCallId===h.toolCallId),k=h,S=b;b!=null?(b.state=h.state,S.input=k.input,S.output=k.output,S.errorText=k.errorText,S.rawInput=k.rawInput,S.preliminary=k.preliminary,h.title!==void 0&&(S.title=h.title),S.providerExecuted=(T=k.providerExecuted)!=null?T:b.providerExecuted,k.providerMetadata!=null&&(b.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:`tool-${h.toolName}`,toolCallId:h.toolCallId,state:h.state,title:h.title,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function w(h){var T,b;const k=c.message.parts.find(x=>x.type==="dynamic-tool"&&x.toolCallId===h.toolCallId),S=h,I=k;k!=null?(k.state=h.state,I.toolName=h.toolName,I.input=S.input,I.output=S.output,I.errorText=S.errorText,I.rawInput=(T=S.rawInput)!=null?T:I.rawInput,I.preliminary=S.preliminary,h.title!==void 0&&(I.title=h.title),I.providerExecuted=(b=S.providerExecuted)!=null?b:k.providerExecuted,S.providerMetadata!=null&&(k.callProviderMetadata=S.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:h.toolName,toolCallId:h.toolCallId,state:h.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,providerExecuted:S.providerExecuted,title:h.title,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function _(h){if(h!=null){const T=c.message.metadata!=null?Xs(c.message.metadata,h):h;t!=null&&await kt({value:T,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=T}}switch(a.type){case"text-start":{const h={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeTextParts[a.id]=h,c.message.parts.push(h),u();break}case"text-delta":{const h=c.activeTextParts[a.id];if(h==null)throw new no({chunkType:"text-delta",chunkId:a.id,message:`Received text-delta for missing text part with ID "${a.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});h.text+=a.delta,h.providerMetadata=(m=a.providerMetadata)!=null?m:h.providerMetadata,u();break}case"text-end":{const h=c.activeTextParts[a.id];if(h==null)throw new no({chunkType:"text-end",chunkId:a.id,message:`Received text-end for missing text part with ID "${a.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});h.state="done",h.providerMetadata=(p=a.providerMetadata)!=null?p:h.providerMetadata,delete c.activeTextParts[a.id],u();break}case"reasoning-start":{const h={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeReasoningParts[a.id]=h,c.message.parts.push(h),u();break}case"reasoning-delta":{const h=c.activeReasoningParts[a.id];if(h==null)throw new no({chunkType:"reasoning-delta",chunkId:a.id,message:`Received reasoning-delta for missing reasoning part with ID "${a.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});h.text+=a.delta,h.providerMetadata=(f=a.providerMetadata)!=null?f:h.providerMetadata,u();break}case"reasoning-end":{const h=c.activeReasoningParts[a.id];if(h==null)throw new no({chunkType:"reasoning-end",chunkId:a.id,message:`Received reasoning-end for missing reasoning part with ID "${a.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});h.providerMetadata=(g=a.providerMetadata)!=null?g:h.providerMetadata,h.state="done",delete c.activeReasoningParts[a.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}}),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 h=c.message.parts.filter(Hl);c.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:h.length,dynamic:a.dynamic,title:a.title},a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted,title:a.title,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted,title:a.title,providerMetadata:a.providerMetadata}),u();break}case"tool-input-delta":{const h=c.partialToolCalls[a.toolCallId];if(h==null)throw new no({chunkType:"tool-input-delta",chunkId:a.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${a.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});h.text+=a.inputTextDelta;const{value:T}=await Ho(h.text);h.dynamic?w({toolCallId:a.toolCallId,toolName:h.toolName,state:"input-streaming",input:T,title:h.title}):y({toolCallId:a.toolCallId,toolName:h.toolName,state:"input-streaming",input:T,title:h.title}),u();break}case"tool-input-available":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:a.title}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:a.title}),u(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{const h=c.message.parts.filter(dm).find(b=>b.toolCallId===a.toolCallId);(h!=null?h.type==="dynamic-tool":!!a.dynamic)?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({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-approval-request":{const h=v(a.toolCallId);h.state="approval-requested",h.approval={id:a.approvalId},u();break}case"tool-output-denied":{const h=v(a.toolCallId);h.state="output-denied",u();break}case"tool-output-available":{const h=v(a.toolCallId);h.type==="dynamic-tool"?w({toolCallId:a.toolCallId,toolName:h.toolName,state:"output-available",input:h.input,output:a.output,preliminary:a.preliminary,providerExecuted:a.providerExecuted,title:h.title}):y({toolCallId:a.toolCallId,toolName:pm(h),state:"output-available",input:h.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary,title:h.title}),u();break}case"tool-output-error":{const h=v(a.toolCallId);h.type==="dynamic-tool"?w({toolCallId:a.toolCallId,toolName:h.toolName,state:"output-error",input:h.input,errorText:a.errorText,providerExecuted:a.providerExecuted,title:h.title}):y({toolCallId:a.toolCallId,toolName:pm(h),state:"output-error",input:h.input,rawInput:h.rawInput,errorText:a.errorText,providerExecuted:a.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":{a.messageId!=null&&(c.message.id=a.messageId),await _(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&u();break}case"finish":{a.finishReason!=null&&(c.finishReason=a.finishReason),await _(a.messageMetadata),a.messageMetadata!=null&&u();break}case"message-metadata":{await _(a.messageMetadata),a.messageMetadata!=null&&u();break}case"error":{o?.(new Error(a.errorText));break}default:if(kC(a)){if(r?.[a.type]!=null){const b=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===a.id&&S.type===a.type),k=b>=0?b:c.message.parts.length;await kt({value:a.data,schema:r[a.type],context:{field:`message.parts[${k}].data`,entityName:a.type,entityId:a.id}})}const h=a;if(h.transient){i?.(h);break}const T=h.id!=null?c.message.parts.find(b=>h.type===b.type&&h.id===b.id):void 0;T!=null?T.data=h.data:c.message.parts.push(h),i?.(h),u()}}l.enqueue(a)})}}))}function IC({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let a=!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"&&(a=!0),v.enqueue(g)}}));if(n==null&&r==null)return l;const c=TC({lastMessage:i?structuredClone(i):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===i?.id;await n({isAborted:a,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===i?.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 SC({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 xC({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let i=o.pipeThrough(new cm);if(s){const[a,l]=i.tee();i=a,s({stream:l})}lm({response:e,status:t,statusText:r,headers:Object.fromEntries(ra(n,um).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function Jo(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;if(!n){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 EC({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 fm(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function $C(){let e=[],t=null,r=!1,n=fm();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=fm(),await n.promise,s();try{const{value:i,done:a}=await e[0].read();a?(e.shift(),e.length===0&&r?t?.close():await s()):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 RC({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:i,repairToolCall:a,experimental_context:l,generateId:c,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f}){let g=null;const v=new ReadableStream({start(S){g=S}}),y=new Set,w=new Map,_=new Map;let h=!1,T;function b(){h&&y.size===0&&(T!=null&&g.enqueue(T),g.close())}const k=new TransformStream({async transform(S,I){const x=S.type;switch(x){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":{I.enqueue(S);break}case"file":{I.enqueue({type:"file",file:new lC({data:S.data,mediaType:S.mediaType}),...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{}});break}case"finish":{T={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:Z0(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const j=_.get(S.toolCallId);if(j==null){g.enqueue({type:"error",error:new Ll({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}I.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:j});break}case"tool-call":{try{const j=await X0({toolCall:S,tools:e,repairToolCall:a,system:o,messages:s});if(_.set(j.toolCallId,j),I.enqueue(j),j.invalid){g.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:fl(j.error),dynamic:!0,title:j.title});break}const M=e?.[j.toolName];if(M==null)break;if(M.onInputAvailable!=null&&await M.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:s,abortSignal:i,experimental_context:l}),await Q0({tool:M,toolCall:j,messages:s,experimental_context:l})){g.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:j});break}if(w.set(j.toolCallId,j.input),M.execute!=null&&j.providerExecuted!==!0){const D=c();y.add(D),Vl({toolCall:j,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:i,experimental_context:l,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f,onPreliminaryToolResult:A=>{g.enqueue(A)}}).then(A=>{g.enqueue(A)}).catch(A=>{g.enqueue({type:"error",error:A})}).finally(()=>{y.delete(D),b()})}}catch(j){g.enqueue({type:"error",error:j})}break}case"tool-result":{const j=S.toolName;S.isError?g.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic}):I.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic});break}default:{const j=x;throw new Error(`Unhandled chunk type: ${j}`)}}},flush(){h=!0,b()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){}})),v.pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){S.close()}}))])}})}var PC=Oo({prefix:"aitxt",size:24});function Jl({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=Zl(1),experimental_output:m,output:p=m,experimental_telemetry:f,prepareStep:g,providerOptions:v,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:_,experimental_transform:h,experimental_download:T,includeRawChunks:b=!1,onChunk:k,onError:S=({error:Z})=>{console.error(Z)},onFinish:I,onAbort:x,onStepFinish:j,experimental_onStart:M,experimental_onStepStart:D,experimental_onToolCallStart:A,experimental_onToolCallFinish:O,experimental_context:H,experimental_include:Q,_internal:{now:Y=ea,generateId:W=PC}={},...pe}){const Z=Dl(l),P=I0(l),B=Mk(l),F=P!=null?new AbortController:void 0,E=B!=null?new AbortController:void 0;return new MC({model:Ys(e),telemetry:f,headers:c,settings:pe,maxRetries:i,abortSignal:om(a,Z!=null?AbortSignal.timeout(Z):void 0,F?.signal,E?.signal),stepTimeoutMs:P,stepAbortController:F,chunkTimeoutMs:B,chunkAbortController:E,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Rn(h),activeTools:w,repairToolCall:_,stopConditions:Rn(u),output:p,providerOptions:v,prepareStep:g,includeRawChunks:b,timeout:l,stopWhen:u,originalAbortSignal:a,onChunk:k,onError:S,onFinish:I,onAbort:x,onStepFinish:j,onStart:M,onStepStart:D,onToolCallStart:A,onToolCallFinish:O,now:Y,generateId:W,experimental_context:H,download:T,include:Q})}function NC(e){let t,r="",n="",o,s="";function i({controller:a,partialOutput:l=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(a,l){var c;if(a.type==="finish-step"&&n.length>0&&i({controller:l}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){l.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){l.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){l.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&i({controller:l}),l.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text,o=(c=a.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const m=JSON.stringify(u.partial);m!==s&&(i({controller:l,partialOutput:u.partial}),s=m)}}})}var MC=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:i,stepAbortController:a,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:m,messages:p,tools:f,toolChoice:g,transforms:v,activeTools:y,repairToolCall:w,stopConditions:_,output:h,providerOptions:T,prepareStep:b,includeRawChunks:k,now:S,generateId:I,timeout:x,stopWhen:j,originalAbortSignal:M,onChunk:D,onError:A,onFinish:O,onAbort:H,onStepFinish:Q,onStart:Y,onStepStart:W,onToolCallStart:pe,onToolCallFinish:Z,experimental_context:P,download:B,include:F}){this._totalUsage=new Mo,this._finishReason=new Mo,this._rawFinishReason=new Mo,this._steps=new Mo,this.outputSpecification=h,this.includeRawChunks=k,this.tools=f;const N=V0()(t?.integrations);let L,G=[];const ee=[];let se,ke,z,V={},K=[];const X=[],le=new Map;let Te,Fe={},tt={};const ut=new TransformStream({async transform(pt,Ee){var rt,Se,Je,wr;Ee.enqueue(pt);const{part:te}=pt;if((te.type==="text-delta"||te.type==="reasoning-delta"||te.type==="source"||te.type==="tool-call"||te.type==="tool-result"||te.type==="tool-input-start"||te.type==="tool-input-delta"||te.type==="raw")&&await D?.({chunk:te}),te.type==="error"&&await A({error:j0(te.error)}),te.type==="text-start"&&(Fe[te.id]={type:"text",text:"",providerMetadata:te.providerMetadata},G.push(Fe[te.id])),te.type==="text-delta"){const Ge=Fe[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`text part ${te.id} not found`},partialOutput:void 0});return}Ge.text+=te.text,Ge.providerMetadata=(rt=te.providerMetadata)!=null?rt:Ge.providerMetadata}if(te.type==="text-end"){const Ge=Fe[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`text part ${te.id} not found`},partialOutput:void 0});return}Ge.providerMetadata=(Se=te.providerMetadata)!=null?Se:Ge.providerMetadata,delete Fe[te.id]}if(te.type==="reasoning-start"&&(tt[te.id]={type:"reasoning",text:"",providerMetadata:te.providerMetadata},G.push(tt[te.id])),te.type==="reasoning-delta"){const Ge=tt[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`reasoning part ${te.id} not found`},partialOutput:void 0});return}Ge.text+=te.text,Ge.providerMetadata=(Je=te.providerMetadata)!=null?Je:Ge.providerMetadata}if(te.type==="reasoning-end"){const Ge=tt[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`reasoning part ${te.id} not found`},partialOutput:void 0});return}Ge.providerMetadata=(wr=te.providerMetadata)!=null?wr:Ge.providerMetadata,delete tt[te.id]}if(te.type==="file"&&G.push({type:"file",file:te.file,...te.providerMetadata!=null?{providerMetadata:te.providerMetadata}:{}}),te.type==="source"&&G.push(te),te.type==="tool-call"&&G.push(te),te.type==="tool-result"&&!te.preliminary&&G.push(te),te.type==="tool-approval-request"&&G.push(te),te.type==="tool-error"&&G.push(te),te.type==="start-step"&&(G=[],tt={},Fe={},V=te.request,K=te.warnings),te.type==="finish-step"){const Ge=await Bl({content:G,tools:f}),br=new rm({stepNumber:X.length,model:sr,...hn,experimental_context:P,content:G,finishReason:te.finishReason,rawFinishReason:te.rawFinishReason,usage:te.usage,warnings:K,request:V,response:{...te.response,messages:[...ee,...Ge]},providerMetadata:te.providerMetadata});await dr({event:br,callbacks:[Q,N.onStepFinish]}),Ul({warnings:K,provider:sr.provider,model:sr.modelId}),X.push(br),ee.push(...Ge),L.resolve()}te.type==="finish"&&(z=te.totalUsage,se=te.finishReason,ke=te.rawFinishReason)},async flush(pt){try{if(X.length===0){const Je=s?.aborted?s.reason:new a0({message:"No output generated. Check the stream for errors."});dt._finishReason.reject(Je),dt._rawFinishReason.reject(Je),dt._totalUsage.reject(Je),dt._steps.reject(Je);return}const Ee=se??"other",rt=z??Fl();dt._finishReason.resolve(Ee),dt._rawFinishReason.resolve(ke),dt._totalUsage.resolve(rt),dt._steps.resolve(X);const Se=X[X.length-1];await dr({event:{stepNumber:Se.stepNumber,model:Se.model,functionId:Se.functionId,metadata:Se.metadata,experimental_context:Se.experimental_context,finishReason:Se.finishReason,rawFinishReason:Se.rawFinishReason,totalUsage:rt,usage:Se.usage,content:Se.content,text:Se.text,reasoningText:Se.reasoningText,reasoning:Se.reasoning,files:Se.files,sources:Se.sources,toolCalls:Se.toolCalls,staticToolCalls:Se.staticToolCalls,dynamicToolCalls:Se.dynamicToolCalls,toolResults:Se.toolResults,staticToolResults:Se.staticToolResults,dynamicToolResults:Se.dynamicToolResults,request:Se.request,response:Se.response,warnings:Se.warnings,providerMetadata:Se.providerMetadata,steps:X},callbacks:[O,N.onFinish]}),Te.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":Ee,"ai.response.text":{output:()=>Se.text},"ai.response.reasoning":{output:()=>Se.reasoningText},"ai.response.toolCalls":{output:()=>{var Je;return(Je=Se.toolCalls)!=null&&Je.length?JSON.stringify(Se.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Se.providerMetadata),"ai.usage.inputTokens":rt.inputTokens,"ai.usage.outputTokens":rt.outputTokens,"ai.usage.totalTokens":rt.totalTokens,"ai.usage.reasoningTokens":rt.reasoningTokens,"ai.usage.cachedInputTokens":rt.cachedInputTokens}}))}catch(Ee){pt.error(Ee)}finally{Te.end()}}}),Ye=$C();this.addStream=Ye.addStream,this.closeStream=Ye.close;const $=Ye.stream.getReader();let re=new ReadableStream({async start(pt){pt.enqueue({type:"start"})},async pull(pt){function Ee(){H?.({steps:X}),pt.enqueue({type:"abort",...s?.reason!==void 0?{reason:yn(s.reason)}:{}}),pt.close()}try{const{done:rt,value:Se}=await $.read();if(rt){pt.close();return}if(s?.aborted){Ee();return}pt.enqueue(Se)}catch(rt){Cn(rt)&&s?.aborted?Ee():pt.error(rt)}},cancel(pt){return Ye.stream.cancel(pt)}});for(const pt of v)re=re.pipeThrough(pt({tools:f,stopStream(){Ye.terminate()}}));this.baseStream=re.pipeThrough(NC(h??ta())).pipeThrough(ut);const{maxRetries:Ae,retry:yt}=J0({maxRetries:o,abortSignal:s}),Dt=D0(t),Be=zl(n),Br=U0({model:e,telemetry:t,headers:r,settings:{...Be,maxRetries:Ae}}),dt=this,sr={provider:e.provider,modelId:e.modelId},hn={functionId:t?.functionId,metadata:t?.metadata};Bo({name:"ai.streamText",attributes:Er({telemetry:t,attributes:{...Zo({operationId:"ai.streamText",telemetry:t}),...Br,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:m,messages:p})}}}),tracer:Dt,endWhenDone:!1,fn:async pt=>{Te=pt;const Ee=await L0({system:u,prompt:m,messages:p});await dr({event:{model:sr,system:u,prompt:m,messages:p,tools:f,toolChoice:g,activeTools:y,maxOutputTokens:Be.maxOutputTokens,temperature:Be.temperature,topP:Be.topP,topK:Be.topK,presencePenalty:Be.presencePenalty,frequencyPenalty:Be.frequencyPenalty,stopSequences:Be.stopSequences,seed:Be.seed,maxRetries:Ae,timeout:x,headers:r,providerOptions:T,stopWhen:j,output:h,abortSignal:M,include:F,...hn,experimental_context:P},callbacks:[Y,N.onStart]});const rt=Ee.messages,Se=[],{approvedToolApprovals:Je,deniedToolApprovals:wr}=G0({messages:rt});if(wr.length>0||Je.length>0){const Ge=[...Je,...wr].filter(ft=>ft.toolCall.providerExecuted),br=Je.filter(ft=>!ft.toolCall.providerExecuted),nt=wr.filter(ft=>!ft.toolCall.providerExecuted),St=wr.filter(ft=>ft.toolCall.providerExecuted);let Ce;const Ot=new ReadableStream({start(ft){Ce=ft}});dt.addStream(Ot);try{for(const It of[...nt,...St])Ce?.enqueue({type:"tool-output-denied",toolCallId:It.toolCall.toolCallId,toolName:It.toolCall.toolName});const ft=[];if(await Promise.all(br.map(async It=>{const lt=await Vl({toolCall:It.toolCall,tools:f,tracer:Dt,telemetry:t,messages:rt,abortSignal:s,experimental_context:P,stepNumber:X.length,model:sr,onToolCallStart:[pe,N.onToolCallStart],onToolCallFinish:[Z,N.onToolCallFinish],onPreliminaryToolResult:Hr=>{Ce?.enqueue(Hr)}});lt!=null&&(Ce?.enqueue(lt),ft.push(lt))})),Ge.length>0&&Se.push({role:"tool",content:Ge.map(It=>({type:"tool-approval-response",approvalId:It.approvalResponse.approvalId,approved:It.approvalResponse.approved,reason:It.approvalResponse.reason,providerExecuted:!0}))}),ft.length>0||nt.length>0){const It=[];for(const lt of ft)It.push({type:"tool-result",toolCallId:lt.toolCallId,toolName:lt.toolName,output:await Fo({toolCallId:lt.toolCallId,input:lt.input,tool:f?.[lt.toolName],output:lt.type==="tool-result"?lt.output:lt.error,errorMode:lt.type==="tool-error"?"text":"none"})});for(const lt of nt)It.push({type:"tool-result",toolCallId:lt.toolCall.toolCallId,toolName:lt.toolCall.toolName,output:{type:"execution-denied",reason:lt.approvalResponse.reason}});Se.push({role:"tool",content:It})}}finally{Ce?.close()}}ee.push(...Se);async function te({currentStep:Ge,responseMessages:br,usage:nt}){var St,Ce,Ot,ft,It,lt,Hr,wo,Mi;const Oi=dt.includeRawChunks,_s=i!=null?setTimeout(()=>a.abort(),i):void 0;let ar;function vs(){l!=null&&(ar!=null&&clearTimeout(ar),ar=setTimeout(()=>c.abort(),l))}function Ai(){ar!=null&&(clearTimeout(ar),ar=void 0)}function ws(){_s!=null&&clearTimeout(_s)}try{L=new Mo;const mn=[...rt,...br],_t=await b?.({model:e,steps:X,stepNumber:X.length,messages:mn,experimental_context:P}),Rr=Ys((St=_t?.model)!=null?St:e),bs={provider:Rr.provider,modelId:Rr.modelId},Ne=await R0({prompt:{system:(Ce=_t?.system)!=null?Ce:Ee.system,messages:(Ot=_t?.messages)!=null?Ot:mn},supportedUrls:await Rr.supportedUrls,download:B}),At=(ft=_t?.activeTools)!=null?ft:y,{toolChoice:gn,tools:Jr}=await M0({tools:f,toolChoice:(It=_t?.toolChoice)!=null?It:g,activeTools:At});P=(lt=_t?.experimental_context)!=null?lt:P;const qi=(Hr=_t?.messages)!=null?Hr:mn,Li=(wo=_t?.system)!=null?wo:Ee.system,ks=Xs(T,_t?.providerOptions);await dr({event:{stepNumber:X.length,model:bs,system:Li,messages:qi,tools:f,toolChoice:gn,activeTools:At,steps:[...X],providerOptions:ks,timeout:x,headers:r,stopWhen:j,output:h,abortSignal:M,include:F,...hn,experimental_context:P},callbacks:[W,N.onStepStart]});const{result:{stream:ji,response:Cs,request:bo},doStreamSpan:ct,startTimestampMs:Gr}=await yt(()=>Bo({name:"ai.streamText.doStream",attributes:Er({telemetry:t,attributes:{...Zo({operationId:"ai.streamText.doStream",telemetry:t}),...Br,"ai.model.provider":Rr.provider,"ai.model.id":Rr.modelId,"ai.prompt.messages":{input:()=>F0(Ne)},"ai.prompt.tools":{input:()=>Jr?.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>gn!=null?JSON.stringify(gn):void 0},"gen_ai.system":Rr.provider,"gen_ai.request.model":Rr.modelId,"gen_ai.request.frequency_penalty":Be.frequencyPenalty,"gen_ai.request.max_tokens":Be.maxOutputTokens,"gen_ai.request.presence_penalty":Be.presencePenalty,"gen_ai.request.stop_sequences":Be.stopSequences,"gen_ai.request.temperature":Be.temperature,"gen_ai.request.top_k":Be.topK,"gen_ai.request.top_p":Be.topP}}),tracer:Dt,endWhenDone:!1,fn:async we=>({startTimestampMs:S(),doStreamSpan:we,result:await Rr.doStream({...Be,tools:Jr,toolChoice:gn,responseFormat:await h?.responseFormat,prompt:Ne,providerOptions:ks,abortSignal:s,headers:r,includeRawChunks:Oi})})})),Ui=RC({tools:f,generatorStream:ji,tracer:Dt,telemetry:t,system:u,messages:mn,repairToolCall:w,abortSignal:s,experimental_context:P,generateId:I,stepNumber:X.length,model:bs,onToolCallStart:[pe,N.onToolCallStart],onToolCallFinish:[Z,N.onToolCallFinish]}),zE=(Mi=F?.requestBody)==null||Mi?bo??{}:{...bo,body:void 0},Ts=[],Ss=[];let Gu;const Wu={};let ko="other",Ku,kr=Fl(),Yu,ev=!0,Pr={id:I(),timestamp:new Date,modelId:sr.modelId},tv="";dt.addStream(Ui.pipeThrough(new TransformStream({async transform(we,Nt){var Is,xs,Di,ht,Nr;if(vs(),we.type==="stream-start"){Gu=we.warnings;return}if(ev){const mt=S()-Gr;ev=!1,ct.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":mt}),ct.setAttributes({"ai.response.msToFirstChunk":mt}),Nt.enqueue({type:"start-step",request:zE,warnings:Gu??[]})}const Qu=we.type;switch(Qu){case"tool-approval-request":case"text-start":case"text-end":{Nt.enqueue(we);break}case"text-delta":{we.delta.length>0&&(Nt.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),tv+=we.delta);break}case"reasoning-start":case"reasoning-end":{Nt.enqueue(we);break}case"reasoning-delta":{Nt.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{Nt.enqueue(we),Ts.push(we);break}case"tool-result":{Nt.enqueue(we),we.preliminary||Ss.push(we);break}case"tool-error":{Nt.enqueue(we),Ss.push(we);break}case"response-metadata":{Pr={id:(Is=we.id)!=null?Is:Pr.id,timestamp:(xs=we.timestamp)!=null?xs:Pr.timestamp,modelId:(Di=we.modelId)!=null?Di:Pr.modelId};break}case"finish":{kr=we.usage,ko=we.finishReason,Ku=we.rawFinishReason,Yu=we.providerMetadata;const mt=S()-Gr;ct.addEvent("ai.stream.finish"),ct.setAttributes({"ai.response.msToFinish":mt,"ai.response.avgOutputTokensPerSecond":1e3*((ht=kr.outputTokens)!=null?ht:0)/mt});break}case"file":{Nt.enqueue(we);break}case"source":{Nt.enqueue(we);break}case"tool-input-start":{Wu[we.id]=we.toolName;const mt=f?.[we.toolName];mt?.onInputStart!=null&&await mt.onInputStart({toolCallId:we.id,messages:mn,abortSignal:s,experimental_context:P}),Nt.enqueue({...we,dynamic:(Nr=we.dynamic)!=null?Nr:mt?.type==="dynamic",title:mt?.title});break}case"tool-input-end":{delete Wu[we.id],Nt.enqueue(we);break}case"tool-input-delta":{const mt=Wu[we.id],Xu=f?.[mt];Xu?.onInputDelta!=null&&await Xu.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:mn,abortSignal:s,experimental_context:P}),Nt.enqueue(we);break}case"error":{Nt.enqueue(we),ko="error";break}case"raw":{Oi&&Nt.enqueue(we);break}default:{const mt=Qu;throw new Error(`Unknown chunk type: ${mt}`)}}},async flush(we){const Nt=Ts.length>0?JSON.stringify(Ts):void 0;try{ct.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":ko,"ai.response.text":{output:()=>tv},"ai.response.reasoning":{output:()=>{const ht=G.filter(Nr=>Nr.type==="reasoning");return ht.length>0?ht.map(Nr=>Nr.text).join(`
|
|
69
|
-
`):void 0}},"ai.response.toolCalls":{output:()=>Nt},"ai.response.id":Pr.id,"ai.response.model":Pr.modelId,"ai.response.timestamp":Pr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Yu),"ai.usage.inputTokens":kr.inputTokens,"ai.usage.outputTokens":kr.outputTokens,"ai.usage.totalTokens":kr.totalTokens,"ai.usage.reasoningTokens":kr.reasoningTokens,"ai.usage.cachedInputTokens":kr.cachedInputTokens,"gen_ai.response.finish_reasons":[ko],"gen_ai.response.id":Pr.id,"gen_ai.response.model":Pr.modelId,"gen_ai.usage.input_tokens":kr.inputTokens,"gen_ai.usage.output_tokens":kr.outputTokens}}))}catch{}finally{ct.end()}we.enqueue({type:"finish-step",finishReason:ko,rawFinishReason:Ku,usage:kr,providerMetadata:Yu,response:{...Pr,headers:Cs?.headers}});const Is=B0(nt,kr);await L.promise;const xs=Ts.filter(ht=>ht.providerExecuted!==!0),Di=Ss.filter(ht=>ht.providerExecuted!==!0);for(const ht of Ts){if(ht.providerExecuted!==!0)continue;const Nr=f?.[ht.toolName];Nr?.type==="provider"&&Nr.supportsDeferredResults&&(Ss.some(mt=>(mt.type==="tool-result"||mt.type==="tool-error")&&mt.toolCallId===ht.toolCallId)||le.set(ht.toolCallId,{toolName:ht.toolName}))}for(const ht of Ss)(ht.type==="tool-result"||ht.type==="tool-error")&&le.delete(ht.toolCallId);if(ws(),Ai(),(xs.length>0&&Di.length===xs.length||le.size>0)&&!await nm({stopConditions:_,steps:X})){br.push(...await Bl({content:X[X.length-1].content,tools:f}));try{await te({currentStep:Ge+1,responseMessages:br,usage:Is})}catch(ht){we.enqueue({type:"error",error:ht}),dt.closeStream()}}else we.enqueue({type:"finish",finishReason:ko,rawFinishReason:Ku,totalUsage:Is}),dt.closeStream()}})))}finally{ws(),Ai()}}await te({currentStep:0,responseMessages:Se,usage:Fl()})}}).catch(pt=>{dt.addStream(new ReadableStream({start(Ee){Ee.enqueue({type:"error",error:pt}),Ee.close()}})),dt.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 Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await EC({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 Jo(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 Cr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Jo(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:ta()).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:i=!0,sendFinish:a=!0,onError:l=yn}={}){const c=t!=null?bC({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}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});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":{i&&f.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&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 Jo(IC({stream:m,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}={}){xC({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){vC({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 wC({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 _C({textStream:this.textStream,...e})}};Oo({prefix:"aiobj",size:24}),Oo({prefix:"aiobj",size:24});let Gl;Gl=globalThis.crypto;async function OC(e){return(await Gl).getRandomValues(new Uint8Array(e))}async function AC(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await OC(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function qC(e){return await AC(e)}async function LC(e){const t=await(await Gl).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function hm(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await qC(e),r=await LC(t);return{code_verifier:t,code_challenge:r}}var jC="AI_MCPClientError",mm=`vercel.ai.error.${jC}`,UC=Symbol.for(mm),gm,ym,De=class extends(ym=ge,gm=UC,ym){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[gm]=!0,this.data=n,this.code=o}static isInstance(e){return ge.hasMarker(e,mm)}},oo="2025-06-18",DC=[oo,"2025-03-26","2024-11-05"],zC=ce(ye(d(),$e())),FC=at({name:d(),version:d()}),na=at({_meta:ce(C({}).loose())}),Lr=na,_m=C({method:d(),params:ce(na)}),vm=C({applyDefaults:ce(he())}).loose(),VC=at({experimental:ce(C({}).loose()),logging:ce(C({}).loose()),prompts:ce(at({listChanged:ce(he())})),resources:ce(at({subscribe:ce(he()),listChanged:ce(he())})),tools:ce(at({listChanged:ce(he())})),elicitation:ce(vm)});C({elicitation:ce(vm)}).loose();var ZC=Lr.extend({protocolVersion:d(),capabilities:VC,serverInfo:FC,instructions:ce(d())}),Wl=Lr.extend({nextCursor:ce(d())}),BC=C({name:d(),title:ce(d()),description:ce(d()),inputSchema:C({type:R("object"),properties:ce(C({}).loose())}).loose(),outputSchema:ce(C({}).loose()),annotations:ce(C({title:ce(d())}).loose()),_meta:zC}).loose(),HC=Wl.extend({tools:q(BC)}),wm=C({type:R("text"),text:d()}).loose(),bm=C({type:R("image"),data:qp(),mimeType:d()}).loose(),JC=C({uri:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d()),size:ce(U())}).loose(),GC=Wl.extend({resources:q(JC)}),km=C({uri:d(),name:ce(d()),title:ce(d()),mimeType:ce(d())}).loose(),Cm=km.extend({text:d()}),Tm=km.extend({blob:qp()}),Sm=C({type:R("resource"),resource:ae([Cm,Tm])}).loose(),WC=Lr.extend({content:q(ae([wm,bm,Sm])),structuredContent:ce($e()),isError:he().default(!1).optional()}).or(Lr.extend({toolResult:$e()})),KC=C({uriTemplate:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d())}).loose(),YC=Lr.extend({resourceTemplates:q(KC)}),QC=Lr.extend({contents:q(ae([Cm,Tm]))}),XC=C({name:d(),description:ce(d()),required:ce(he())}).loose(),e5=C({name:d(),title:ce(d()),description:ce(d()),arguments:ce(q(XC))}).loose(),t5=Wl.extend({prompts:q(e5)}),r5=C({role:ae([R("user"),R("assistant")]),content:ae([wm,bm,Sm])}).loose(),n5=Lr.extend({description:ce(d()),messages:q(r5)}),o5=na.extend({message:d(),requestedSchema:$e()}),Im=_m.extend({method:R("elicitation/create"),params:o5}),s5=Lr.extend({action:ae([R("accept"),R("decline"),R("cancel")]),content:ce(ye(d(),$e()))}),oa="2.0",a5=C({jsonrpc:R(oa),id:ae([d(),U().int()])}).merge(_m).strict(),i5=C({jsonrpc:R(oa),id:ae([d(),U().int()]),result:Lr}).strict(),l5=C({jsonrpc:R(oa),id:ae([d(),U().int()]),error:C({code:U().int(),message:d(),data:ce($e())})}).strict(),c5=C({jsonrpc:R(oa)}).merge(C({method:d(),params:ce(na)})).strict(),Go=ae([a5,c5,i5,l5]),xm=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Em=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:U().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Bt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Hp.custom,message:"URL must be parseable",fatal:!0}),Bd}).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"}),u5=C({resource:d().url(),authorization_servers:q(Bt).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:he().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:he().optional()}).passthrough(),$m=C({issuer:d(),authorization_endpoint:Bt,token_endpoint:Bt,registration_endpoint:Bt.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(),d5=C({issuer:d(),authorization_endpoint:Bt,token_endpoint:Bt,userinfo_endpoint:Bt.optional(),jwks_uri:Bt,registration_endpoint:Bt.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(),p5=d5.merge($m.pick({code_challenge_methods_supported:!0})),f5=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:U().optional(),client_secret_expires_at:U().optional()}).strip(),h5=C({redirect_uris:q(Bt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Bt.optional(),logo_uri:Bt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Bt.optional(),policy_uri:d().optional(),jwks_uri:Bt.optional(),jwks:bt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),m5=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),g5=h5.merge(f5),y5="AI_MCPClientOAuthError",Rm=`vercel.ai.error.${y5}`,_5=Symbol.for(Rm),Pm,Nm,Wo=class extends(Nm=ge,Pm=_5,Nm){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[Pm]=!0}static isInstance(e){return ge.hasMarker(e,Rm)}},so=class extends Wo{};so.errorCode="server_error";var sa=class extends Wo{};sa.errorCode="invalid_client";var aa=class extends Wo{};aa.errorCode="invalid_grant";var ia=class extends Wo{};ia.errorCode="unauthorized_client";var v5={[so.errorCode]:so,[sa.errorCode]:sa,[aa.errorCode]:aa,[ia.errorCode]:ia};function w5(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function b5({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 la=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function ca(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 k5(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Kl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Kl(e,void 0,r):void 0;throw n}}async function Mm(e,t,r=fetch){return await Kl(e,{"MCP-Protocol-Version":t},r)}function C5(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function T5(e,t,r,n){var o,s;const i=new URL(e),a=(o=n?.protocolVersion)!=null?o:oo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=k5(t,i.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:i),l.search=i.search}let c=await Mm(l,a,r);if(!n?.metadataUrl&&C5(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await Mm(u,a,r)}return c}async function S5(e,t,r=fetch){const n=await T5(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 u5.parse(await n.json())}function I5(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 x5(e,{fetchFn:t=fetch,protocolVersion:r=oo}={}){var n;const o={"MCP-Protocol-Version":r},s=I5(e);for(const{url:i,type:a}of s){const l=await Kl(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 $m.parse(await l.json());{const c=p5.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 E5(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 hm(),m=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",a),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"),i&&c.searchParams.set("resource",i.href),{authorizationUrl:c,codeVerifier:m}}function Om(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 Am(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":$5(o,s,r);return;case"client_secret_post":R5(o,s,n);return;case"none":P5(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function $5(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 R5(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function P5(e,t){t.set("client_id",e)}async function Yl(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=m5.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=v5[o]||so;return new a({message:s||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new so({message:o})}}async function N5(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:a,fetchFn:l}){var c;const u="authorization_code",m=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const 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(a)a(p,f,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=Om(r,v);Am(y,r,p,f)}i&&f.set("resource",i.href);const g=await(l??fetch)(m,{method:"POST",headers:p,body:f});if(!g.ok)throw await Yl(g);return Em.parse(await g.json())}async function M5(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",Accept:"application/json"}),m=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,m,e,t);else{const f=(a=t?.token_endpoint_auth_methods_supported)!=null?a:[],g=Om(r,f);Am(g,r,u,m)}o&&m.set("resource",o.href);const p=await(i??fetch)(c,{method:"POST",headers:u,body:m});if(!p.ok)throw await Yl(p);return Em.parse({refresh_token:n,...await p.json()})}async function O5(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 Yl(s);return g5.parse(await s.json())}async function ua(e,t){var r,n;try{return await Ql(e,t)}catch(o){if(o instanceof sa||o instanceof ia)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Ql(e,t);if(o instanceof aa)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Ql(e,t);throw o}}async function A5(e,t,r){const n=w5(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!b5({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 Ql(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await S5(t,{resourceMetadataUrl:o},s),i.authorization_servers&&i.authorization_servers.length>0&&(a=i.authorization_servers[0])}catch{}a||(a=t);const l=await A5(t,e,i),c=await x5(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 O5(a,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),y=await N5(a,{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 M5(a,{metadata:c,clientInformation:u,refreshToken:m.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Wo)||v instanceof so))throw v}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await E5(a,{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 q5=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":oo};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return nn(t,`ai-sdk/${xm}`,Ao())}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=ca(u);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new la;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(g){return(i=this.onerror)==null||i.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 De({message:g});return(a=this.onerror)==null||a.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).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 De({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:h,data:T}=_;if(h==="endpoint"){if(this.endpoint=new URL(T,this.url),this.endpoint.origin!==this.url.origin)throw new De({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 b=Go.parse(JSON.parse(T));(g=this.onmessage)==null||g.call(this,b)}catch(b){const k=new De({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(v=this.onerror)==null||v.call(this,k)}}}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 De({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,i,a,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},m=await fetch(t,u);if(m.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ca(m);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new la;(s=this.onerror)==null||s.call(this,f);return}}catch(p){(i=this.onerror)==null||i.call(this,p);return}return r(!0)}if(!m.ok){const p=await m.text().catch(()=>null),f=new De({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${p}`});(a=this.onerror)==null||a.call(this,f);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},L5=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":oo};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 nn(t,`ai-sdk/${xm}`,Ao())}async start(){if(this.abortController)throw new De({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,i,a,l,c;try{const m={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},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=ca(p);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new la}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 De({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=>Go.parse(h)):[Go.parse(w)];for(const h of _)(i=this.onmessage)==null||i.call(this,h);return}if(v.includes("text/event-stream")){if(!p.body){const T=new De({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(a=this.onerror)==null||a.call(this,T),T}const _=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).getReader();(async()=>{var T,b,k;try{for(;;){const{done:S,value:I}=await _.read();if(S)return;const{event:x,data:j}=I;if(x==="message")try{const M=Go.parse(JSON.parse(j));(T=this.onmessage)==null||T.call(this,M)}catch(M){const D=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:M});(b=this.onerror)==null||b.call(this,D)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const y=new De({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 De({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=ca(c);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new la;(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 De({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 Kn).getReader(),f=async()=>{var g,v,y,w;try{for(;;){const{done:_,value:h}=await p.read();if(_)return;const{event:T,data:b,id:k}=h;if(k&&(this.lastInboundEventId=k),T==="message")try{const S=Go.parse(JSON.parse(b));(g=this.onmessage)==null||g.call(this,S)}catch(S){const I=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,I)}}}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;(i=this.onerror)==null||i.call(this,l),(a=this.abortController)!=null&&a.signal.aborted||this.scheduleInboundSseReconnection()}}};function j5(e){switch(e.type){case"sse":return new q5(e);case"http":return new L5(e);default:throw new De({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function U5(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var D5="1.0.0";function qm({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 z5(e){const t=new F5(e);return await t.init(),t}var F5=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=D5,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},U5(e)?this.transport=e:this.transport=j5(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 De({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:oo,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:ZC});if(e===void 0)throw new De({message:"Server sent invalid initialize result"});if(!DC.includes(e.protocolVersion))throw new De({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 De({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new De({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new De({message:"Server does not support prompts"});break;default:throw new De({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new De({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 De({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 De({message:"Failed to parse server response",cause:u});o(m)}}),this.transport.send(a).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:HC,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:WC,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:GC,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:QC,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:YC,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:t5,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:n5,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:i,description:a,inputSchema:l,annotations:c,_meta:u}of e.tools){const m=i??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"?Df({description:a,title:m,inputSchema:ro({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:qm}):{description:a,title:m,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:g,toModelOutput:qm};o[s]={...v,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await Xt({value:e.structuredContent,schema:Sn(t)});if(!n.success)throw new De({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 er({text:n.text,schema:t});if(!o.success)throw new De({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new De({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!==Im)throw new De({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=Im.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=s5.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 De({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 De({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new De({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function da(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Lm(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...da(t.headers),...da(n.headers)}:t.headers};return e(r,o)}:e}const pa="2025-11-25",V5=[pa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Pn="io.modelcontextprotocol/related-task",fa="2.0",xt=Zp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),jm=ae([d(),U().int()]),Um=d();at({ttl:ae([U(),Us()]).optional(),pollInterval:U().optional()});const Z5=C({ttl:U().optional()}),B5=C({taskId:d()}),Xl=at({progressToken:jm.optional(),[Pn]:B5.optional()}),Kt=C({_meta:Xl.optional()}),Ko=Kt.extend({task:Z5.optional()}),H5=e=>Ko.safeParse(e).success,Et=C({method:d(),params:Kt.loose().optional()}),rr=C({_meta:Xl.optional()}),nr=C({method:d(),params:rr.loose().optional()}),$t=at({_meta:Xl.optional()}),ha=ae([d(),U().int()]),Dm=C({jsonrpc:R(fa),id:ha,...Et.shape}).strict(),ec=e=>Dm.safeParse(e).success,zm=C({jsonrpc:R(fa),...nr.shape}).strict(),J5=e=>zm.safeParse(e).success,tc=C({jsonrpc:R(fa),id:ha,result:$t}).strict(),Yo=e=>tc.safeParse(e).success;var xe;(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"})(xe||(xe={}));const rc=C({jsonrpc:R(fa),id:ha.optional(),error:C({code:U().int(),message:d(),data:$e().optional()})}).strict(),G5=e=>rc.safeParse(e).success,Nn=ae([Dm,zm,tc,rc]);ae([tc,rc]);const Mn=$t.strict(),W5=rr.extend({requestId:ha.optional(),reason:d().optional()}),nc=nr.extend({method:R("notifications/cancelled"),params:W5}),K5=C({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:me(["light","dark"]).optional()}),Qo=C({icons:q(K5).optional()}),ao=C({name:d(),title:d().optional()}),Fm=ao.extend({...ao.shape,...Qo.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),Y5=Yi(C({applyDefaults:he().optional()}),ye(d(),$e())),Q5=Bp(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Yi(C({form:Y5.optional(),url:xt.optional()}),ye(d(),$e()).optional())),X5=at({list:xt.optional(),cancel:xt.optional(),requests:at({sampling:at({createMessage:xt.optional()}).optional(),elicitation:at({create:xt.optional()}).optional()}).optional()}),eT=at({list:xt.optional(),cancel:xt.optional(),requests:at({tools:at({call:xt.optional()}).optional()}).optional()}),tT=C({experimental:ye(d(),xt).optional(),sampling:C({context:xt.optional(),tools:xt.optional()}).optional(),elicitation:Q5.optional(),roots:C({listChanged:he().optional()}).optional(),tasks:X5.optional()}),rT=Kt.extend({protocolVersion:d(),capabilities:tT,clientInfo:Fm}),nT=Et.extend({method:R("initialize"),params:rT}),oT=C({experimental:ye(d(),xt).optional(),logging:xt.optional(),completions:xt.optional(),prompts:C({listChanged:he().optional()}).optional(),resources:C({subscribe:he().optional(),listChanged:he().optional()}).optional(),tools:C({listChanged:he().optional()}).optional(),tasks:eT.optional()}),Vm=$t.extend({protocolVersion:d(),capabilities:oT,serverInfo:Fm,instructions:d().optional()}),Zm=nr.extend({method:R("notifications/initialized"),params:rr.optional()}),sT=e=>Zm.safeParse(e).success,oc=Et.extend({method:R("ping"),params:Kt.optional()}),aT=C({progress:U(),total:ce(U()),message:ce(d())}),iT=C({...rr.shape,...aT.shape,progressToken:jm}),sc=nr.extend({method:R("notifications/progress"),params:iT}),lT=Kt.extend({cursor:Um.optional()}),Xo=Et.extend({params:lT.optional()}),es=$t.extend({nextCursor:Um.optional()}),cT=me(["working","input_required","completed","failed","cancelled"]),ts=C({taskId:d(),status:cT,ttl:ae([U(),Us()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ce(U()),statusMessage:ce(d())}),rs=$t.extend({task:ts}),uT=rr.merge(ts),ma=nr.extend({method:R("notifications/tasks/status"),params:uT}),ac=Et.extend({method:R("tasks/get"),params:Kt.extend({taskId:d()})}),ic=$t.merge(ts),lc=Et.extend({method:R("tasks/result"),params:Kt.extend({taskId:d()})});$t.loose();const cc=Xo.extend({method:R("tasks/list")}),uc=es.extend({tasks:q(ts)}),dc=Et.extend({method:R("tasks/cancel"),params:Kt.extend({taskId:d()})}),dT=$t.merge(ts),Bm=C({uri:d(),mimeType:ce(d()),_meta:ye(d(),$e()).optional()}),Hm=Bm.extend({text:d()}),pc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Jm=Bm.extend({blob:pc}),ns=me(["user","assistant"]),io=C({audience:q(ns).optional(),priority:U().min(0).max(1).optional(),lastModified:Rp({offset:!0}).optional()}),Gm=C({...ao.shape,...Qo.shape,uri:d(),description:ce(d()),mimeType:ce(d()),annotations:io.optional(),_meta:ce(at({}))}),pT=C({...ao.shape,...Qo.shape,uriTemplate:d(),description:ce(d()),mimeType:ce(d()),annotations:io.optional(),_meta:ce(at({}))}),fT=Xo.extend({method:R("resources/list")}),Wm=es.extend({resources:q(Gm)}),hT=Xo.extend({method:R("resources/templates/list")}),Km=es.extend({resourceTemplates:q(pT)}),fc=Kt.extend({uri:d()}),mT=fc,gT=Et.extend({method:R("resources/read"),params:mT}),Ym=$t.extend({contents:q(ae([Hm,Jm]))}),hc=nr.extend({method:R("notifications/resources/list_changed"),params:rr.optional()}),yT=fc,_T=Et.extend({method:R("resources/subscribe"),params:yT}),vT=fc,wT=Et.extend({method:R("resources/unsubscribe"),params:vT}),bT=rr.extend({uri:d()}),Qm=nr.extend({method:R("notifications/resources/updated"),params:bT}),kT=C({name:d(),description:ce(d()),required:ce(he())}),CT=C({...ao.shape,...Qo.shape,description:ce(d()),arguments:ce(q(kT)),_meta:ce(at({}))}),TT=Xo.extend({method:R("prompts/list")}),Xm=es.extend({prompts:q(CT)}),ST=Kt.extend({name:d(),arguments:ye(d(),d()).optional()}),IT=Et.extend({method:R("prompts/get"),params:ST}),mc=C({type:R("text"),text:d(),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),gc=C({type:R("image"),data:pc,mimeType:d(),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),yc=C({type:R("audio"),data:pc,mimeType:d(),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),xT=C({type:R("tool_use"),name:d(),id:d(),input:ye(d(),$e()),_meta:ye(d(),$e()).optional()}),ET=C({type:R("resource"),resource:ae([Hm,Jm]),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),$T=Gm.extend({type:R("resource_link")}),_c=ae([mc,gc,yc,$T,ET]),RT=C({role:ns,content:_c}),e2=$t.extend({description:d().optional(),messages:q(RT)}),vc=nr.extend({method:R("notifications/prompts/list_changed"),params:rr.optional()}),PT=C({title:d().optional(),readOnlyHint:he().optional(),destructiveHint:he().optional(),idempotentHint:he().optional(),openWorldHint:he().optional()}),NT=C({taskSupport:me(["required","optional","forbidden"]).optional()}),t2=C({...ao.shape,...Qo.shape,description:d().optional(),inputSchema:C({type:R("object"),properties:ye(d(),xt).optional(),required:q(d()).optional()}).catchall($e()),outputSchema:C({type:R("object"),properties:ye(d(),xt).optional(),required:q(d()).optional()}).catchall($e()).optional(),annotations:PT.optional(),execution:NT.optional(),_meta:ye(d(),$e()).optional()}),MT=Xo.extend({method:R("tools/list")}),r2=es.extend({tools:q(t2)}),os=$t.extend({content:q(_c).default([]),structuredContent:ye(d(),$e()).optional(),isError:he().optional()});os.or($t.extend({toolResult:$e()}));const OT=Ko.extend({name:d(),arguments:ye(d(),$e()).optional()}),AT=Et.extend({method:R("tools/call"),params:OT}),wc=nr.extend({method:R("notifications/tools/list_changed"),params:rr.optional()}),qT=C({autoRefresh:he().default(!0),debounceMs:U().int().nonnegative().default(300)}),n2=me(["debug","info","notice","warning","error","critical","alert","emergency"]),LT=Kt.extend({level:n2}),jT=Et.extend({method:R("logging/setLevel"),params:LT}),UT=rr.extend({level:n2,logger:d().optional(),data:$e()}),o2=nr.extend({method:R("notifications/message"),params:UT}),DT=C({name:d().optional()}),zT=C({hints:q(DT).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),FT=C({mode:me(["auto","required","none"]).optional()}),VT=C({type:R("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(_c).default([]),structuredContent:C({}).loose().optional(),isError:he().optional(),_meta:ye(d(),$e()).optional()}),ZT=je("type",[mc,gc,yc]),ga=je("type",[mc,gc,yc,xT,VT]),BT=C({role:ns,content:ae([ga,q(ga)]),_meta:ye(d(),$e()).optional()}),HT=Ko.extend({messages:q(BT),modelPreferences:zT.optional(),systemPrompt:d().optional(),includeContext:me(["none","thisServer","allServers"]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:q(d()).optional(),metadata:xt.optional(),tools:q(t2).optional(),toolChoice:FT.optional()}),bc=Et.extend({method:R("sampling/createMessage"),params:HT}),kc=$t.extend({model:d(),stopReason:ce(me(["endTurn","stopSequence","maxTokens"]).or(d())),role:ns,content:ZT}),s2=$t.extend({model:d(),stopReason:ce(me(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:ns,content:ae([ga,q(ga)])}),JT=C({type:R("boolean"),title:d().optional(),description:d().optional(),default:he().optional()}),GT=C({type:R("string"),title:d().optional(),description:d().optional(),minLength:U().optional(),maxLength:U().optional(),format:me(["email","uri","date","date-time"]).optional(),default:d().optional()}),WT=C({type:me(["number","integer"]),title:d().optional(),description:d().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),KT=C({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),YT=C({type:R("string"),title:d().optional(),description:d().optional(),oneOf:q(C({const:d(),title:d()})),default:d().optional()}),QT=C({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),XT=ae([KT,YT]),eS=C({type:R("array"),title:d().optional(),description:d().optional(),minItems:U().optional(),maxItems:U().optional(),items:C({type:R("string"),enum:q(d())}),default:q(d()).optional()}),tS=C({type:R("array"),title:d().optional(),description:d().optional(),minItems:U().optional(),maxItems:U().optional(),items:C({anyOf:q(C({const:d(),title:d()}))}),default:q(d()).optional()}),rS=ae([eS,tS]),nS=ae([QT,XT,rS]),oS=ae([nS,JT,GT,WT]),sS=Ko.extend({mode:R("form").optional(),message:d(),requestedSchema:C({type:R("object"),properties:ye(d(),oS),required:q(d()).optional()})}),aS=Ko.extend({mode:R("url"),message:d(),elicitationId:d(),url:d().url()}),iS=ae([sS,aS]),Cc=Et.extend({method:R("elicitation/create"),params:iS}),lS=rr.extend({elicitationId:d()}),cS=nr.extend({method:R("notifications/elicitation/complete"),params:lS}),Tc=$t.extend({action:me(["accept","decline","cancel"]),content:Bp(e=>e===null?void 0:e,ye(d(),ae([d(),U(),he(),q(d())])).optional())}),uS=C({type:R("ref/resource"),uri:d()}),dS=C({type:R("ref/prompt"),name:d()}),pS=Kt.extend({ref:ae([dS,uS]),argument:C({name:d(),value:d()}),context:C({arguments:ye(d(),d()).optional()}).optional()}),fS=Et.extend({method:R("completion/complete"),params:pS}),a2=$t.extend({completion:at({values:q(d()).max(100),total:ce(U().int()),hasMore:ce(he())})}),hS=C({uri:d().startsWith("file://"),name:d().optional(),_meta:ye(d(),$e()).optional()}),i2=Et.extend({method:R("roots/list"),params:Kt.optional()}),l2=$t.extend({roots:q(hS)}),mS=nr.extend({method:R("notifications/roots/list_changed"),params:rr.optional()});ae([oc,nT,fS,jT,IT,TT,fT,hT,gT,_T,wT,AT,MT,ac,lc,cc,dc]),ae([nc,sc,Zm,mS,ma]),ae([Mn,kc,s2,Tc,l2,ic,uc,rs]),ae([oc,bc,Cc,i2,ac,lc,cc,dc]),ae([nc,sc,o2,Qm,hc,wc,vc,ma,cS]),ae([Mn,Vm,a2,e2,Xm,Wm,Km,Ym,os,r2,ic,uc,rs]);class be 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===xe.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new gS(o.elicitations,r)}return new be(t,r,n)}}class gS extends be{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(xe.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const Rt=Sb().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Hp.custom,message:"URL must be parseable",fatal:!0}),Bd}).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"}),yS=at({resource:d().url(),authorization_servers:q(Rt).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:he().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:he().optional()}),c2=at({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,registration_endpoint:Rt.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:Rt.optional(),revocation_endpoint:Rt.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:he().optional()}),_S=at({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,userinfo_endpoint:Rt.optional(),jwks_uri:Rt,registration_endpoint:Rt.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:he().optional(),request_parameter_supported:he().optional(),request_uri_parameter_supported:he().optional(),require_request_uri_registration:he().optional(),op_policy_uri:Rt.optional(),op_tos_uri:Rt.optional(),client_id_metadata_document_supported:he().optional()}),vS=C({..._S.shape,...c2.pick({code_challenge_methods_supported:!0}).shape}),wS=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Jp().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),bS=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),u2=Rt.optional().or(R("").transform(()=>{})),kS=C({redirect_uris:q(Rt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Rt.optional(),logo_uri:u2,scope:d().optional(),contacts:q(d()).optional(),tos_uri:u2,policy_uri:d().optional(),jwks_uri:Rt.optional(),jwks:bt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),CS=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:U().optional(),client_secret_expires_at:U().optional()}).strip(),TS=kS.merge(CS);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function SS(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function IS({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 Ct 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 Sc extends Ct{}Sc.errorCode="invalid_request";class ya extends Ct{}ya.errorCode="invalid_client";class _a extends Ct{}_a.errorCode="invalid_grant";class va extends Ct{}va.errorCode="unauthorized_client";class Ic extends Ct{}Ic.errorCode="unsupported_grant_type";class xc extends Ct{}xc.errorCode="invalid_scope";class Ec extends Ct{}Ec.errorCode="access_denied";class lo extends Ct{}lo.errorCode="server_error";class $c extends Ct{}$c.errorCode="temporarily_unavailable";class Rc extends Ct{}Rc.errorCode="unsupported_response_type";class Pc extends Ct{}Pc.errorCode="unsupported_token_type";class Nc extends Ct{}Nc.errorCode="invalid_token";class Mc extends Ct{}Mc.errorCode="method_not_allowed";class Oc extends Ct{}Oc.errorCode="too_many_requests";class wa extends Ct{}wa.errorCode="invalid_client_metadata";class Ac extends Ct{}Ac.errorCode="insufficient_scope";class qc extends Ct{}qc.errorCode="invalid_target";const xS={[Sc.errorCode]:Sc,[ya.errorCode]:ya,[_a.errorCode]:_a,[va.errorCode]:va,[Ic.errorCode]:Ic,[xc.errorCode]:xc,[Ec.errorCode]:Ec,[lo.errorCode]:lo,[$c.errorCode]:$c,[Rc.errorCode]:Rc,[Pc.errorCode]:Pc,[Nc.errorCode]:Nc,[Mc.errorCode]:Mc,[Oc.errorCode]:Oc,[wa.errorCode]:wa,[Ac.errorCode]:Ac,[qc.errorCode]:qc};class or extends Error{constructor(t){super(t??"Unauthorized")}}function ES(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Lc="code",jc="S256";function $S(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&&ES(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 RS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":PS(o,s,r);return;case"client_secret_post":NS(o,s,n);return;case"none":MS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function PS(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 NS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function MS(e,t){t.set("client_id",e)}async function d2(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=bS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=xS[o]||lo;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new lo(o)}}async function On(e,t){try{return await Uc(e,t)}catch(r){if(r instanceof ya||r instanceof va)return await e.invalidateCredentials?.("all"),await Uc(e,t);if(r instanceof _a)return await e.invalidateCredentials?.("tokens"),await Uc(e,t);throw r}}async function Uc(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await qS(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 AS(t,e,i),c=await zS(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 y=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!OS(w))throw new wa(`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 HS(a,{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 BS(e,a,{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 ZS(a,{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 Ct)||y instanceof lo))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:v}=await FS(a,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(g),"REDIRECT"}function OS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function AS(e,t,r){const n=SS(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!IS({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 ba(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Dc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Dc(e,"scope")||void 0,a=Dc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Dc(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 qS(e,t,r=fetch){const n=await US(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 yS.parse(await n.json())}async function zc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?zc(e,void 0,r):void 0;throw n}}function LS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function p2(e,t,r=fetch){return await zc(e,{"MCP-Protocol-Version":t},r)}function jS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function US(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??pa;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=LS(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await p2(i,s,r);if(!n?.metadataUrl&&jS(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await p2(l,s,r)}return a}function DS(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 zS(e,{fetchFn:t=fetch,protocolVersion:r=pa}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=DS(e);for(const{url:s,type:i}of o){const a=await zc(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"?c2.parse(await a.json()):vS.parse(await a.json())}}}async function FS(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(Lc))throw new Error(`Incompatible auth server: does not support response type ${Lc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(jc))throw new Error(`Incompatible auth server: does not support code challenge method ${jc}`)}else a=new URL("/authorize",e);const l=await hm(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",Lc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",jc),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 VS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function f2(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],m=$S(n,u);RS(m,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await d2(c);return wS.parse(await c.json())}async function ZS(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 f2(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function BS(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=VS(o,c,e.redirectUrl)}const l=await e.clientInformation();return f2(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function HS(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 d2(s);return TS.parse(await s.json())}const JS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class co extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class ka{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=Lm(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??JS}async _authThenStart(){if(!this._authProvider)throw new or("No auth provider");let t;try{t=await On(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 or;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=da(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 co(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 Kn({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:g}=await u.read();if(g)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const v=Nn.parse(JSON.parse(f.data));Yo(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(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 or("No auth provider");if(await On(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or("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:ec(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 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 p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new co(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:g}=ba(a);if(this._resourceMetadataUrl=f,this._scope=g,await On(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:g,error:v}=ba(a);if(v==="insufficient_scope"){const y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new co(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await On(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new or;return this.send(t)}}throw new co(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),sT(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=a.headers.get("content-type");if(u)if(m?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(m?.includes("application/json")){const p=await a.json(),f=Array.isArray(p)?p.map(g=>Nn.parse(g)):[Nn.parse(p)];for(const g of f)this.onmessage?.(g)}else throw await a.body?.cancel(),new co(-1,`Unexpected content type: ${m}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new co(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 Ca{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new Ca,r=new Ca;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 Fc=C({error:C({message:d(),type:d().nullish(),param:bt().nullish(),code:ae([d(),U()]).nullish()})}),fr=on({errorSchema:Fc,errorToMessage:e=>e.error.message});function h2(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("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 m2(e){var t,r,n,o,s,i;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 a=(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=(i=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?i:0;return{inputTokens:{total:a,noCache:a-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function GS({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:i}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:i});break}case"developer":{n.push({role:"developer",content:i});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,l)=>{var c,u,m;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const p=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${p};base64,${eo(a.data)}`,detail:(u=(c=a.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Cr({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:eo(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:eo(a.data),format:"mp3"}};default:throw new Cr({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Cr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(m=a.filename)!=null?m:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${eo(a.data)}`}}}else throw new Cr({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const l=[];for(const c of i)switch(c.type){case"text":{a+=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:a,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const a of i){if(a.type==="tool-approval-response")continue;const l=a.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:a.toolCallId,content:c})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:o}}function Vc({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function g2(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 WS=ve(()=>_e(C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({message:C({role:R("assistant").nullish(),content:d().nullish(),tool_calls:q(C({id:d().nullish(),type:R("function"),function:C({name:d(),arguments:d()})})).nullish(),annotations:q(C({type:R("url_citation"),url_citation:C({start_index:U(),end_index:U(),url:d(),title:d()})})).nullish()}),index:U(),logprobs:C({content:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:C({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:C({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish()}))),KS=ve(()=>_e(ae([C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({delta:C({role:me(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(C({index:U(),id:d().nullish(),type:R("function").nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(C({type:R("url_citation"),url_citation:C({start_index:U(),end_index:U(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:C({content:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:U()})),usage:C({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:C({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish()}),Fc]))),YS=ve(()=>_e(C({logitBias:ye(Jp(),U()).optional(),logprobs:ae([he(),U()]).optional(),parallelToolCalls:he().optional(),user:d().optional(),reasoningEffort:me(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:U().optional(),store:he().optional(),metadata:ye(d().max(64),d().max(512)).optional(),prediction:ye(d(),bt()).optional(),serviceTier:me(["auto","flex","priority","default"]).optional(),strictJsonSchema:he().optional(),textVerbosity:me(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:me(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:me(["system","developer","remove"]).optional(),forceReasoning:he().optional()})));function QS({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 Cr({functionality:`tool choice type: ${s}`})}}}var XS=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:i,stopSequences:a,responseFormat:l,seed:c,tools:u,toolChoice:m,providerOptions:p}){var f,g,v,y,w;const _=[],h=(f=await Ar({provider:"openai",providerOptions:p,schema:YS}))!=null?f:{},T=h2(this.modelId),b=(g=h.forceReasoning)!=null?g:T.isReasoningModel;o!=null&&_.push({type:"unsupported",feature:"topK"});const{messages:k,warnings:S}=GS({prompt:e,systemMessageMode:(v=h.systemMessageMode)!=null?v:b?"developer":T.systemMessageMode});_.push(...S);const I=(y=h.strictJsonSchema)!=null?y:!0,x={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:i,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:I,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,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:k};b?((h.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,_.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,_.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,_.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),x.max_tokens!=null&&(x.max_completion_tokens==null&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&x.temperature!=null&&(x.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),h.serviceTier==="flex"&&!T.supportsFlexProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),h.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:j,toolChoice:M,toolWarnings:D}=QS({tools:u,toolChoice:m});return{args:{...x,tools:j,tool_choice:M},warnings:[..._,...D]}}async doGenerate(e){var t,r,n,o,s,i,a;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:m,rawValue:p}=await Vt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:l,failedResponseHandler:fr,successfulResponseHandler:tr(WS),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:qt(),toolName:_.function.name,input:_.function.arguments});for(const _ of(n=f.message.annotations)!=null?n:[])g.push({type:"source",sourceType:"url",id:qt(),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),((i=f.logprobs)==null?void 0:i.content)!=null&&(w.openai.logprobs=f.logprobs.content),{content:g,finishReason:{unified:g2(f.finish_reason),raw:(a=f.finish_reason)!=null?a:void 0},usage:m2(m.usage),request:{body:l},response:{...Vc(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 Vt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:n,failedResponseHandler:fr,successfulResponseHandler:Js(KS),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=[];let a={unified:"other",raw:void 0},l,c=!1,u=!1;const m={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,f){var g,v,y,w,_,h,T,b,k,S,I,x,j,M,D,A,O;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const H=p.value;if("error"in H){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:H.error});return}if(!c){const W=Vc(H);Object.values(W).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Vc(H)}))}H.usage!=null&&(l=H.usage,((g=H.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(m.openai.acceptedPredictionTokens=(v=H.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens),((y=H.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(m.openai.rejectedPredictionTokens=(w=H.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const Q=H.choices[0];if(Q?.finish_reason!=null&&(a={unified:g2(Q.finish_reason),raw:Q.finish_reason}),((_=Q?.logprobs)==null?void 0:_.content)!=null&&(m.openai.logprobs=Q.logprobs.content),Q?.delta==null)return;const Y=Q.delta;if(Y.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:Y.content})),Y.tool_calls!=null)for(const W of Y.tool_calls){const pe=W.index;if(i[pe]==null){if(W.type!=null&&W.type!=="function")throw new zi({data:W,message:"Expected 'function' type."});if(W.id==null)throw new zi({data:W,message:"Expected 'id' to be a string."});if(((h=W.function)==null?void 0:h.name)==null)throw new zi({data:W,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:W.id,toolName:W.function.name}),i[pe]={id:W.id,type:"function",function:{name:W.function.name,arguments:(T=W.function.arguments)!=null?T:""},hasFinished:!1};const P=i[pe];((b=P.function)==null?void 0:b.name)!=null&&((k=P.function)==null?void 0:k.arguments)!=null&&(P.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),qf(P.function.arguments)&&(f.enqueue({type:"tool-input-end",id:P.id}),f.enqueue({type:"tool-call",toolCallId:(S=P.id)!=null?S:qt(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const Z=i[pe];Z.hasFinished||(((I=W.function)==null?void 0:I.arguments)!=null&&(Z.function.arguments+=(j=(x=W.function)==null?void 0:x.arguments)!=null?j:""),f.enqueue({type:"tool-input-delta",id:Z.id,delta:(M=W.function.arguments)!=null?M:""}),((D=Z.function)==null?void 0:D.name)!=null&&((A=Z.function)==null?void 0:A.arguments)!=null&&qf(Z.function.arguments)&&(f.enqueue({type:"tool-input-end",id:Z.id}),f.enqueue({type:"tool-call",toolCallId:(O=Z.id)!=null?O:qt(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}if(Y.annotations!=null)for(const W of Y.annotations)f.enqueue({type:"source",sourceType:"url",id:qt(),url:W.url_citation.url,title:W.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:a,usage:m2(l),...m!=null?{providerMetadata:m}:{}})}})),request:{body:n},response:{headers:o}}}};function y2(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,i=(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:i,reasoning:void 0},raw:e}}function eI({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
|
|
68
|
+
`)}})}},um={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function CC({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new cm);if(o){const[i,a]=s.tee();s=i,o({stream:a})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:ra(r,um)})}function TC({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 SC(e){return e.type.startsWith("data-")}function Jl(e){return e.type.startsWith("tool-")}function IC(e){return e.type==="dynamic-tool"}function dm(e){return Jl(e)||IC(e)}function pm(e){return e.type.split("-").slice(1).join("-")}function xC({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function EC({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await n(async({state:c,write:u})=>{var m,p,f,g;function v(h){const b=c.message.parts.filter(dm).find(k=>k.toolCallId===h);if(b==null)throw new no({chunkType:"tool-invocation",chunkId:h,message:`No tool invocation found for tool call ID "${h}".`});return b}function y(h){var T;const b=c.message.parts.find(I=>Jl(I)&&I.toolCallId===h.toolCallId),k=h,S=b;b!=null?(b.state=h.state,S.input=k.input,S.output=k.output,S.errorText=k.errorText,S.rawInput=k.rawInput,S.preliminary=k.preliminary,h.title!==void 0&&(S.title=h.title),S.providerExecuted=(T=k.providerExecuted)!=null?T:b.providerExecuted,k.providerMetadata!=null&&(b.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:`tool-${h.toolName}`,toolCallId:h.toolCallId,state:h.state,title:h.title,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function w(h){var T,b;const k=c.message.parts.find(x=>x.type==="dynamic-tool"&&x.toolCallId===h.toolCallId),S=h,I=k;k!=null?(k.state=h.state,I.toolName=h.toolName,I.input=S.input,I.output=S.output,I.errorText=S.errorText,I.rawInput=(T=S.rawInput)!=null?T:I.rawInput,I.preliminary=S.preliminary,h.title!==void 0&&(I.title=h.title),I.providerExecuted=(b=S.providerExecuted)!=null?b:k.providerExecuted,S.providerMetadata!=null&&(k.callProviderMetadata=S.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:h.toolName,toolCallId:h.toolCallId,state:h.state,input:S.input,output:S.output,errorText:S.errorText,preliminary:S.preliminary,providerExecuted:S.providerExecuted,title:h.title,...S.providerMetadata!=null?{callProviderMetadata:S.providerMetadata}:{}})}async function _(h){if(h!=null){const T=c.message.metadata!=null?Xs(c.message.metadata,h):h;t!=null&&await kt({value:T,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=T}}switch(a.type){case"text-start":{const h={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeTextParts[a.id]=h,c.message.parts.push(h),u();break}case"text-delta":{const h=c.activeTextParts[a.id];if(h==null)throw new no({chunkType:"text-delta",chunkId:a.id,message:`Received text-delta for missing text part with ID "${a.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});h.text+=a.delta,h.providerMetadata=(m=a.providerMetadata)!=null?m:h.providerMetadata,u();break}case"text-end":{const h=c.activeTextParts[a.id];if(h==null)throw new no({chunkType:"text-end",chunkId:a.id,message:`Received text-end for missing text part with ID "${a.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});h.state="done",h.providerMetadata=(p=a.providerMetadata)!=null?p:h.providerMetadata,delete c.activeTextParts[a.id],u();break}case"reasoning-start":{const h={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};c.activeReasoningParts[a.id]=h,c.message.parts.push(h),u();break}case"reasoning-delta":{const h=c.activeReasoningParts[a.id];if(h==null)throw new no({chunkType:"reasoning-delta",chunkId:a.id,message:`Received reasoning-delta for missing reasoning part with ID "${a.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});h.text+=a.delta,h.providerMetadata=(f=a.providerMetadata)!=null?f:h.providerMetadata,u();break}case"reasoning-end":{const h=c.activeReasoningParts[a.id];if(h==null)throw new no({chunkType:"reasoning-end",chunkId:a.id,message:`Received reasoning-end for missing reasoning part with ID "${a.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});h.providerMetadata=(g=a.providerMetadata)!=null?g:h.providerMetadata,h.state="done",delete c.activeReasoningParts[a.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}}),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 h=c.message.parts.filter(Jl);c.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:h.length,dynamic:a.dynamic,title:a.title},a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted,title:a.title,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted,title:a.title,providerMetadata:a.providerMetadata}),u();break}case"tool-input-delta":{const h=c.partialToolCalls[a.toolCallId];if(h==null)throw new no({chunkType:"tool-input-delta",chunkId:a.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${a.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});h.text+=a.inputTextDelta;const{value:T}=await Ho(h.text);h.dynamic?w({toolCallId:a.toolCallId,toolName:h.toolName,state:"input-streaming",input:T,title:h.title}):y({toolCallId:a.toolCallId,toolName:h.toolName,state:"input-streaming",input:T,title:h.title}),u();break}case"tool-input-available":{a.dynamic?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:a.title}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata,title:a.title}),u(),s&&!a.providerExecuted&&await s({toolCall:a});break}case"tool-input-error":{const h=c.message.parts.filter(dm).find(b=>b.toolCallId===a.toolCallId);(h!=null?h.type==="dynamic-tool":!!a.dynamic)?w({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({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-approval-request":{const h=v(a.toolCallId);h.state="approval-requested",h.approval={id:a.approvalId},u();break}case"tool-output-denied":{const h=v(a.toolCallId);h.state="output-denied",u();break}case"tool-output-available":{const h=v(a.toolCallId);h.type==="dynamic-tool"?w({toolCallId:a.toolCallId,toolName:h.toolName,state:"output-available",input:h.input,output:a.output,preliminary:a.preliminary,providerExecuted:a.providerExecuted,title:h.title}):y({toolCallId:a.toolCallId,toolName:pm(h),state:"output-available",input:h.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary,title:h.title}),u();break}case"tool-output-error":{const h=v(a.toolCallId);h.type==="dynamic-tool"?w({toolCallId:a.toolCallId,toolName:h.toolName,state:"output-error",input:h.input,errorText:a.errorText,providerExecuted:a.providerExecuted,title:h.title}):y({toolCallId:a.toolCallId,toolName:pm(h),state:"output-error",input:h.input,rawInput:h.rawInput,errorText:a.errorText,providerExecuted:a.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":{a.messageId!=null&&(c.message.id=a.messageId),await _(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&u();break}case"finish":{a.finishReason!=null&&(c.finishReason=a.finishReason),await _(a.messageMetadata),a.messageMetadata!=null&&u();break}case"message-metadata":{await _(a.messageMetadata),a.messageMetadata!=null&&u();break}case"error":{o?.(new Error(a.errorText));break}default:if(SC(a)){if(r?.[a.type]!=null){const b=c.message.parts.findIndex(S=>"id"in S&&"data"in S&&S.id===a.id&&S.type===a.type),k=b>=0?b:c.message.parts.length;await kt({value:a.data,schema:r[a.type],context:{field:`message.parts[${k}].data`,entityName:a.type,entityId:a.id}})}const h=a;if(h.transient){i?.(h);break}const T=h.id!=null?c.message.parts.find(b=>h.type===b.type&&h.id===b.id):void 0;T!=null?T.data=h.data:c.message.parts.push(h),i?.(h),u()}}l.enqueue(a)})}}))}function $C({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let i=t?.[t.length-1];i?.role!=="assistant"?i=void 0:e=i.id;let a=!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"&&(a=!0),v.enqueue(g)}}));if(n==null&&r==null)return l;const c=xC({lastMessage:i?structuredClone(i):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===i?.id;await n({isAborted:a,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===i?.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 EC({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 RC({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let i=o.pipeThrough(new cm);if(s){const[a,l]=i.tee();i=a,s({stream:l})}lm({response:e,status:t,statusText:r,headers:Object.fromEntries(ra(n,um).entries()),stream:i.pipeThrough(new TextEncoderStream)})}function Jo(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;if(!n){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 PC({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 fm(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function NC(){let e=[],t=null,r=!1,n=fm();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=fm(),await n.promise,s();try{const{value:i,done:a}=await e[0].read();a?(e.shift(),e.length===0&&r?t?.close():await s()):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 MC({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:i,repairToolCall:a,experimental_context:l,generateId:c,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f}){let g=null;const v=new ReadableStream({start(S){g=S}}),y=new Set,w=new Map,_=new Map;let h=!1,T;function b(){h&&y.size===0&&(T!=null&&g.enqueue(T),g.close())}const k=new TransformStream({async transform(S,I){const x=S.type;switch(x){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":{I.enqueue(S);break}case"file":{I.enqueue({type:"file",file:new dC({data:S.data,mediaType:S.mediaType}),...S.providerMetadata!=null?{providerMetadata:S.providerMetadata}:{}});break}case"finish":{T={type:"finish",finishReason:S.finishReason.unified,rawFinishReason:S.finishReason.raw,usage:Z0(S.usage),providerMetadata:S.providerMetadata};break}case"tool-approval-request":{const j=_.get(S.toolCallId);if(j==null){g.enqueue({type:"error",error:new jl({toolCallId:S.toolCallId,approvalId:S.approvalId})});break}I.enqueue({type:"tool-approval-request",approvalId:S.approvalId,toolCall:j});break}case"tool-call":{try{const j=await X0({toolCall:S,tools:e,repairToolCall:a,system:o,messages:s});if(_.set(j.toolCallId,j),I.enqueue(j),j.invalid){g.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:hl(j.error),dynamic:!0,title:j.title});break}const M=e?.[j.toolName];if(M==null)break;if(M.onInputAvailable!=null&&await M.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:s,abortSignal:i,experimental_context:l}),await Q0({tool:M,toolCall:j,messages:s,experimental_context:l})){g.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:j});break}if(w.set(j.toolCallId,j.input),M.execute!=null&&j.providerExecuted!==!0){const D=c();y.add(D),Zl({toolCall:j,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:i,experimental_context:l,stepNumber:u,model:m,onToolCallStart:p,onToolCallFinish:f,onPreliminaryToolResult:A=>{g.enqueue(A)}}).then(A=>{g.enqueue(A)}).catch(A=>{g.enqueue({type:"error",error:A})}).finally(()=>{y.delete(D),b()})}}catch(j){g.enqueue({type:"error",error:j})}break}case"tool-result":{const j=S.toolName;S.isError?g.enqueue({type:"tool-error",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),providerExecuted:!0,error:S.result,dynamic:S.dynamic}):I.enqueue({type:"tool-result",toolCallId:S.toolCallId,toolName:j,input:w.get(S.toolCallId),output:S.result,providerExecuted:!0,dynamic:S.dynamic});break}default:{const j=x;throw new Error(`Unhandled chunk type: ${j}`)}}},flush(){h=!0,b()}});return new ReadableStream({async start(S){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){}})),v.pipeTo(new WritableStream({write(I){S.enqueue(I)},close(){S.close()}}))])}})}var OC=Oo({prefix:"aitxt",size:24});function Gl({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:i,abortSignal:a,timeout:l,headers:c,stopWhen:u=Bl(1),experimental_output:m,output:p=m,experimental_telemetry:f,prepareStep:g,providerOptions:v,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:_,experimental_transform:h,experimental_download:T,includeRawChunks:b=!1,onChunk:k,onError:S=({error:Z})=>{console.error(Z)},onFinish:I,onAbort:x,onStepFinish:j,experimental_onStart:M,experimental_onStepStart:D,experimental_onToolCallStart:A,experimental_onToolCallFinish:O,experimental_context:H,experimental_include:Q,_internal:{now:Y=ea,generateId:W=OC}={},...pe}){const Z=zl(l),P=I0(l),B=qk(l),F=P!=null?new AbortController:void 0,E=B!=null?new AbortController:void 0;return new qC({model:Ys(e),telemetry:f,headers:c,settings:pe,maxRetries:i,abortSignal:om(a,Z!=null?AbortSignal.timeout(Z):void 0,F?.signal,E?.signal),stepTimeoutMs:P,stepAbortController:F,chunkTimeoutMs:B,chunkAbortController:E,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:Rn(h),activeTools:w,repairToolCall:_,stopConditions:Rn(u),output:p,providerOptions:v,prepareStep:g,includeRawChunks:b,timeout:l,stopWhen:u,originalAbortSignal:a,onChunk:k,onError:S,onFinish:I,onAbort:x,onStepFinish:j,onStart:M,onStepStart:D,onToolCallStart:A,onToolCallFinish:O,now:Y,generateId:W,experimental_context:H,download:T,include:Q})}function AC(e){let t,r="",n="",o,s="";function i({controller:a,partialOutput:l=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(a,l){var c;if(a.type==="finish-step"&&n.length>0&&i({controller:l}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){l.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){l.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){l.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&i({controller:l}),l.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text,o=(c=a.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const m=JSON.stringify(u.partial);m!==s&&(i({controller:l,partialOutput:u.partial}),s=m)}}})}var qC=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:i,stepAbortController:a,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:m,messages:p,tools:f,toolChoice:g,transforms:v,activeTools:y,repairToolCall:w,stopConditions:_,output:h,providerOptions:T,prepareStep:b,includeRawChunks:k,now:S,generateId:I,timeout:x,stopWhen:j,originalAbortSignal:M,onChunk:D,onError:A,onFinish:O,onAbort:H,onStepFinish:Q,onStart:Y,onStepStart:W,onToolCallStart:pe,onToolCallFinish:Z,experimental_context:P,download:B,include:F}){this._totalUsage=new Mo,this._finishReason=new Mo,this._rawFinishReason=new Mo,this._steps=new Mo,this.outputSpecification=h,this.includeRawChunks=k,this.tools=f;const N=V0()(t?.integrations);let L,G=[];const ee=[];let se,ke,z,V={},K=[];const X=[],le=new Map;let Te,Fe={},tt={};const ut=new TransformStream({async transform(pt,Ee){var rt,Se,Je,wr;Ee.enqueue(pt);const{part:te}=pt;if((te.type==="text-delta"||te.type==="reasoning-delta"||te.type==="source"||te.type==="tool-call"||te.type==="tool-result"||te.type==="tool-input-start"||te.type==="tool-input-delta"||te.type==="raw")&&await D?.({chunk:te}),te.type==="error"&&await A({error:j0(te.error)}),te.type==="text-start"&&(Fe[te.id]={type:"text",text:"",providerMetadata:te.providerMetadata},G.push(Fe[te.id])),te.type==="text-delta"){const Ge=Fe[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`text part ${te.id} not found`},partialOutput:void 0});return}Ge.text+=te.text,Ge.providerMetadata=(rt=te.providerMetadata)!=null?rt:Ge.providerMetadata}if(te.type==="text-end"){const Ge=Fe[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`text part ${te.id} not found`},partialOutput:void 0});return}Ge.providerMetadata=(Se=te.providerMetadata)!=null?Se:Ge.providerMetadata,delete Fe[te.id]}if(te.type==="reasoning-start"&&(tt[te.id]={type:"reasoning",text:"",providerMetadata:te.providerMetadata},G.push(tt[te.id])),te.type==="reasoning-delta"){const Ge=tt[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`reasoning part ${te.id} not found`},partialOutput:void 0});return}Ge.text+=te.text,Ge.providerMetadata=(Je=te.providerMetadata)!=null?Je:Ge.providerMetadata}if(te.type==="reasoning-end"){const Ge=tt[te.id];if(Ge==null){Ee.enqueue({part:{type:"error",error:`reasoning part ${te.id} not found`},partialOutput:void 0});return}Ge.providerMetadata=(wr=te.providerMetadata)!=null?wr:Ge.providerMetadata,delete tt[te.id]}if(te.type==="file"&&G.push({type:"file",file:te.file,...te.providerMetadata!=null?{providerMetadata:te.providerMetadata}:{}}),te.type==="source"&&G.push(te),te.type==="tool-call"&&G.push(te),te.type==="tool-result"&&!te.preliminary&&G.push(te),te.type==="tool-approval-request"&&G.push(te),te.type==="tool-error"&&G.push(te),te.type==="start-step"&&(G=[],tt={},Fe={},V=te.request,K=te.warnings),te.type==="finish-step"){const Ge=await Hl({content:G,tools:f}),br=new rm({stepNumber:X.length,model:sr,...hn,experimental_context:P,content:G,finishReason:te.finishReason,rawFinishReason:te.rawFinishReason,usage:te.usage,warnings:K,request:V,response:{...te.response,messages:[...ee,...Ge]},providerMetadata:te.providerMetadata});await dr({event:br,callbacks:[Q,N.onStepFinish]}),Dl({warnings:K,provider:sr.provider,model:sr.modelId}),X.push(br),ee.push(...Ge),L.resolve()}te.type==="finish"&&(z=te.totalUsage,se=te.finishReason,ke=te.rawFinishReason)},async flush(pt){try{if(X.length===0){const Je=s?.aborted?s.reason:new a0({message:"No output generated. Check the stream for errors."});dt._finishReason.reject(Je),dt._rawFinishReason.reject(Je),dt._totalUsage.reject(Je),dt._steps.reject(Je);return}const Ee=se??"other",rt=z??Vl();dt._finishReason.resolve(Ee),dt._rawFinishReason.resolve(ke),dt._totalUsage.resolve(rt),dt._steps.resolve(X);const Se=X[X.length-1];await dr({event:{stepNumber:Se.stepNumber,model:Se.model,functionId:Se.functionId,metadata:Se.metadata,experimental_context:Se.experimental_context,finishReason:Se.finishReason,rawFinishReason:Se.rawFinishReason,totalUsage:rt,usage:Se.usage,content:Se.content,text:Se.text,reasoningText:Se.reasoningText,reasoning:Se.reasoning,files:Se.files,sources:Se.sources,toolCalls:Se.toolCalls,staticToolCalls:Se.staticToolCalls,dynamicToolCalls:Se.dynamicToolCalls,toolResults:Se.toolResults,staticToolResults:Se.staticToolResults,dynamicToolResults:Se.dynamicToolResults,request:Se.request,response:Se.response,warnings:Se.warnings,providerMetadata:Se.providerMetadata,steps:X},callbacks:[O,N.onFinish]}),Te.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":Ee,"ai.response.text":{output:()=>Se.text},"ai.response.reasoning":{output:()=>Se.reasoningText},"ai.response.toolCalls":{output:()=>{var Je;return(Je=Se.toolCalls)!=null&&Je.length?JSON.stringify(Se.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Se.providerMetadata),"ai.usage.inputTokens":rt.inputTokens,"ai.usage.outputTokens":rt.outputTokens,"ai.usage.totalTokens":rt.totalTokens,"ai.usage.reasoningTokens":rt.reasoningTokens,"ai.usage.cachedInputTokens":rt.cachedInputTokens}}))}catch(Ee){pt.error(Ee)}finally{Te.end()}}}),Ye=NC();this.addStream=Ye.addStream,this.closeStream=Ye.close;const $=Ye.stream.getReader();let re=new ReadableStream({async start(pt){pt.enqueue({type:"start"})},async pull(pt){function Ee(){H?.({steps:X}),pt.enqueue({type:"abort",...s?.reason!==void 0?{reason:yn(s.reason)}:{}}),pt.close()}try{const{done:rt,value:Se}=await $.read();if(rt){pt.close();return}if(s?.aborted){Ee();return}pt.enqueue(Se)}catch(rt){Cn(rt)&&s?.aborted?Ee():pt.error(rt)}},cancel(pt){return Ye.stream.cancel(pt)}});for(const pt of v)re=re.pipeThrough(pt({tools:f,stopStream(){Ye.terminate()}}));this.baseStream=re.pipeThrough(AC(h??ta())).pipeThrough(ut);const{maxRetries:Ae,retry:yt}=J0({maxRetries:o,abortSignal:s}),Dt=D0(t),Be=Fl(n),Br=U0({model:e,telemetry:t,headers:r,settings:{...Be,maxRetries:Ae}}),dt=this,sr={provider:e.provider,modelId:e.modelId},hn={functionId:t?.functionId,metadata:t?.metadata};Bo({name:"ai.streamText",attributes:Er({telemetry:t,attributes:{...Zo({operationId:"ai.streamText",telemetry:t}),...Br,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:m,messages:p})}}}),tracer:Dt,endWhenDone:!1,fn:async pt=>{Te=pt;const Ee=await L0({system:u,prompt:m,messages:p});await dr({event:{model:sr,system:u,prompt:m,messages:p,tools:f,toolChoice:g,activeTools:y,maxOutputTokens:Be.maxOutputTokens,temperature:Be.temperature,topP:Be.topP,topK:Be.topK,presencePenalty:Be.presencePenalty,frequencyPenalty:Be.frequencyPenalty,stopSequences:Be.stopSequences,seed:Be.seed,maxRetries:Ae,timeout:x,headers:r,providerOptions:T,stopWhen:j,output:h,abortSignal:M,include:F,...hn,experimental_context:P},callbacks:[Y,N.onStart]});const rt=Ee.messages,Se=[],{approvedToolApprovals:Je,deniedToolApprovals:wr}=G0({messages:rt});if(wr.length>0||Je.length>0){const Ge=[...Je,...wr].filter(ft=>ft.toolCall.providerExecuted),br=Je.filter(ft=>!ft.toolCall.providerExecuted),nt=wr.filter(ft=>!ft.toolCall.providerExecuted),St=wr.filter(ft=>ft.toolCall.providerExecuted);let Ce;const Ot=new ReadableStream({start(ft){Ce=ft}});dt.addStream(Ot);try{for(const It of[...nt,...St])Ce?.enqueue({type:"tool-output-denied",toolCallId:It.toolCall.toolCallId,toolName:It.toolCall.toolName});const ft=[];if(await Promise.all(br.map(async It=>{const lt=await Zl({toolCall:It.toolCall,tools:f,tracer:Dt,telemetry:t,messages:rt,abortSignal:s,experimental_context:P,stepNumber:X.length,model:sr,onToolCallStart:[pe,N.onToolCallStart],onToolCallFinish:[Z,N.onToolCallFinish],onPreliminaryToolResult:Hr=>{Ce?.enqueue(Hr)}});lt!=null&&(Ce?.enqueue(lt),ft.push(lt))})),Ge.length>0&&Se.push({role:"tool",content:Ge.map(It=>({type:"tool-approval-response",approvalId:It.approvalResponse.approvalId,approved:It.approvalResponse.approved,reason:It.approvalResponse.reason,providerExecuted:!0}))}),ft.length>0||nt.length>0){const It=[];for(const lt of ft)It.push({type:"tool-result",toolCallId:lt.toolCallId,toolName:lt.toolName,output:await Fo({toolCallId:lt.toolCallId,input:lt.input,tool:f?.[lt.toolName],output:lt.type==="tool-result"?lt.output:lt.error,errorMode:lt.type==="tool-error"?"text":"none"})});for(const lt of nt)It.push({type:"tool-result",toolCallId:lt.toolCall.toolCallId,toolName:lt.toolCall.toolName,output:{type:"execution-denied",reason:lt.approvalResponse.reason}});Se.push({role:"tool",content:It})}}finally{Ce?.close()}}ee.push(...Se);async function te({currentStep:Ge,responseMessages:br,usage:nt}){var St,Ce,Ot,ft,It,lt,Hr,wo,Oi;const Ai=dt.includeRawChunks,_s=i!=null?setTimeout(()=>a.abort(),i):void 0;let ar;function vs(){l!=null&&(ar!=null&&clearTimeout(ar),ar=setTimeout(()=>c.abort(),l))}function qi(){ar!=null&&(clearTimeout(ar),ar=void 0)}function ws(){_s!=null&&clearTimeout(_s)}try{L=new Mo;const mn=[...rt,...br],_t=await b?.({model:e,steps:X,stepNumber:X.length,messages:mn,experimental_context:P}),Rr=Ys((St=_t?.model)!=null?St:e),bs={provider:Rr.provider,modelId:Rr.modelId},Ne=await R0({prompt:{system:(Ce=_t?.system)!=null?Ce:Ee.system,messages:(Ot=_t?.messages)!=null?Ot:mn},supportedUrls:await Rr.supportedUrls,download:B}),At=(ft=_t?.activeTools)!=null?ft:y,{toolChoice:gn,tools:Jr}=await M0({tools:f,toolChoice:(It=_t?.toolChoice)!=null?It:g,activeTools:At});P=(lt=_t?.experimental_context)!=null?lt:P;const Li=(Hr=_t?.messages)!=null?Hr:mn,ji=(wo=_t?.system)!=null?wo:Ee.system,ks=Xs(T,_t?.providerOptions);await dr({event:{stepNumber:X.length,model:bs,system:ji,messages:Li,tools:f,toolChoice:gn,activeTools:At,steps:[...X],providerOptions:ks,timeout:x,headers:r,stopWhen:j,output:h,abortSignal:M,include:F,...hn,experimental_context:P},callbacks:[W,N.onStepStart]});const{result:{stream:Ui,response:Cs,request:bo},doStreamSpan:ct,startTimestampMs:Gr}=await yt(()=>Bo({name:"ai.streamText.doStream",attributes:Er({telemetry:t,attributes:{...Zo({operationId:"ai.streamText.doStream",telemetry:t}),...Br,"ai.model.provider":Rr.provider,"ai.model.id":Rr.modelId,"ai.prompt.messages":{input:()=>F0(Ne)},"ai.prompt.tools":{input:()=>Jr?.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>gn!=null?JSON.stringify(gn):void 0},"gen_ai.system":Rr.provider,"gen_ai.request.model":Rr.modelId,"gen_ai.request.frequency_penalty":Be.frequencyPenalty,"gen_ai.request.max_tokens":Be.maxOutputTokens,"gen_ai.request.presence_penalty":Be.presencePenalty,"gen_ai.request.stop_sequences":Be.stopSequences,"gen_ai.request.temperature":Be.temperature,"gen_ai.request.top_k":Be.topK,"gen_ai.request.top_p":Be.topP}}),tracer:Dt,endWhenDone:!1,fn:async we=>({startTimestampMs:S(),doStreamSpan:we,result:await Rr.doStream({...Be,tools:Jr,toolChoice:gn,responseFormat:await h?.responseFormat,prompt:Ne,providerOptions:ks,abortSignal:s,headers:r,includeRawChunks:Ai})})})),Di=MC({tools:f,generatorStream:Ui,tracer:Dt,telemetry:t,system:u,messages:mn,repairToolCall:w,abortSignal:s,experimental_context:P,generateId:I,stepNumber:X.length,model:bs,onToolCallStart:[pe,N.onToolCallStart],onToolCallFinish:[Z,N.onToolCallFinish]}),zE=(Oi=F?.requestBody)==null||Oi?bo??{}:{...bo,body:void 0},Ts=[],Ss=[];let Gu;const Wu={};let ko="other",Ku,kr=Vl(),Yu,nv=!0,Pr={id:I(),timestamp:new Date,modelId:sr.modelId},ov="";dt.addStream(Di.pipeThrough(new TransformStream({async transform(we,Nt){var Is,xs,zi,ht,Nr;if(vs(),we.type==="stream-start"){Gu=we.warnings;return}if(nv){const mt=S()-Gr;nv=!1,ct.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":mt}),ct.setAttributes({"ai.response.msToFirstChunk":mt}),Nt.enqueue({type:"start-step",request:zE,warnings:Gu??[]})}const Qu=we.type;switch(Qu){case"tool-approval-request":case"text-start":case"text-end":{Nt.enqueue(we);break}case"text-delta":{we.delta.length>0&&(Nt.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),ov+=we.delta);break}case"reasoning-start":case"reasoning-end":{Nt.enqueue(we);break}case"reasoning-delta":{Nt.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{Nt.enqueue(we),Ts.push(we);break}case"tool-result":{Nt.enqueue(we),we.preliminary||Ss.push(we);break}case"tool-error":{Nt.enqueue(we),Ss.push(we);break}case"response-metadata":{Pr={id:(Is=we.id)!=null?Is:Pr.id,timestamp:(xs=we.timestamp)!=null?xs:Pr.timestamp,modelId:(zi=we.modelId)!=null?zi:Pr.modelId};break}case"finish":{kr=we.usage,ko=we.finishReason,Ku=we.rawFinishReason,Yu=we.providerMetadata;const mt=S()-Gr;ct.addEvent("ai.stream.finish"),ct.setAttributes({"ai.response.msToFinish":mt,"ai.response.avgOutputTokensPerSecond":1e3*((ht=kr.outputTokens)!=null?ht:0)/mt});break}case"file":{Nt.enqueue(we);break}case"source":{Nt.enqueue(we);break}case"tool-input-start":{Wu[we.id]=we.toolName;const mt=f?.[we.toolName];mt?.onInputStart!=null&&await mt.onInputStart({toolCallId:we.id,messages:mn,abortSignal:s,experimental_context:P}),Nt.enqueue({...we,dynamic:(Nr=we.dynamic)!=null?Nr:mt?.type==="dynamic",title:mt?.title});break}case"tool-input-end":{delete Wu[we.id],Nt.enqueue(we);break}case"tool-input-delta":{const mt=Wu[we.id],Xu=f?.[mt];Xu?.onInputDelta!=null&&await Xu.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:mn,abortSignal:s,experimental_context:P}),Nt.enqueue(we);break}case"error":{Nt.enqueue(we),ko="error";break}case"raw":{Ai&&Nt.enqueue(we);break}default:{const mt=Qu;throw new Error(`Unknown chunk type: ${mt}`)}}},async flush(we){const Nt=Ts.length>0?JSON.stringify(Ts):void 0;try{ct.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":ko,"ai.response.text":{output:()=>ov},"ai.response.reasoning":{output:()=>{const ht=G.filter(Nr=>Nr.type==="reasoning");return ht.length>0?ht.map(Nr=>Nr.text).join(`
|
|
69
|
+
`):void 0}},"ai.response.toolCalls":{output:()=>Nt},"ai.response.id":Pr.id,"ai.response.model":Pr.modelId,"ai.response.timestamp":Pr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Yu),"ai.usage.inputTokens":kr.inputTokens,"ai.usage.outputTokens":kr.outputTokens,"ai.usage.totalTokens":kr.totalTokens,"ai.usage.reasoningTokens":kr.reasoningTokens,"ai.usage.cachedInputTokens":kr.cachedInputTokens,"gen_ai.response.finish_reasons":[ko],"gen_ai.response.id":Pr.id,"gen_ai.response.model":Pr.modelId,"gen_ai.usage.input_tokens":kr.inputTokens,"gen_ai.usage.output_tokens":kr.outputTokens}}))}catch{}finally{ct.end()}we.enqueue({type:"finish-step",finishReason:ko,rawFinishReason:Ku,usage:kr,providerMetadata:Yu,response:{...Pr,headers:Cs?.headers}});const Is=B0(nt,kr);await L.promise;const xs=Ts.filter(ht=>ht.providerExecuted!==!0),zi=Ss.filter(ht=>ht.providerExecuted!==!0);for(const ht of Ts){if(ht.providerExecuted!==!0)continue;const Nr=f?.[ht.toolName];Nr?.type==="provider"&&Nr.supportsDeferredResults&&(Ss.some(mt=>(mt.type==="tool-result"||mt.type==="tool-error")&&mt.toolCallId===ht.toolCallId)||le.set(ht.toolCallId,{toolName:ht.toolName}))}for(const ht of Ss)(ht.type==="tool-result"||ht.type==="tool-error")&&le.delete(ht.toolCallId);if(ws(),qi(),(xs.length>0&&zi.length===xs.length||le.size>0)&&!await nm({stopConditions:_,steps:X})){br.push(...await Hl({content:X[X.length-1].content,tools:f}));try{await te({currentStep:Ge+1,responseMessages:br,usage:Is})}catch(ht){we.enqueue({type:"error",error:ht}),dt.closeStream()}}else we.enqueue({type:"finish",finishReason:ko,rawFinishReason:Ku,totalUsage:Is}),dt.closeStream()}})))}finally{ws(),qi()}}await te({currentStep:0,responseMessages:Se,usage:Vl()})}}).catch(pt=>{dt.addStream(new ReadableStream({start(Ee){Ee.enqueue({type:"error",error:pt}),Ee.close()}})),dt.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 Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Jo(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await PC({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 Jo(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 Cr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Jo(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:ta()).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:i=!0,sendFinish:a=!0,onError:l=yn}={}){const c=t!=null?TC({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}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});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":{i&&f.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&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 Jo($C({stream:m,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}={}){RC({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){kC({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 CC({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 bC({textStream:this.textStream,...e})}};Oo({prefix:"aiobj",size:24}),Oo({prefix:"aiobj",size:24});let Wl;Wl=globalThis.crypto;async function LC(e){return(await Wl).getRandomValues(new Uint8Array(e))}async function jC(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await LC(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function UC(e){return await jC(e)}async function DC(e){const t=await(await Wl).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function hm(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await UC(e),r=await DC(t);return{code_verifier:t,code_challenge:r}}var zC="AI_MCPClientError",mm=`vercel.ai.error.${zC}`,FC=Symbol.for(mm),gm,ym,De=class extends(ym=ge,gm=FC,ym){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[gm]=!0,this.data=n,this.code=o}static isInstance(e){return ge.hasMarker(e,mm)}},oo="2025-06-18",VC=[oo,"2025-03-26","2024-11-05"],ZC=ce(ye(d(),$e())),BC=at({name:d(),version:d()}),na=at({_meta:ce(C({}).loose())}),Lr=na,_m=C({method:d(),params:ce(na)}),vm=C({applyDefaults:ce(he())}).loose(),HC=at({experimental:ce(C({}).loose()),logging:ce(C({}).loose()),prompts:ce(at({listChanged:ce(he())})),resources:ce(at({subscribe:ce(he()),listChanged:ce(he())})),tools:ce(at({listChanged:ce(he())})),elicitation:ce(vm)});C({elicitation:ce(vm)}).loose();var JC=Lr.extend({protocolVersion:d(),capabilities:HC,serverInfo:BC,instructions:ce(d())}),Kl=Lr.extend({nextCursor:ce(d())}),GC=C({name:d(),title:ce(d()),description:ce(d()),inputSchema:C({type:R("object"),properties:ce(C({}).loose())}).loose(),outputSchema:ce(C({}).loose()),annotations:ce(C({title:ce(d())}).loose()),_meta:ZC}).loose(),WC=Kl.extend({tools:q(GC)}),wm=C({type:R("text"),text:d()}).loose(),bm=C({type:R("image"),data:qp(),mimeType:d()}).loose(),KC=C({uri:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d()),size:ce(U())}).loose(),YC=Kl.extend({resources:q(KC)}),km=C({uri:d(),name:ce(d()),title:ce(d()),mimeType:ce(d())}).loose(),Cm=km.extend({text:d()}),Tm=km.extend({blob:qp()}),Sm=C({type:R("resource"),resource:ae([Cm,Tm])}).loose(),QC=Lr.extend({content:q(ae([wm,bm,Sm])),structuredContent:ce($e()),isError:he().default(!1).optional()}).or(Lr.extend({toolResult:$e()})),XC=C({uriTemplate:d(),name:d(),title:ce(d()),description:ce(d()),mimeType:ce(d())}).loose(),e5=Lr.extend({resourceTemplates:q(XC)}),t5=Lr.extend({contents:q(ae([Cm,Tm]))}),r5=C({name:d(),description:ce(d()),required:ce(he())}).loose(),n5=C({name:d(),title:ce(d()),description:ce(d()),arguments:ce(q(r5))}).loose(),o5=Kl.extend({prompts:q(n5)}),s5=C({role:ae([R("user"),R("assistant")]),content:ae([wm,bm,Sm])}).loose(),a5=Lr.extend({description:ce(d()),messages:q(s5)}),i5=na.extend({message:d(),requestedSchema:$e()}),Im=_m.extend({method:R("elicitation/create"),params:i5}),l5=Lr.extend({action:ae([R("accept"),R("decline"),R("cancel")]),content:ce(ye(d(),$e()))}),oa="2.0",c5=C({jsonrpc:R(oa),id:ae([d(),U().int()])}).merge(_m).strict(),u5=C({jsonrpc:R(oa),id:ae([d(),U().int()]),result:Lr}).strict(),d5=C({jsonrpc:R(oa),id:ae([d(),U().int()]),error:C({code:U().int(),message:d(),data:ce($e())})}).strict(),p5=C({jsonrpc:R(oa)}).merge(C({method:d(),params:ce(na)})).strict(),Go=ae([c5,p5,u5,d5]),xm=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Em=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:U().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),Bt=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Hp.custom,message:"URL must be parseable",fatal:!0}),Bd}).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"}),f5=C({resource:d().url(),authorization_servers:q(Bt).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:he().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:he().optional()}).passthrough(),$m=C({issuer:d(),authorization_endpoint:Bt,token_endpoint:Bt,registration_endpoint:Bt.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(),h5=C({issuer:d(),authorization_endpoint:Bt,token_endpoint:Bt,userinfo_endpoint:Bt.optional(),jwks_uri:Bt,registration_endpoint:Bt.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(),m5=h5.merge($m.pick({code_challenge_methods_supported:!0})),g5=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:U().optional(),client_secret_expires_at:U().optional()}).strip(),y5=C({redirect_uris:q(Bt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Bt.optional(),logo_uri:Bt.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:Bt.optional(),policy_uri:d().optional(),jwks_uri:Bt.optional(),jwks:bt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),_5=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),v5=y5.merge(g5),w5="AI_MCPClientOAuthError",Rm=`vercel.ai.error.${w5}`,b5=Symbol.for(Rm),Pm,Nm,Wo=class extends(Nm=ge,Pm=b5,Nm){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[Pm]=!0}static isInstance(e){return ge.hasMarker(e,Rm)}},so=class extends Wo{};so.errorCode="server_error";var sa=class extends Wo{};sa.errorCode="invalid_client";var aa=class extends Wo{};aa.errorCode="invalid_grant";var ia=class extends Wo{};ia.errorCode="unauthorized_client";var k5={[so.errorCode]:so,[sa.errorCode]:sa,[aa.errorCode]:aa,[ia.errorCode]:ia};function C5(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function T5({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 la=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function ca(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 S5(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Yl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Yl(e,void 0,r):void 0;throw n}}async function Mm(e,t,r=fetch){return await Yl(e,{"MCP-Protocol-Version":t},r)}function I5(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function x5(e,t,r,n){var o,s;const i=new URL(e),a=(o=n?.protocolVersion)!=null?o:oo;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=S5(t,i.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:i),l.search=i.search}let c=await Mm(l,a,r);if(!n?.metadataUrl&&I5(c,i.pathname)){const u=new URL(`/.well-known/${t}`,i);c=await Mm(u,a,r)}return c}async function E5(e,t,r=fetch){const n=await x5(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 f5.parse(await n.json())}function $5(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 R5(e,{fetchFn:t=fetch,protocolVersion:r=oo}={}){var n;const o={"MCP-Protocol-Version":r},s=$5(e);for(const{url:i,type:a}of s){const l=await Yl(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 $m.parse(await l.json());{const c=m5.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 P5(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 hm(),m=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",a),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"),i&&c.searchParams.set("resource",i.href),{authorizationUrl:c,codeVerifier:m}}function Om(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 Am(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":N5(o,s,r);return;case"client_secret_post":M5(o,s,n);return;case"none":O5(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function N5(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 M5(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function O5(e,t){t.set("client_id",e)}async function Ql(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=_5.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=k5[o]||so;return new a({message:s||"",cause:i})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new so({message:o})}}async function A5(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:i,addClientAuthentication:a,fetchFn:l}){var c;const u="authorization_code",m=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const 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(a)a(p,f,e,t);else{const v=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=Om(r,v);Am(y,r,p,f)}i&&f.set("resource",i.href);const g=await(l??fetch)(m,{method:"POST",headers:p,body:f});if(!g.ok)throw await Ql(g);return Em.parse(await g.json())}async function q5(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",Accept:"application/json"}),m=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,m,e,t);else{const f=(a=t?.token_endpoint_auth_methods_supported)!=null?a:[],g=Om(r,f);Am(g,r,u,m)}o&&m.set("resource",o.href);const p=await(i??fetch)(c,{method:"POST",headers:u,body:m});if(!p.ok)throw await Ql(p);return Em.parse({refresh_token:n,...await p.json()})}async function L5(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Ql(s);return v5.parse(await s.json())}async function ua(e,t){var r,n;try{return await Xl(e,t)}catch(o){if(o instanceof sa||o instanceof ia)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Xl(e,t);if(o instanceof aa)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Xl(e,t);throw o}}async function j5(e,t,r){const n=C5(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!T5({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 Xl(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await E5(t,{resourceMetadataUrl:o},s),i.authorization_servers&&i.authorization_servers.length>0&&(a=i.authorization_servers[0])}catch{}a||(a=t);const l=await j5(t,e,i),c=await R5(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 L5(a,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(v),u=v}if(r!==void 0){const v=await e.codeVerifier(),y=await A5(a,{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 q5(a,{metadata:c,clientInformation:u,refreshToken:m.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Wo)||v instanceof so))throw v}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:g}=await P5(a,{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 U5=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":oo};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return nn(t,`ai-sdk/${xm}`,Ao())}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=ca(u);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new la;return(s=this.onerror)==null||s.call(this,v),t(v)}}catch(g){return(i=this.onerror)==null||i.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 De({message:g});return(a=this.onerror)==null||a.call(this,v),t(v)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).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 De({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:h,data:T}=_;if(h==="endpoint"){if(this.endpoint=new URL(T,this.url),this.endpoint.origin!==this.url.origin)throw new De({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 b=Go.parse(JSON.parse(T));(g=this.onmessage)==null||g.call(this,b)}catch(b){const k=new De({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(v=this.onerror)==null||v.call(this,k)}}}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 De({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,i,a,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal},m=await fetch(t,u);if(m.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=ca(m);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const f=new la;(s=this.onerror)==null||s.call(this,f);return}}catch(p){(i=this.onerror)==null||i.call(this,p);return}return r(!0)}if(!m.ok){const p=await m.text().catch(()=>null),f=new De({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${m.status}): ${p}`});(a=this.onerror)==null||a.call(this,f);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},D5=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":oo};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 nn(t,`ai-sdk/${xm}`,Ao())}async start(){if(this.abortController)throw new De({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,i,a,l,c;try{const m={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal},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=ca(p);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new la}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 De({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=>Go.parse(h)):[Go.parse(w)];for(const h of _)(i=this.onmessage)==null||i.call(this,h);return}if(v.includes("text/event-stream")){if(!p.body){const T=new De({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(a=this.onerror)==null||a.call(this,T),T}const _=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).getReader();(async()=>{var T,b,k;try{for(;;){const{done:S,value:I}=await _.read();if(S)return;const{event:x,data:j}=I;if(x==="message")try{const M=Go.parse(JSON.parse(j));(T=this.onmessage)==null||T.call(this,M)}catch(M){const D=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:M});(b=this.onerror)==null||b.call(this,D)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const y=new De({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 De({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=ca(c);try{if(await ua(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const v=new la;(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 De({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 Kn).getReader(),f=async()=>{var g,v,y,w;try{for(;;){const{done:_,value:h}=await p.read();if(_)return;const{event:T,data:b,id:k}=h;if(k&&(this.lastInboundEventId=k),T==="message")try{const S=Go.parse(JSON.parse(b));(g=this.onmessage)==null||g.call(this,S)}catch(S){const I=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:S});(v=this.onerror)==null||v.call(this,I)}}}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;(i=this.onerror)==null||i.call(this,l),(a=this.abortController)!=null&&a.signal.aborted||this.scheduleInboundSseReconnection()}}};function z5(e){switch(e.type){case"sse":return new U5(e);case"http":return new D5(e);default:throw new De({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function F5(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var V5="1.0.0";function qm({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 Z5(e){const t=new B5(e);return await t.init(),t}var B5=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=V5,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},F5(e)?this.transport=e:this.transport=z5(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 De({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:oo,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:JC});if(e===void 0)throw new De({message:"Server sent invalid initialize result"});if(!VC.includes(e.protocolVersion))throw new De({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 De({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new De({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new De({message:"Server does not support prompts"});break;default:throw new De({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new De({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 De({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 De({message:"Failed to parse server response",cause:u});o(m)}}),this.transport.send(a).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:WC,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:QC,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:YC,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:t5,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:e5,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:o5,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:a5,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:i,description:a,inputSchema:l,annotations:c,_meta:u}of e.tools){const m=i??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"?Df({description:a,title:m,inputSchema:ro({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:g,toModelOutput:qm}):{description:a,title:m,inputSchema:t[s].inputSchema,...f!=null?{outputSchema:f}:{},execute:g,toModelOutput:qm};o[s]={...v,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await Xt({value:e.structuredContent,schema:Sn(t)});if(!n.success)throw new De({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 er({text:n.text,schema:t});if(!o.success)throw new De({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new De({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!==Im)throw new De({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=Im.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=l5.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 De({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 De({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new De({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}};function da(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Lm(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...da(t.headers),...da(n.headers)}:t.headers};return e(r,o)}:e}const pa="2025-11-25",H5=[pa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Pn="io.modelcontextprotocol/related-task",fa="2.0",xt=Zp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),jm=ae([d(),U().int()]),Um=d();at({ttl:ae([U(),Us()]).optional(),pollInterval:U().optional()});const J5=C({ttl:U().optional()}),G5=C({taskId:d()}),ec=at({progressToken:jm.optional(),[Pn]:G5.optional()}),Kt=C({_meta:ec.optional()}),Ko=Kt.extend({task:J5.optional()}),W5=e=>Ko.safeParse(e).success,Et=C({method:d(),params:Kt.loose().optional()}),rr=C({_meta:ec.optional()}),nr=C({method:d(),params:rr.loose().optional()}),$t=at({_meta:ec.optional()}),ha=ae([d(),U().int()]),Dm=C({jsonrpc:R(fa),id:ha,...Et.shape}).strict(),tc=e=>Dm.safeParse(e).success,zm=C({jsonrpc:R(fa),...nr.shape}).strict(),K5=e=>zm.safeParse(e).success,rc=C({jsonrpc:R(fa),id:ha,result:$t}).strict(),Yo=e=>rc.safeParse(e).success;var xe;(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"})(xe||(xe={}));const nc=C({jsonrpc:R(fa),id:ha.optional(),error:C({code:U().int(),message:d(),data:$e().optional()})}).strict(),Y5=e=>nc.safeParse(e).success,Nn=ae([Dm,zm,rc,nc]);ae([rc,nc]);const Mn=$t.strict(),Q5=rr.extend({requestId:ha.optional(),reason:d().optional()}),oc=nr.extend({method:R("notifications/cancelled"),params:Q5}),X5=C({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:me(["light","dark"]).optional()}),Qo=C({icons:q(X5).optional()}),ao=C({name:d(),title:d().optional()}),Fm=ao.extend({...ao.shape,...Qo.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),eT=Qi(C({applyDefaults:he().optional()}),ye(d(),$e())),tT=Bp(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Qi(C({form:eT.optional(),url:xt.optional()}),ye(d(),$e()).optional())),rT=at({list:xt.optional(),cancel:xt.optional(),requests:at({sampling:at({createMessage:xt.optional()}).optional(),elicitation:at({create:xt.optional()}).optional()}).optional()}),nT=at({list:xt.optional(),cancel:xt.optional(),requests:at({tools:at({call:xt.optional()}).optional()}).optional()}),oT=C({experimental:ye(d(),xt).optional(),sampling:C({context:xt.optional(),tools:xt.optional()}).optional(),elicitation:tT.optional(),roots:C({listChanged:he().optional()}).optional(),tasks:rT.optional()}),sT=Kt.extend({protocolVersion:d(),capabilities:oT,clientInfo:Fm}),aT=Et.extend({method:R("initialize"),params:sT}),iT=C({experimental:ye(d(),xt).optional(),logging:xt.optional(),completions:xt.optional(),prompts:C({listChanged:he().optional()}).optional(),resources:C({subscribe:he().optional(),listChanged:he().optional()}).optional(),tools:C({listChanged:he().optional()}).optional(),tasks:nT.optional()}),Vm=$t.extend({protocolVersion:d(),capabilities:iT,serverInfo:Fm,instructions:d().optional()}),Zm=nr.extend({method:R("notifications/initialized"),params:rr.optional()}),lT=e=>Zm.safeParse(e).success,sc=Et.extend({method:R("ping"),params:Kt.optional()}),cT=C({progress:U(),total:ce(U()),message:ce(d())}),uT=C({...rr.shape,...cT.shape,progressToken:jm}),ac=nr.extend({method:R("notifications/progress"),params:uT}),dT=Kt.extend({cursor:Um.optional()}),Xo=Et.extend({params:dT.optional()}),es=$t.extend({nextCursor:Um.optional()}),pT=me(["working","input_required","completed","failed","cancelled"]),ts=C({taskId:d(),status:pT,ttl:ae([U(),Us()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ce(U()),statusMessage:ce(d())}),rs=$t.extend({task:ts}),fT=rr.merge(ts),ma=nr.extend({method:R("notifications/tasks/status"),params:fT}),ic=Et.extend({method:R("tasks/get"),params:Kt.extend({taskId:d()})}),lc=$t.merge(ts),cc=Et.extend({method:R("tasks/result"),params:Kt.extend({taskId:d()})});$t.loose();const uc=Xo.extend({method:R("tasks/list")}),dc=es.extend({tasks:q(ts)}),pc=Et.extend({method:R("tasks/cancel"),params:Kt.extend({taskId:d()})}),hT=$t.merge(ts),Bm=C({uri:d(),mimeType:ce(d()),_meta:ye(d(),$e()).optional()}),Hm=Bm.extend({text:d()}),fc=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Jm=Bm.extend({blob:fc}),ns=me(["user","assistant"]),io=C({audience:q(ns).optional(),priority:U().min(0).max(1).optional(),lastModified:Rp({offset:!0}).optional()}),Gm=C({...ao.shape,...Qo.shape,uri:d(),description:ce(d()),mimeType:ce(d()),annotations:io.optional(),_meta:ce(at({}))}),mT=C({...ao.shape,...Qo.shape,uriTemplate:d(),description:ce(d()),mimeType:ce(d()),annotations:io.optional(),_meta:ce(at({}))}),gT=Xo.extend({method:R("resources/list")}),Wm=es.extend({resources:q(Gm)}),yT=Xo.extend({method:R("resources/templates/list")}),Km=es.extend({resourceTemplates:q(mT)}),hc=Kt.extend({uri:d()}),_T=hc,vT=Et.extend({method:R("resources/read"),params:_T}),Ym=$t.extend({contents:q(ae([Hm,Jm]))}),mc=nr.extend({method:R("notifications/resources/list_changed"),params:rr.optional()}),wT=hc,bT=Et.extend({method:R("resources/subscribe"),params:wT}),kT=hc,CT=Et.extend({method:R("resources/unsubscribe"),params:kT}),TT=rr.extend({uri:d()}),Qm=nr.extend({method:R("notifications/resources/updated"),params:TT}),ST=C({name:d(),description:ce(d()),required:ce(he())}),IT=C({...ao.shape,...Qo.shape,description:ce(d()),arguments:ce(q(ST)),_meta:ce(at({}))}),xT=Xo.extend({method:R("prompts/list")}),Xm=es.extend({prompts:q(IT)}),ET=Kt.extend({name:d(),arguments:ye(d(),d()).optional()}),$T=Et.extend({method:R("prompts/get"),params:ET}),gc=C({type:R("text"),text:d(),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),yc=C({type:R("image"),data:fc,mimeType:d(),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),_c=C({type:R("audio"),data:fc,mimeType:d(),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),RT=C({type:R("tool_use"),name:d(),id:d(),input:ye(d(),$e()),_meta:ye(d(),$e()).optional()}),PT=C({type:R("resource"),resource:ae([Hm,Jm]),annotations:io.optional(),_meta:ye(d(),$e()).optional()}),NT=Gm.extend({type:R("resource_link")}),vc=ae([gc,yc,_c,NT,PT]),MT=C({role:ns,content:vc}),e2=$t.extend({description:d().optional(),messages:q(MT)}),wc=nr.extend({method:R("notifications/prompts/list_changed"),params:rr.optional()}),OT=C({title:d().optional(),readOnlyHint:he().optional(),destructiveHint:he().optional(),idempotentHint:he().optional(),openWorldHint:he().optional()}),AT=C({taskSupport:me(["required","optional","forbidden"]).optional()}),t2=C({...ao.shape,...Qo.shape,description:d().optional(),inputSchema:C({type:R("object"),properties:ye(d(),xt).optional(),required:q(d()).optional()}).catchall($e()),outputSchema:C({type:R("object"),properties:ye(d(),xt).optional(),required:q(d()).optional()}).catchall($e()).optional(),annotations:OT.optional(),execution:AT.optional(),_meta:ye(d(),$e()).optional()}),qT=Xo.extend({method:R("tools/list")}),r2=es.extend({tools:q(t2)}),os=$t.extend({content:q(vc).default([]),structuredContent:ye(d(),$e()).optional(),isError:he().optional()});os.or($t.extend({toolResult:$e()}));const LT=Ko.extend({name:d(),arguments:ye(d(),$e()).optional()}),jT=Et.extend({method:R("tools/call"),params:LT}),bc=nr.extend({method:R("notifications/tools/list_changed"),params:rr.optional()}),UT=C({autoRefresh:he().default(!0),debounceMs:U().int().nonnegative().default(300)}),n2=me(["debug","info","notice","warning","error","critical","alert","emergency"]),DT=Kt.extend({level:n2}),zT=Et.extend({method:R("logging/setLevel"),params:DT}),FT=rr.extend({level:n2,logger:d().optional(),data:$e()}),o2=nr.extend({method:R("notifications/message"),params:FT}),VT=C({name:d().optional()}),ZT=C({hints:q(VT).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),BT=C({mode:me(["auto","required","none"]).optional()}),HT=C({type:R("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(vc).default([]),structuredContent:C({}).loose().optional(),isError:he().optional(),_meta:ye(d(),$e()).optional()}),JT=je("type",[gc,yc,_c]),ga=je("type",[gc,yc,_c,RT,HT]),GT=C({role:ns,content:ae([ga,q(ga)]),_meta:ye(d(),$e()).optional()}),WT=Ko.extend({messages:q(GT),modelPreferences:ZT.optional(),systemPrompt:d().optional(),includeContext:me(["none","thisServer","allServers"]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:q(d()).optional(),metadata:xt.optional(),tools:q(t2).optional(),toolChoice:BT.optional()}),kc=Et.extend({method:R("sampling/createMessage"),params:WT}),Cc=$t.extend({model:d(),stopReason:ce(me(["endTurn","stopSequence","maxTokens"]).or(d())),role:ns,content:JT}),s2=$t.extend({model:d(),stopReason:ce(me(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:ns,content:ae([ga,q(ga)])}),KT=C({type:R("boolean"),title:d().optional(),description:d().optional(),default:he().optional()}),YT=C({type:R("string"),title:d().optional(),description:d().optional(),minLength:U().optional(),maxLength:U().optional(),format:me(["email","uri","date","date-time"]).optional(),default:d().optional()}),QT=C({type:me(["number","integer"]),title:d().optional(),description:d().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),XT=C({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),eS=C({type:R("string"),title:d().optional(),description:d().optional(),oneOf:q(C({const:d(),title:d()})),default:d().optional()}),tS=C({type:R("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),rS=ae([XT,eS]),nS=C({type:R("array"),title:d().optional(),description:d().optional(),minItems:U().optional(),maxItems:U().optional(),items:C({type:R("string"),enum:q(d())}),default:q(d()).optional()}),oS=C({type:R("array"),title:d().optional(),description:d().optional(),minItems:U().optional(),maxItems:U().optional(),items:C({anyOf:q(C({const:d(),title:d()}))}),default:q(d()).optional()}),sS=ae([nS,oS]),aS=ae([tS,rS,sS]),iS=ae([aS,KT,YT,QT]),lS=Ko.extend({mode:R("form").optional(),message:d(),requestedSchema:C({type:R("object"),properties:ye(d(),iS),required:q(d()).optional()})}),cS=Ko.extend({mode:R("url"),message:d(),elicitationId:d(),url:d().url()}),uS=ae([lS,cS]),Tc=Et.extend({method:R("elicitation/create"),params:uS}),dS=rr.extend({elicitationId:d()}),pS=nr.extend({method:R("notifications/elicitation/complete"),params:dS}),Sc=$t.extend({action:me(["accept","decline","cancel"]),content:Bp(e=>e===null?void 0:e,ye(d(),ae([d(),U(),he(),q(d())])).optional())}),fS=C({type:R("ref/resource"),uri:d()}),hS=C({type:R("ref/prompt"),name:d()}),mS=Kt.extend({ref:ae([hS,fS]),argument:C({name:d(),value:d()}),context:C({arguments:ye(d(),d()).optional()}).optional()}),gS=Et.extend({method:R("completion/complete"),params:mS}),a2=$t.extend({completion:at({values:q(d()).max(100),total:ce(U().int()),hasMore:ce(he())})}),yS=C({uri:d().startsWith("file://"),name:d().optional(),_meta:ye(d(),$e()).optional()}),i2=Et.extend({method:R("roots/list"),params:Kt.optional()}),l2=$t.extend({roots:q(yS)}),_S=nr.extend({method:R("notifications/roots/list_changed"),params:rr.optional()});ae([sc,aT,gS,zT,$T,xT,gT,yT,vT,bT,CT,jT,qT,ic,cc,uc,pc]),ae([oc,ac,Zm,_S,ma]),ae([Mn,Cc,s2,Sc,l2,lc,dc,rs]),ae([sc,kc,Tc,i2,ic,cc,uc,pc]),ae([oc,ac,o2,Qm,mc,bc,wc,ma,pS]),ae([Mn,Vm,a2,e2,Xm,Wm,Km,Ym,os,r2,lc,dc,rs]);class be 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===xe.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new vS(o.elicitations,r)}return new be(t,r,n)}}class vS extends be{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(xe.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const Rt=Eb().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Hp.custom,message:"URL must be parseable",fatal:!0}),Bd}).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"}),wS=at({resource:d().url(),authorization_servers:q(Rt).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:he().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:he().optional()}),c2=at({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,registration_endpoint:Rt.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:Rt.optional(),revocation_endpoint:Rt.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:he().optional()}),bS=at({issuer:d(),authorization_endpoint:Rt,token_endpoint:Rt,userinfo_endpoint:Rt.optional(),jwks_uri:Rt,registration_endpoint:Rt.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:he().optional(),request_parameter_supported:he().optional(),request_uri_parameter_supported:he().optional(),require_request_uri_registration:he().optional(),op_policy_uri:Rt.optional(),op_tos_uri:Rt.optional(),client_id_metadata_document_supported:he().optional()}),kS=C({...bS.shape,...c2.pick({code_challenge_methods_supported:!0}).shape}),CS=C({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Jp().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),TS=C({error:d(),error_description:d().optional(),error_uri:d().optional()}),u2=Rt.optional().or(R("").transform(()=>{})),SS=C({redirect_uris:q(Rt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:Rt.optional(),logo_uri:u2,scope:d().optional(),contacts:q(d()).optional(),tos_uri:u2,policy_uri:d().optional(),jwks_uri:Rt.optional(),jwks:bt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),IS=C({client_id:d(),client_secret:d().optional(),client_id_issued_at:U().optional(),client_secret_expires_at:U().optional()}).strip(),xS=SS.merge(IS);C({error:d(),error_description:d().optional()}).strip(),C({token:d(),token_type_hint:d().optional()}).strip();function ES(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function $S({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 Ct 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 Ic extends Ct{}Ic.errorCode="invalid_request";class ya extends Ct{}ya.errorCode="invalid_client";class _a extends Ct{}_a.errorCode="invalid_grant";class va extends Ct{}va.errorCode="unauthorized_client";class xc extends Ct{}xc.errorCode="unsupported_grant_type";class Ec extends Ct{}Ec.errorCode="invalid_scope";class $c extends Ct{}$c.errorCode="access_denied";class lo extends Ct{}lo.errorCode="server_error";class Rc extends Ct{}Rc.errorCode="temporarily_unavailable";class Pc extends Ct{}Pc.errorCode="unsupported_response_type";class Nc extends Ct{}Nc.errorCode="unsupported_token_type";class Mc extends Ct{}Mc.errorCode="invalid_token";class Oc extends Ct{}Oc.errorCode="method_not_allowed";class Ac extends Ct{}Ac.errorCode="too_many_requests";class wa extends Ct{}wa.errorCode="invalid_client_metadata";class qc extends Ct{}qc.errorCode="insufficient_scope";class Lc extends Ct{}Lc.errorCode="invalid_target";const RS={[Ic.errorCode]:Ic,[ya.errorCode]:ya,[_a.errorCode]:_a,[va.errorCode]:va,[xc.errorCode]:xc,[Ec.errorCode]:Ec,[$c.errorCode]:$c,[lo.errorCode]:lo,[Rc.errorCode]:Rc,[Pc.errorCode]:Pc,[Nc.errorCode]:Nc,[Mc.errorCode]:Mc,[Oc.errorCode]:Oc,[Ac.errorCode]:Ac,[wa.errorCode]:wa,[qc.errorCode]:qc,[Lc.errorCode]:Lc};class or extends Error{constructor(t){super(t??"Unauthorized")}}function PS(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const jc="code",Uc="S256";function NS(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&&PS(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 MS(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":OS(o,s,r);return;case"client_secret_post":AS(o,s,n);return;case"none":qS(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function OS(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 AS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function qS(e,t){t.set("client_id",e)}async function d2(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=TS.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=RS[o]||lo;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new lo(o)}}async function On(e,t){try{return await Dc(e,t)}catch(r){if(r instanceof ya||r instanceof va)return await e.invalidateCredentials?.("all"),await Dc(e,t);if(r instanceof _a)return await e.invalidateCredentials?.("tokens"),await Dc(e,t);throw r}}async function Dc(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i,a;try{i=await US(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 jS(t,e,i),c=await ZS(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 y=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!LS(w))throw new wa(`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 WS(a,{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 GS(e,a,{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 JS(a,{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 Ct)||y instanceof lo))throw y}const f=e.state?await e.state():void 0,{authorizationUrl:g,codeVerifier:v}=await BS(a,{metadata:c,clientInformation:u,state:f,redirectUrl:e.redirectUrl,scope:n||i?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(g),"REDIRECT"}function LS(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function jS(e,t,r){const n=ES(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!$S({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 ba(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=zc(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=zc(e,"scope")||void 0,a=zc(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function zc(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 US(e,t,r=fetch){const n=await FS(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 wS.parse(await n.json())}async function Fc(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Fc(e,void 0,r):void 0;throw n}}function DS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function p2(e,t,r=fetch){return await Fc(e,{"MCP-Protocol-Version":t},r)}function zS(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function FS(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??pa;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=DS(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await p2(i,s,r);if(!n?.metadataUrl&&zS(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await p2(l,s,r)}return a}function VS(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 ZS(e,{fetchFn:t=fetch,protocolVersion:r=pa}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=VS(e);for(const{url:s,type:i}of o){const a=await Fc(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"?c2.parse(await a.json()):kS.parse(await a.json())}}}async function BS(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(jc))throw new Error(`Incompatible auth server: does not support response type ${jc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Uc))throw new Error(`Incompatible auth server: does not support code challenge method ${Uc}`)}else a=new URL("/authorize",e);const l=await hm(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",jc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",Uc),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 HS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function f2(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],m=NS(n,u);MS(m,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await d2(c);return CS.parse(await c.json())}async function JS(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 f2(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function GS(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=HS(o,c,e.redirectUrl)}const l=await e.clientInformation();return f2(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function WS(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 d2(s);return xS.parse(await s.json())}const KS={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class co extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class ka{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=Lm(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??KS}async _authThenStart(){if(!this._authProvider)throw new or("No auth provider");let t;try{t=await On(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 or;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=da(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 co(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 Kn({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:g}=await u.read();if(g)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const v=Nn.parse(JSON.parse(f.data));Yo(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(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 or("No auth provider");if(await On(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or("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:tc(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 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 p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new co(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:f,scope:g}=ba(a);if(this._resourceMetadataUrl=f,this._scope=g,await On(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or;return this._hasCompletedAuthFlow=!0,this.send(t)}if(a.status===403&&this._authProvider){const{resourceMetadataUrl:f,scope:g,error:v}=ba(a);if(v==="insufficient_scope"){const y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new co(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),f&&(this._resourceMetadataUrl=f),this._lastUpscopingHeader=y??void 0,await On(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new or;return this.send(t)}}throw new co(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),lT(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=a.headers.get("content-type");if(u)if(m?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(m?.includes("application/json")){const p=await a.json(),f=Array.isArray(p)?p.map(g=>Nn.parse(g)):[Nn.parse(p)];for(const g of f)this.onmessage?.(g)}else throw await a.body?.cancel(),new co(-1,`Unexpected content type: ${m}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new co(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 h2 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(m2(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(m2(this),r)}}function YS(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Vc(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Vc).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Vc(e.cause)}`:e.message:`${e}`}function m2(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var g2=e=>{throw TypeError(e)},Zc=(e,t,r)=>t.has(e)||g2("Cannot "+r),Oe=(e,t,r)=>(Zc(e,t,"read from private field"),r?r.call(e):t.get(e)),wt=(e,t,r)=>t.has(e)?g2("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),et=(e,t,r,n)=>(Zc(e,t,"write to private field"),t.set(e,r),r),jr=(e,t,r)=>(Zc(e,t,"access private method"),r),Ht,An,uo,Ca,Ta,ss,po,as,an,fo,ho,mo,is,fr,Bc,Hc,Jc,y2,Gc,Wc,ls,Kc,Yc;class Sa extends EventTarget{constructor(t,r){var n,o;super(),wt(this,fr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,wt(this,Ht),wt(this,An),wt(this,uo),wt(this,Ca),wt(this,Ta),wt(this,ss),wt(this,po),wt(this,as,null),wt(this,an),wt(this,fo),wt(this,ho,null),wt(this,mo,null),wt(this,is,null),wt(this,Hc,async s=>{var i;Oe(this,fo).reset();const{body:a,redirected:l,status:c,headers:u}=s;if(c===204){jr(this,fr,ls).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?et(this,uo,new URL(s.url)):et(this,uo,void 0),c!==200){jr(this,fr,ls).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){jr(this,fr,ls).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Oe(this,Ht)===this.CLOSED)return;et(this,Ht,this.OPEN);const m=new Event("open");if((i=Oe(this,is))==null||i.call(this,m),this.dispatchEvent(m),typeof a!="object"||!a||!("getReader"in a)){jr(this,fr,ls).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,f=a.getReader();let g=!0;do{const{done:v,value:y}=await f.read();y&&Oe(this,fo).feed(p.decode(y,{stream:!v})),v&&(g=!1,Oe(this,fo).reset(),jr(this,fr,Kc).call(this))}while(g)}),wt(this,Jc,s=>{et(this,an,void 0),!(s.name==="AbortError"||s.type==="aborted")&&jr(this,fr,Kc).call(this,Vc(s))}),wt(this,Gc,s=>{typeof s.id=="string"&&et(this,as,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:Oe(this,uo)?Oe(this,uo).origin:Oe(this,An).origin,lastEventId:s.id||""});Oe(this,mo)&&(!s.event||s.event==="message")&&Oe(this,mo).call(this,i),this.dispatchEvent(i)}),wt(this,Wc,s=>{et(this,ss,s)}),wt(this,Yc,()=>{et(this,po,void 0),Oe(this,Ht)===this.CONNECTING&&jr(this,fr,Bc).call(this)});try{if(t instanceof URL)et(this,An,t);else if(typeof t=="string")et(this,An,new URL(t,QS()));else throw new Error("Invalid URL")}catch{throw YS("An invalid or illegal string was specified")}et(this,fo,mf({onEvent:Oe(this,Gc),onRetry:Oe(this,Wc)})),et(this,Ht,this.CONNECTING),et(this,ss,3e3),et(this,Ta,(n=r?.fetch)!=null?n:globalThis.fetch),et(this,Ca,(o=r?.withCredentials)!=null?o:!1),jr(this,fr,Bc).call(this)}get readyState(){return Oe(this,Ht)}get url(){return Oe(this,An).href}get withCredentials(){return Oe(this,Ca)}get onerror(){return Oe(this,ho)}set onerror(t){et(this,ho,t)}get onmessage(){return Oe(this,mo)}set onmessage(t){et(this,mo,t)}get onopen(){return Oe(this,is)}set onopen(t){et(this,is,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(){Oe(this,po)&&clearTimeout(Oe(this,po)),Oe(this,Ht)!==this.CLOSED&&(Oe(this,an)&&Oe(this,an).abort(),et(this,Ht,this.CLOSED),et(this,an,void 0))}}Ht=new WeakMap,An=new WeakMap,uo=new WeakMap,Ca=new WeakMap,Ta=new WeakMap,ss=new WeakMap,po=new WeakMap,as=new WeakMap,an=new WeakMap,fo=new WeakMap,ho=new WeakMap,mo=new WeakMap,is=new WeakMap,fr=new WeakSet,Bc=function(){et(this,Ht,this.CONNECTING),et(this,an,new AbortController),Oe(this,Ta)(Oe(this,An),jr(this,fr,y2).call(this)).then(Oe(this,Hc)).catch(Oe(this,Jc))},Hc=new WeakMap,Jc=new WeakMap,y2=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Oe(this,as)?{"Last-Event-ID":Oe(this,as)}:void 0},cache:"no-store",signal:(e=Oe(this,an))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Gc=new WeakMap,Wc=new WeakMap,ls=function(e,t){var r;Oe(this,Ht)!==this.CLOSED&&et(this,Ht,this.CLOSED);const n=new h2("error",{code:t,message:e});(r=Oe(this,ho))==null||r.call(this,n),this.dispatchEvent(n)},Kc=function(e,t){var r;if(Oe(this,Ht)===this.CLOSED)return;et(this,Ht,this.CONNECTING);const n=new h2("error",{code:t,message:e});(r=Oe(this,ho))==null||r.call(this,n),this.dispatchEvent(n),et(this,po,setTimeout(Oe(this,Yc),Oe(this,ss)))},Yc=new WeakMap,Sa.CONNECTING=0,Sa.OPEN=1,Sa.CLOSED=2;function QS(){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 XS extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Ia{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=Lm(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new or("No auth provider");let t;try{t=await On(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 or;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=da(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 Sa(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}=ba(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 XS(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=Nn.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 or("No auth provider");if(await On(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or("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}=ba(o);if(this._resourceMetadataUrl=i,this._scope=a,await On(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or;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}}class xa{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new xa,r=new xa;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 Qc=C({error:C({message:d(),type:d().nullish(),param:bt().nullish(),code:ae([d(),U()]).nullish()})}),hr=on({errorSchema:Qc,errorToMessage:e=>e.error.message});function _2(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("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 v2(e){var t,r,n,o,s,i;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 a=(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=(i=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?i:0;return{inputTokens:{total:a,noCache:a-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function eI({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:i}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:i});break}case"developer":{n.push({role:"developer",content:i});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,l)=>{var c,u,m;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const p=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${p};base64,${eo(a.data)}`,detail:(u=(c=a.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Cr({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:eo(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:eo(a.data),format:"mp3"}};default:throw new Cr({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Cr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(m=a.filename)!=null?m:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${eo(a.data)}`}}}else throw new Cr({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const l=[];for(const c of i)switch(c.type){case"text":{a+=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:a,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const a of i){if(a.type==="tool-approval-response")continue;const l=a.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:a.toolCallId,content:c})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:o}}function Xc({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function w2(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 tI=ve(()=>_e(C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({message:C({role:R("assistant").nullish(),content:d().nullish(),tool_calls:q(C({id:d().nullish(),type:R("function"),function:C({name:d(),arguments:d()})})).nullish(),annotations:q(C({type:R("url_citation"),url_citation:C({start_index:U(),end_index:U(),url:d(),title:d()})})).nullish()}),index:U(),logprobs:C({content:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:C({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:C({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish()}))),rI=ve(()=>_e(ae([C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({delta:C({role:me(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(C({index:U(),id:d().nullish(),type:R("function").nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(C({type:R("url_citation"),url_citation:C({start_index:U(),end_index:U(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:C({content:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:U()})),usage:C({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:C({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish()}),Qc]))),nI=ve(()=>_e(C({logitBias:ye(Jp(),U()).optional(),logprobs:ae([he(),U()]).optional(),parallelToolCalls:he().optional(),user:d().optional(),reasoningEffort:me(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:U().optional(),store:he().optional(),metadata:ye(d().max(64),d().max(512)).optional(),prediction:ye(d(),bt()).optional(),serviceTier:me(["auto","flex","priority","default"]).optional(),strictJsonSchema:he().optional(),textVerbosity:me(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:me(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:me(["system","developer","remove"]).optional(),forceReasoning:he().optional()})));function oI({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 Cr({functionality:`tool choice type: ${s}`})}}}var sI=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:i,stopSequences:a,responseFormat:l,seed:c,tools:u,toolChoice:m,providerOptions:p}){var f,g,v,y,w;const _=[],h=(f=await Ar({provider:"openai",providerOptions:p,schema:nI}))!=null?f:{},T=_2(this.modelId),b=(g=h.forceReasoning)!=null?g:T.isReasoningModel;o!=null&&_.push({type:"unsupported",feature:"topK"});const{messages:k,warnings:S}=eI({prompt:e,systemMessageMode:(v=h.systemMessageMode)!=null?v:b?"developer":T.systemMessageMode});_.push(...S);const I=(y=h.strictJsonSchema)!=null?y:!0,x={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:i,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:I,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,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:k};b?((h.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,_.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,_.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,_.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),x.max_tokens!=null&&(x.max_completion_tokens==null&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&x.temperature!=null&&(x.temperature=void 0,_.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),h.serviceTier==="flex"&&!T.supportsFlexProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),h.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(_.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:j,toolChoice:M,toolWarnings:D}=oI({tools:u,toolChoice:m});return{args:{...x,tools:j,tool_choice:M},warnings:[..._,...D]}}async doGenerate(e){var t,r,n,o,s,i,a;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:m,rawValue:p}=await Vt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:l,failedResponseHandler:hr,successfulResponseHandler:tr(tI),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:qt(),toolName:_.function.name,input:_.function.arguments});for(const _ of(n=f.message.annotations)!=null?n:[])g.push({type:"source",sourceType:"url",id:qt(),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),((i=f.logprobs)==null?void 0:i.content)!=null&&(w.openai.logprobs=f.logprobs.content),{content:g,finishReason:{unified:w2(f.finish_reason),raw:(a=f.finish_reason)!=null?a:void 0},usage:v2(m.usage),request:{body:l},response:{...Xc(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 Vt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:n,failedResponseHandler:hr,successfulResponseHandler:Js(rI),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=[];let a={unified:"other",raw:void 0},l,c=!1,u=!1;const m={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,f){var g,v,y,w,_,h,T,b,k,S,I,x,j,M,D,A,O;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}const H=p.value;if("error"in H){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:H.error});return}if(!c){const W=Xc(H);Object.values(W).some(Boolean)&&(c=!0,f.enqueue({type:"response-metadata",...Xc(H)}))}H.usage!=null&&(l=H.usage,((g=H.usage.completion_tokens_details)==null?void 0:g.accepted_prediction_tokens)!=null&&(m.openai.acceptedPredictionTokens=(v=H.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens),((y=H.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(m.openai.rejectedPredictionTokens=(w=H.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const Q=H.choices[0];if(Q?.finish_reason!=null&&(a={unified:w2(Q.finish_reason),raw:Q.finish_reason}),((_=Q?.logprobs)==null?void 0:_.content)!=null&&(m.openai.logprobs=Q.logprobs.content),Q?.delta==null)return;const Y=Q.delta;if(Y.content!=null&&(u||(f.enqueue({type:"text-start",id:"0"}),u=!0),f.enqueue({type:"text-delta",id:"0",delta:Y.content})),Y.tool_calls!=null)for(const W of Y.tool_calls){const pe=W.index;if(i[pe]==null){if(W.type!=null&&W.type!=="function")throw new Fi({data:W,message:"Expected 'function' type."});if(W.id==null)throw new Fi({data:W,message:"Expected 'id' to be a string."});if(((h=W.function)==null?void 0:h.name)==null)throw new Fi({data:W,message:"Expected 'function.name' to be a string."});f.enqueue({type:"tool-input-start",id:W.id,toolName:W.function.name}),i[pe]={id:W.id,type:"function",function:{name:W.function.name,arguments:(T=W.function.arguments)!=null?T:""},hasFinished:!1};const P=i[pe];((b=P.function)==null?void 0:b.name)!=null&&((k=P.function)==null?void 0:k.arguments)!=null&&(P.function.arguments.length>0&&f.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),qf(P.function.arguments)&&(f.enqueue({type:"tool-input-end",id:P.id}),f.enqueue({type:"tool-call",toolCallId:(S=P.id)!=null?S:qt(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const Z=i[pe];Z.hasFinished||(((I=W.function)==null?void 0:I.arguments)!=null&&(Z.function.arguments+=(j=(x=W.function)==null?void 0:x.arguments)!=null?j:""),f.enqueue({type:"tool-input-delta",id:Z.id,delta:(M=W.function.arguments)!=null?M:""}),((D=Z.function)==null?void 0:D.name)!=null&&((A=Z.function)==null?void 0:A.arguments)!=null&&qf(Z.function.arguments)&&(f.enqueue({type:"tool-input-end",id:Z.id}),f.enqueue({type:"tool-call",toolCallId:(O=Z.id)!=null?O:qt(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}if(Y.annotations!=null)for(const W of Y.annotations)f.enqueue({type:"source",sourceType:"url",id:qt(),url:W.url_citation.url,title:W.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:a,usage:v2(l),...m!=null?{providerMetadata:m}:{}})}})),request:{body:n},response:{headers:o}}}};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=(t=e.prompt_tokens)!=null?t:0,i=(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:i,reasoning:void 0},raw:e}}function aI({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
|
|
70
70
|
|
|
71
71
|
`,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new _n({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}:
|
|
72
72
|
${i}
|
|
@@ -76,16 +76,16 @@ ${i}
|
|
|
76
76
|
|
|
77
77
|
`;break}case"tool":throw new Cr({functionality:"tool messages"});default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}return n+=`${r}:
|
|
78
78
|
`,{prompt:n,stopSequences:[`
|
|
79
|
-
${t}:`]}}function _2({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 v2(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 tI=ve(()=>_e(C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d(),logprobs:C({tokens:q(d()),token_logprobs:q(U()),top_logprobs:q(ye(d(),U())).nullish()}).nullish()})),usage:C({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()}).nullish()}))),rI=ve(()=>_e(ae([C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d().nullish(),index:U(),logprobs:C({tokens:q(d()),token_logprobs:q(U()),top_logprobs:q(ye(d(),U())).nullish()}).nullish()})),usage:C({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()}).nullish()}),Fc]))),w2=ve(()=>_e(C({echo:he().optional(),logitBias:ye(d(),U()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([he(),U()]).optional()}))),nI=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:i,stopSequences:a,responseFormat:l,tools:c,toolChoice:u,seed:m,providerOptions:p}){const f=[],g={...await Ar({provider:"openai",providerOptions:p,schema:w2}),...await Ar({provider:this.providerOptionsName,providerOptions:p,schema:w2})};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}=eI({prompt:e}),w=[...y??[],...a??[]];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:i,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:i}=await Vt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:r,failedResponseHandler:fr,successfulResponseHandler:tr(tI),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=s.choices[0],l={openai:{}};return a.logprobs!=null&&(l.openai.logprobs=a.logprobs),{content:[{type:"text",text:a.text}],usage:y2(s.usage),finishReason:{unified:v2(a.finish_reason),raw:(t=a.finish_reason)!=null?t:void 0},request:{body:r},response:{..._2(s),headers:o,body:i},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 Vt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:n,failedResponseHandler:fr,successfulResponseHandler:Js(rI),abortSignal:e.abortSignal,fetch:this.config.fetch});let i={unified:"other",raw:void 0};const a={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){i={unified:"error",raw:void 0},m.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){i={unified:"error",raw:void 0},m.enqueue({type:"error",error:p.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",..._2(p)}),m.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const f=p.choices[0];f?.finish_reason!=null&&(i={unified:v2(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(a.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:i,providerMetadata:a,usage:y2(l)})}})),request:{body:n},response:{headers:o}}}},oI=ve(()=>_e(C({dimensions:U().optional(),user:d().optional()}))),sI=ve(()=>_e(C({data:q(C({embedding:q(U())})),usage:C({prompt_tokens:U()}).nullish()}))),aI=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 yv({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Ar({provider:"openai",providerOptions:n,schema:oI}))!=null?o:{},{responseHeaders:i,value:a,rawValue:l}=await Vt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Mt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:fr,successfulResponseHandler:tr(sI),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:a.data.map(c=>c.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:i,body:l}}}},b2=ve(()=>_e(C({created:U().nullish(),data:q(C({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:C({input_tokens:U().nullish(),output_tokens:U().nullish(),total_tokens:U().nullish(),input_tokens_details:C({image_tokens:U().nullish(),text_tokens:U().nullish()}).nullish()}).nullish()}))),iI={"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},lI=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function cI(e){return lI.some(t=>e.startsWith(t))}var uI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=iI[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:i,providerOptions:a,headers:l,abortSignal:c}){var u,m,p,f,g,v,y,w,_,h,T;const b=[];s!=null&&b.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&b.push({type:"unsupported",feature:"seed"});const k=(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:x,responseHeaders:j}=await jf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Mt(this.config.headers(),l),formData:B3({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([Qn(M.data)],{type:M.mediaType})],{type:M.mediaType}):Tf(M.url))),mask:r!=null?await dI(r):void 0,n,size:o,...(f=a.openai)!=null?f:{}}),failedResponseHandler:fr,successfulResponseHandler:tr(b2),abortSignal:c,fetch:this.config.fetch});return{images:x.data.map(M=>M.b64_json),warnings:b,usage:x.usage!=null?{inputTokens:(g=x.usage.input_tokens)!=null?g:void 0,outputTokens:(v=x.usage.output_tokens)!=null?v:void 0,totalTokens:(y=x.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:j},providerMetadata:{openai:{images:x.data.map((M,D)=>{var A,O,H,Q,Y,W;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(A=x.created)!=null?A:void 0,size:(O=x.size)!=null?O:void 0,quality:(H=x.quality)!=null?H:void 0,background:(Q=x.background)!=null?Q:void 0,outputFormat:(Y=x.output_format)!=null?Y:void 0,...k2((W=x.usage)==null?void 0:W.input_tokens_details,D,x.data.length)}})}}}}const{value:S,responseHeaders:I}=await Vt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Mt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=a.openai)!=null?w:{},...cI(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:fr,successfulResponseHandler:tr(b2),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(x=>x.b64_json),warnings:b,usage:S.usage!=null?{inputTokens:(_=S.usage.input_tokens)!=null?_:void 0,outputTokens:(h=S.usage.output_tokens)!=null?h:void 0,totalTokens:(T=S.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:I},providerMetadata:{openai:{images:S.data.map((x,j)=>{var M,D,A,O,H,Q;return{...x.revised_prompt?{revisedPrompt:x.revised_prompt}:{},created:(M=S.created)!=null?M:void 0,size:(D=S.size)!=null?D:void 0,quality:(A=S.quality)!=null?A:void 0,background:(O=S.background)!=null?O:void 0,outputFormat:(H=S.output_format)!=null?H:void 0,...k2((Q=S.usage)==null?void 0:Q.input_tokens_details,j,S.data.length)}})}}}}};function k2(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 dI(e){if(!e)return;if(e.type==="url")return Tf(e.url);const t=e.data instanceof Uint8Array?e.data:Qn(e.data);return new Blob([t],{type:e.mediaType})}var C2=ve(()=>_e(C({callId:d(),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}))),T2=ve(()=>_e(C({status:me(["completed","failed"]),output:d().optional()}))),pI=ur({id:"openai.apply_patch",inputSchema:C2,outputSchema:T2}),fI=pI,hI=ve(()=>_e(C({code:d().nullish(),containerId:d()}))),mI=ve(()=>_e(C({outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullish()}))),gI=ve(()=>_e(C({container:ae([d(),C({fileIds:q(d()).optional()})]).optional()}))),yI=ur({id:"openai.code_interpreter",inputSchema:hI,outputSchema:mI}),_I=(e={})=>yI(e),vI=ve(()=>_e(C({name:d(),description:d().optional(),format:ae([C({type:R("grammar"),syntax:me(["regex","lark"]),definition:d()}),C({type:R("text")})]).optional()}))),wI=ve(()=>_e(d())),bI=Q9({id:"openai.custom",inputSchema:wI}),kI=e=>bI(e),S2=C({key:d(),type:me(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),U(),he(),q(d())])}),I2=C({type:me(["and","or"]),filters:q(ae([S2,el(()=>I2)]))}),CI=ve(()=>_e(C({vectorStoreIds:q(d()),maxNumResults:U().optional(),ranking:C({ranker:d().optional(),scoreThreshold:U().optional()}).optional(),filters:ae([S2,I2]).optional()}))),TI=ve(()=>_e(C({queries:q(d()),results:q(C({attributes:ye(d(),$e()),fileId:d(),filename:d(),score:U(),text:d()})).nullable()}))),SI=ur({id:"openai.file_search",inputSchema:C({}),outputSchema:TI}),II=ve(()=>_e(C({background:me(["auto","opaque","transparent"]).optional(),inputFidelity:me(["low","high"]).optional(),inputImageMask:C({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:me(["auto"]).optional(),outputCompression:U().int().min(0).max(100).optional(),outputFormat:me(["png","jpeg","webp"]).optional(),partialImages:U().int().min(0).max(3).optional(),quality:me(["auto","low","medium","high"]).optional(),size:me(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),xI=ve(()=>_e(C({}))),EI=ve(()=>_e(C({result:d()}))),$I=ur({id:"openai.image_generation",inputSchema:xI,outputSchema:EI}),RI=(e={})=>$I(e),x2=ve(()=>_e(C({action:C({type:R("exec"),command:q(d()),timeoutMs:U().optional(),user:d().optional(),workingDirectory:d().optional(),env:ye(d(),d()).optional()})}))),E2=ve(()=>_e(C({output:d()}))),PI=ur({id:"openai.local_shell",inputSchema:x2,outputSchema:E2}),$2=ve(()=>_e(C({action:C({commands:q(d()),timeoutMs:U().optional(),maxOutputLength:U().optional()})}))),Zc=ve(()=>_e(C({output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exitCode:U()})])}))}))),NI=q(je("type",[C({type:R("skillReference"),skillId:d(),version:d().optional()}),C({type:R("inline"),name:d(),description:d(),source:C({type:R("base64"),mediaType:R("application/zip"),data:d()})})])).optional(),MI=ve(()=>_e(C({environment:ae([C({type:R("containerAuto"),fileIds:q(d()).optional(),memoryLimit:me(["1g","4g","16g","64g"]).optional(),networkPolicy:je("type",[C({type:R("disabled")}),C({type:R("allowlist"),allowedDomains:q(d()),domainSecrets:q(C({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:NI}),C({type:R("containerReference"),containerId:d()}),C({type:R("local").optional(),skills:q(C({name:d(),description:d(),path:d()})).optional()})]).optional()}))),OI=ur({id:"openai.shell",inputSchema:$2,outputSchema:Zc}),AI=ve(()=>_e(C({externalWebAccess:he().optional(),filters:C({allowedDomains:q(d()).optional()}).optional(),searchContextSize:me(["low","medium","high"]).optional(),userLocation:C({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),qI=ve(()=>_e(C({}))),LI=ve(()=>_e(C({action:je("type",[C({type:R("search"),query:d().optional()}),C({type:R("openPage"),url:d().nullish()}),C({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(je("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).optional()}))),jI=ur({id:"openai.web_search",inputSchema:qI,outputSchema:LI}),UI=(e={})=>jI(e),DI=ve(()=>_e(C({searchContextSize:me(["low","medium","high"]).optional(),userLocation:C({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),zI=ve(()=>_e(C({}))),FI=ve(()=>_e(C({action:je("type",[C({type:R("search"),query:d().optional()}),C({type:R("openPage"),url:d().nullish()}),C({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),VI=ur({id:"openai.web_search_preview",inputSchema:zI,outputSchema:FI}),Bc=el(()=>ae([d(),U(),he(),Us(),q(Bc),ye(d(),Bc)])),ZI=ve(()=>_e(C({serverLabel:d(),allowedTools:ae([q(d()),C({readOnly:he().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ye(d(),d()).optional(),requireApproval:ae([me(["always","never"]),C({never:C({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),BI=ve(()=>_e(C({}))),HI=ve(()=>_e(C({type:R("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),Bc]).optional()}))),JI=ur({id:"openai.mcp",inputSchema:BI,outputSchema:HI}),GI=e=>JI(e),WI={applyPatch:fI,customTool:kI,codeInterpreter:_I,fileSearch:SI,imageGeneration:RI,localShell:PI,shell:OI,webSearchPreview:VI,webSearch:UI,mcp:GI};function R2(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,i=e.output_tokens,a=(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-a,cacheRead:a,cacheWrite:void 0},outputTokens:{total:i,text:i-l,reasoning:l},raw:e}}function P2(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function KI({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:i=!1,hasLocalShellTool:a=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1,customProviderToolNames:u}){var m,p,f,g,v,y,w,_,h,T,b,k,S;const I=[],x=[],j=new Set;for(const{role:M,content:D}of e)switch(M){case"system":{switch(r){case"system":{I.push({role:"system",content:D});break}case"developer":{I.push({role:"developer",content:D});break}case"remove":{x.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":{I.push({role:"user",content:D.map((A,O)=>{var H,Q,Y;switch(A.type){case"text":return{type:"input_text",text:A.text};case"file":if(A.mediaType.startsWith("image/")){const W=A.mediaType==="image/*"?"image/jpeg":A.mediaType;return{type:"input_image",...A.data instanceof URL?{image_url:A.data.toString()}:typeof A.data=="string"&&P2(A.data,o)?{file_id:A.data}:{image_url:`data:${W};base64,${eo(A.data)}`},detail:(Q=(H=A.providerOptions)==null?void 0:H[n])==null?void 0:Q.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"&&P2(A.data,o)?{file_id:A.data}:{filename:(Y=A.filename)!=null?Y:`part-${O}.pdf`,file_data:`data:application/pdf;base64,${eo(A.data)}`}};throw new Cr({functionality:`file part media type ${A.mediaType}`})}}})});break}case"assistant":{const A={};for(const O of D)switch(O.type){case"text":{const H=(m=O.providerOptions)==null?void 0:m[n],Q=H?.itemId,Y=H?.phase;if(i&&Q!=null)break;if(s&&Q!=null){I.push({type:"item_reference",id:Q});break}I.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:Q,...Y!=null&&{phase:Y}});break}case"tool-call":{const H=(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(i&&H!=null)break;if(O.providerExecuted){s&&H!=null&&I.push({type:"item_reference",id:H});break}if(s&&H!=null){I.push({type:"item_reference",id:H});break}const Q=t.toProviderToolName(O.toolName);if(a&&Q==="local_shell"){const Y=await kt({value:O.input,schema:x2});I.push({type:"local_shell_call",call_id:O.toolCallId,id:H,action:{type:"exec",command:Y.action.command,timeout_ms:Y.action.timeoutMs,user:Y.action.user,working_directory:Y.action.workingDirectory,env:Y.action.env}});break}if(l&&Q==="shell"){const Y=await kt({value:O.input,schema:$2});I.push({type:"shell_call",call_id:O.toolCallId,id:H,status:"completed",action:{commands:Y.action.commands,timeout_ms:Y.action.timeoutMs,max_output_length:Y.action.maxOutputLength}});break}if(c&&Q==="apply_patch"){const Y=await kt({value:O.input,schema:C2});I.push({type:"apply_patch_call",call_id:Y.callId,id:H,status:"completed",operation:Y.operation});break}if(u?.has(Q)){I.push({type:"custom_tool_call",call_id:O.toolCallId,name:Q,input:typeof O.input=="string"?O.input:JSON.stringify(O.input),id:H});break}I.push({type:"function_call",call_id:O.toolCallId,name:Q,arguments:JSON.stringify(O.input),id:H});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"||i)break;const H=t.toProviderToolName(O.toolName);if(l&&H==="shell"){if(O.output.type==="json"){const Q=await kt({value:O.output.value,schema:Zc});I.push({type:"shell_call_output",call_id:O.toolCallId,output:Q.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Y.outcome.exitCode}}))})}break}if(s){const Q=(h=(_=(w=O.providerOptions)==null?void 0:w[n])==null?void 0:_.itemId)!=null?h:O.toolCallId;I.push({type:"item_reference",id:Q})}else x.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const H=await Ar({provider:n,providerOptions:O.providerOptions,schema:YI}),Q=H?.itemId;if(i&&Q!=null)break;if(Q!=null){const Y=A[Q];if(s)Y===void 0&&(I.push({type:"item_reference",id:Q}),A[Q]={type:"reasoning",id:Q,summary:[]});else{const W=[];O.text.length>0?W.push({type:"summary_text",text:O.text}):Y!==void 0&&x.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),Y===void 0?(A[Q]={type:"reasoning",id:Q,encrypted_content:H?.reasoningEncryptedContent,summary:W},I.push(A[Q])):(Y.summary.push(...W),H?.reasoningEncryptedContent!=null&&(Y.encrypted_content=H.reasoningEncryptedContent))}}else{const Y=H?.reasoningEncryptedContent;if(Y!=null){const W=[];O.text.length>0&&W.push({type:"summary_text",text:O.text}),I.push({type:"reasoning",encrypted_content:Y,summary:W})}else x.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 D){if(A.type==="tool-approval-response"){const Y=A;if(j.has(Y.approvalId))continue;j.add(Y.approvalId),s&&I.push({type:"item_reference",id:Y.approvalId}),I.push({type:"mcp_approval_response",approval_request_id:Y.approvalId,approve:Y.approved});continue}const O=A.output;if(O.type==="execution-denied"&&((b=(T=O.providerOptions)==null?void 0:T.openai)==null?void 0:b.approvalId))continue;const H=t.toProviderToolName(A.toolName);if(a&&H==="local_shell"&&O.type==="json"){const Y=await kt({value:O.value,schema:E2});I.push({type:"local_shell_call_output",call_id:A.toolCallId,output:Y.output});continue}if(l&&H==="shell"&&O.type==="json"){const Y=await kt({value:O.value,schema:Zc});I.push({type:"shell_call_output",call_id:A.toolCallId,output:Y.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:W.outcome.exitCode}}))});continue}if(c&&A.toolName==="apply_patch"&&O.type==="json"){const Y=await kt({value:O.value,schema:T2});I.push({type:"apply_patch_call_output",call_id:A.toolCallId,status:Y.status,output:Y.output});continue}if(u?.has(H)){let Y;switch(O.type){case"text":case"error-text":Y=O.value;break;case"execution-denied":Y=(k=O.reason)!=null?k:"Tool execution denied.";break;case"json":case"error-json":Y=JSON.stringify(O.value);break;case"content":Y=O.value.map(W=>{var pe;switch(W.type){case"text":return{type:"input_text",text:W.text};case"image-data":return{type:"input_image",image_url:`data:${W.mediaType};base64,${W.data}`};case"image-url":return{type:"input_image",image_url:W.url};case"file-data":return{type:"input_file",filename:(pe=W.filename)!=null?pe:"data",file_data:`data:${W.mediaType};base64,${W.data}`};default:x.push({type:"other",message:`unsupported custom tool content part type: ${W.type}`});return}}).filter(Ef);break;default:Y=""}I.push({type:"custom_tool_call_output",call_id:A.toolCallId,output:Y});continue}let Q;switch(O.type){case"text":case"error-text":Q=O.value;break;case"execution-denied":Q=(S=O.reason)!=null?S:"Tool execution denied.";break;case"json":case"error-json":Q=JSON.stringify(O.value);break;case"content":Q=O.value.map(Y=>{var W;switch(Y.type){case"text":return{type:"input_text",text:Y.text};case"image-data":return{type:"input_image",image_url:`data:${Y.mediaType};base64,${Y.data}`};case"image-url":return{type:"input_image",image_url:Y.url};case"file-data":return{type:"input_file",filename:(W=Y.filename)!=null?W:"data",file_data:`data:${Y.mediaType};base64,${Y.data}`};default:{x.push({type:"other",message:`unsupported tool content part type: ${Y.type}`});return}}}).filter(Ef);break}I.push({type:"function_call_output",call_id:A.toolCallId,output:Q})}break}default:{const A=M;throw new Error(`Unsupported role: ${A}`)}}return{input:I,warnings:x}}var YI=C({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function N2({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 QI=ve(()=>_e(ae([C({type:R("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish()}),C({type:me(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:U(),input_tokens_details:C({cached_tokens:U().nullish()}).nullish(),output_tokens:U(),output_tokens_details:C({reasoning_tokens:U().nullish()}).nullish()}),service_tier:d().nullish()})}),C({type:R("response.created"),response:C({id:d(),created_at:U(),model:d(),service_tier:d().nullish()})}),C({type:R("response.output_item.added"),output_index:U(),item:je("type",[C({type:R("message"),id:d(),phase:me(["commentary","final_answer"]).nullish()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),C({type:R("web_search_call"),id:d(),status:d()}),C({type:R("computer_call"),id:d(),status:d()}),C({type:R("file_search_call"),id:d()}),C({type:R("image_generation_call"),id:d()}),C({type:R("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable(),status:d()}),C({type:R("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d()}),C({type:R("mcp_approval_request"),id:d()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),C({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:U()})])}))})])}),C({type:R("response.output_item.done"),output_index:U(),item:je("type",[C({type:R("message"),id:d(),phase:me(["commentary","final_answer"]).nullish()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:R("completed")}),C({type:R("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:R("completed")}),C({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable()}),C({type:R("image_generation_call"),id:d(),result:d()}),C({type:R("web_search_call"),id:d(),status:d(),action:je("type",[C({type:R("search"),query:d().nullish(),sources:q(je("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).nullish()}),C({type:R("open_page"),url:d().nullish()}),C({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:R("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ye(d(),ae([d(),U(),he()])),file_id:d(),filename:d(),score:U(),text:d()})).nullish()}),C({type:R("local_shell_call"),id:d(),call_id:d(),action:C({type:R("exec"),command:q(d()),timeout_ms:U().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),C({type:R("computer_call"),id:d(),status:R("completed")}),C({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:bt(),annotations:ye(d(),$e()).optional()})),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:U()})])}))})])}),C({type:R("response.function_call_arguments.delta"),item_id:d(),output_index:U(),delta:d()}),C({type:R("response.custom_tool_call_input.delta"),item_id:d(),output_index:U(),delta:d()}),C({type:R("response.image_generation_call.partial_image"),item_id:d(),output_index:U(),partial_image_b64:d()}),C({type:R("response.code_interpreter_call_code.delta"),item_id:d(),output_index:U(),delta:d()}),C({type:R("response.code_interpreter_call_code.done"),item_id:d(),output_index:U(),code:d()}),C({type:R("response.output_text.annotation.added"),annotation:je("type",[C({type:R("url_citation"),start_index:U(),end_index:U(),url:d(),title:d()}),C({type:R("file_citation"),file_id:d(),filename:d(),index:U()}),C({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:U(),end_index:U()}),C({type:R("file_path"),file_id:d(),index:U()})])}),C({type:R("response.reasoning_summary_part.added"),item_id:d(),summary_index:U()}),C({type:R("response.reasoning_summary_text.delta"),item_id:d(),summary_index:U(),delta:d()}),C({type:R("response.reasoning_summary_part.done"),item_id:d(),summary_index:U()}),C({type:R("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:U(),delta:d(),obfuscation:d().nullish()}),C({type:R("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:U(),diff:d()}),C({type:R("error"),sequence_number:U(),error:C({type:d(),code:d(),message:d(),param:d().nullish()})}),C({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),XI=ve(()=>_e(C({id:d().optional(),created_at:U().optional(),error:C({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(je("type",[C({type:R("message"),role:R("assistant"),id:d(),phase:me(["commentary","final_answer"]).nullish(),content:q(C({type:R("output_text"),text:d(),logprobs:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish(),annotations:q(je("type",[C({type:R("url_citation"),start_index:U(),end_index:U(),url:d(),title:d()}),C({type:R("file_citation"),file_id:d(),filename:d(),index:U()}),C({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:U(),end_index:U()}),C({type:R("file_path"),file_id:d(),index:U()})]))}))}),C({type:R("web_search_call"),id:d(),status:d(),action:je("type",[C({type:R("search"),query:d().nullish(),sources:q(je("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).nullish()}),C({type:R("open_page"),url:d().nullish()}),C({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:R("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ye(d(),ae([d(),U(),he()])),file_id:d(),filename:d(),score:U(),text:d()})).nullish()}),C({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable()}),C({type:R("image_generation_call"),id:d(),result:d()}),C({type:R("local_shell_call"),id:d(),call_id:d(),action:C({type:R("exec"),command:q(d()),timeout_ms:U().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),C({type:R("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),C({type:R("custom_tool_call"),call_id:d(),name:d(),input:d(),id:d()}),C({type:R("computer_call"),id:d(),status:d().optional()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(C({type:R("summary_text"),text:d()}))}),C({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:bt(),annotations:ye(d(),$e()).optional()})),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:U()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:U(),input_tokens_details:C({cached_tokens:U().nullish()}).nullish(),output_tokens:U(),output_tokens_details:C({reasoning_tokens:U().nullish()}).nullish()}).optional()}))),M2=20,O2=ve(()=>_e(C({conversation:d().nullish(),include:q(me(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([he(),U().min(1).max(M2)]).optional(),maxToolCalls:U().nullish(),metadata:bt().nullish(),parallelToolCalls:he().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:me(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:me(["auto","flex","priority","default"]).nullish(),store:he().nullish(),strictJsonSchema:he().nullish(),textVerbosity:me(["low","medium","high"]).nullish(),truncation:me(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:me(["system","developer","remove"]).optional(),forceReasoning:he().optional()})));async function e8({tools:e,toolChoice:t,toolNameMapping:r,customProviderToolNames:n}){var o;e=e?.length?e:void 0;const s=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const i=[],a=n??new Set;for(const c of e)switch(c.type){case"function":i.push({type:"function",name:c.name,description:c.description,parameters:c.inputSchema,...c.strict!=null?{strict:c.strict}:{}});break;case"provider":{switch(c.id){case"openai.file_search":{const u=await kt({value:c.args,schema:CI});i.push({type:"file_search",vector_store_ids:u.vectorStoreIds,max_num_results:u.maxNumResults,ranking_options:u.ranking?{ranker:u.ranking.ranker,score_threshold:u.ranking.scoreThreshold}:void 0,filters:u.filters});break}case"openai.local_shell":{i.push({type:"local_shell"});break}case"openai.shell":{const u=await kt({value:c.args,schema:MI});i.push({type:"shell",...u.environment&&{environment:t8(u.environment)}});break}case"openai.apply_patch":{i.push({type:"apply_patch"});break}case"openai.web_search_preview":{const u=await kt({value:c.args,schema:DI});i.push({type:"web_search_preview",search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.web_search":{const u=await kt({value:c.args,schema:AI});i.push({type:"web_search",filters:u.filters!=null?{allowed_domains:u.filters.allowedDomains}:void 0,external_web_access:u.externalWebAccess,search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.code_interpreter":{const u=await kt({value:c.args,schema:gI});i.push({type:"code_interpreter",container:u.container==null?{type:"auto",file_ids:void 0}:typeof u.container=="string"?u.container:{type:"auto",file_ids:u.container.fileIds}});break}case"openai.image_generation":{const u=await kt({value:c.args,schema:II});i.push({type:"image_generation",background:u.background,input_fidelity:u.inputFidelity,input_image_mask:u.inputImageMask?{file_id:u.inputImageMask.fileId,image_url:u.inputImageMask.imageUrl}:void 0,model:u.model,moderation:u.moderation,partial_images:u.partialImages,quality:u.quality,output_compression:u.outputCompression,output_format:u.outputFormat,size:u.size});break}case"openai.mcp":{const u=await kt({value:c.args,schema:ZI}),m=g=>({tool_names:g.toolNames}),p=u.requireApproval,f=p==null?void 0:typeof p=="string"?p:p.never!=null?{never:m(p.never)}:void 0;i.push({type:"mcp",server_label:u.serverLabel,allowed_tools:Array.isArray(u.allowedTools)?u.allowedTools:u.allowedTools?{read_only:u.allowedTools.readOnly,tool_names:u.allowedTools.toolNames}:void 0,authorization:u.authorization,connector_id:u.connectorId,headers:u.headers,require_approval:f??"never",server_description:u.serverDescription,server_url:u.serverUrl});break}case"openai.custom":{const u=await kt({value:c.args,schema:vI});i.push({type:"custom",name:u.name,description:u.description,format:u.format}),a.add(u.name);break}}break}default:s.push({type:"unsupported",feature:`function tool ${c}`});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:s};const l=t.type;switch(l){case"auto":case"none":case"required":return{tools:i,toolChoice:l,toolWarnings:s};case"tool":{const c=(o=r?.toProviderToolName(t.toolName))!=null?o:t.toolName;return{tools:i,toolChoice:c==="code_interpreter"||c==="file_search"||c==="image_generation"||c==="web_search_preview"||c==="web_search"||c==="mcp"||c==="apply_patch"?{type:c}:a.has(c)?{type:"custom",name:c}:{type:"function",name:c},toolWarnings:s}}default:{const c=l;throw new Cr({functionality:`tool choice type: ${c}`})}}}function t8(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:r8(r.skills)}}return{type:"local",skills:e.skills}}function r8(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 A2(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 i=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;i!=null&&(n[i]=s.toolCallId)}return n}var n8=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:i,seed:a,prompt:l,providerOptions:c,tools:u,toolChoice:m,responseFormat:p}){var f,g,v,y,w,_,h,T,b;const k=[],S=h2(this.modelId);o!=null&&k.push({type:"unsupported",feature:"topK"}),a!=null&&k.push({type:"unsupported",feature:"seed"}),s!=null&&k.push({type:"unsupported",feature:"presencePenalty"}),i!=null&&k.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&k.push({type:"unsupported",feature:"stopSequences"});const I=this.config.provider.includes("azure")?"azure":"openai";let x=await Ar({provider:I,providerOptions:c,schema:O2});x==null&&I!=="openai"&&(x=await Ar({provider:"openai",providerOptions:c,schema:O2}));const j=(f=x?.forceReasoning)!=null?f:S.isReasoningModel;x?.conversation&&x?.previousResponseId&&k.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const M=z3({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"},resolveProviderToolName:ee=>ee.id==="openai.custom"?ee.args.name:void 0}),D=new Set,{tools:A,toolChoice:O,toolWarnings:H}=await e8({tools:u,toolChoice:m,toolNameMapping:M,customProviderToolNames:D}),{input:Q,warnings:Y}=await KI({prompt:l,toolNameMapping:M,systemMessageMode:(g=x?.systemMessageMode)!=null?g:j?"developer":S.systemMessageMode,providerOptionsName:I,fileIdPrefixes:this.config.fileIdPrefixes,store:(v=x?.store)!=null?v:!0,hasConversation:x?.conversation!=null,hasLocalShellTool:P("openai.local_shell"),hasShellTool:P("openai.shell"),hasApplyPatchTool:P("openai.apply_patch"),customProviderToolNames:D.size>0?D:void 0});k.push(...Y);const W=(y=x?.strictJsonSchema)!=null?y:!0;let pe=x?.include;function Z(ee){pe==null?pe=[ee]:pe.includes(ee)||(pe=[...pe,ee])}function P(ee){return u?.find(se=>se.type==="provider"&&se.id===ee)!=null}const B=typeof x?.logprobs=="number"?x?.logprobs:x?.logprobs===!0?M2:void 0;B&&Z("message.output_text.logprobs");const F=(w=u?.find(ee=>ee.type==="provider"&&(ee.id==="openai.web_search"||ee.id==="openai.web_search_preview")))==null?void 0:w.name;F&&Z("web_search_call.action.sources"),P("openai.code_interpreter")&&Z("code_interpreter_call.outputs");const E=x?.store;E===!1&&j&&Z("reasoning.encrypted_content");const N={model:this.modelId,input:Q,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||x?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:W,name:(_=p.name)!=null?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...x?.textVerbosity&&{verbosity:x.textVerbosity}}},conversation:x?.conversation,max_tool_calls:x?.maxToolCalls,metadata:x?.metadata,parallel_tool_calls:x?.parallelToolCalls,previous_response_id:x?.previousResponseId,store:E,user:x?.user,instructions:x?.instructions,service_tier:x?.serviceTier,include:pe,prompt_cache_key:x?.promptCacheKey,prompt_cache_retention:x?.promptCacheRetention,safety_identifier:x?.safetyIdentifier,top_logprobs:B,truncation:x?.truncation,...j&&(x?.reasoningEffort!=null||x?.reasoningSummary!=null)&&{reasoning:{...x?.reasoningEffort!=null&&{effort:x.reasoningEffort},...x?.reasoningSummary!=null&&{summary:x.reasoningSummary}}}};j?x?.reasoningEffort==="none"&&S.supportsNonReasoningParameters||(N.temperature!=null&&(N.temperature=void 0,k.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),N.top_p!=null&&(N.top_p=void 0,k.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(x?.reasoningEffort!=null&&k.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),x?.reasoningSummary!=null&&k.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),x?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete N.service_tier),x?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete N.service_tier);const L=(b=(T=(h=u?.find(ee=>ee.type==="provider"&&ee.id==="openai.shell"))==null?void 0:h.args)==null?void 0:T.environment)==null?void 0:b.type,G=L==="containerAuto"||L==="containerReference";return{webSearchToolName:F,args:{...N,tools:A,tool_choice:O},warnings:[...k,...H],store:E,toolNameMapping:M,providerOptionsName:I,isShellProviderExecuted:G}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,m,p,f,g,v,y,w,_,h,T,b,k,S,I,x;const{args:j,warnings:M,webSearchToolName:D,toolNameMapping:A,providerOptionsName:O,isShellProviderExecuted:H}=await this.getArgs(e),Q=this.config.url({path:"/responses",modelId:this.modelId}),Y=A2(e.prompt),{responseHeaders:W,value:pe,rawValue:Z}=await Vt({url:Q,headers:Mt(this.config.headers(),e.headers),body:j,failedResponseHandler:fr,successfulResponseHandler:tr(XI),abortSignal:e.abortSignal,fetch:this.config.fetch});if(pe.error)throw new ot({message:pe.error.message,url:Q,requestBodyValues:j,statusCode:400,responseHeaders:W,responseBody:Z,isRetryable:!1});const P=[],B=[];let F=!1;for(const L of pe.output)switch(L.type){case"reasoning":{L.summary.length===0&&L.summary.push({type:"summary_text",text:""});for(const G of L.summary)P.push({type:"reasoning",text:G.text,providerMetadata:{[O]:{itemId:L.id,reasoningEncryptedContent:(t=L.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),result:{result:L.result}});break}case"local_shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("local_shell"),input:JSON.stringify({action:L.action}),providerMetadata:{[O]:{itemId:L.id}}});break}case"shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),input:JSON.stringify({action:{commands:L.action.commands}}),...H&&{providerExecuted:!0},providerMetadata:{[O]:{itemId:L.id}}});break}case"shell_call_output":{P.push({type:"tool-result",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),result:{output:L.output.map(G=>({stdout:G.stdout,stderr:G.stderr,outcome:G.outcome.type==="exit"?{type:"exit",exitCode:G.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const G of L.content){(n=(r=e.providerOptions)==null?void 0:r[O])!=null&&n.logprobs&&G.logprobs&&B.push(G.logprobs);const ee={itemId:L.id,...L.phase!=null&&{phase:L.phase},...G.annotations.length>0&&{annotations:G.annotations}};P.push({type:"text",text:G.text,providerMetadata:{[O]:ee}});for(const se of G.annotations)se.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(i=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?i:qt(),url:se.url,title:se.title}):se.type==="file_citation"?P.push({type:"source",sourceType:"document",id:(c=(l=(a=this.config).generateId)==null?void 0:l.call(a))!=null?c:qt(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[O]:{type:se.type,fileId:se.file_id,index:se.index}}}):se.type==="container_file_citation"?P.push({type:"source",sourceType:"document",id:(p=(m=(u=this.config).generateId)==null?void 0:m.call(u))!=null?p:qt(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[O]:{type:se.type,fileId:se.file_id,containerId:se.container_id}}}):se.type==="file_path"&&P.push({type:"source",sourceType:"document",id:(v=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?v:qt(),mediaType:"application/octet-stream",title:se.file_id,filename:se.file_id,providerMetadata:{[O]:{type:se.type,fileId:se.file_id,index:se.index}}})}break}case"function_call":{F=!0,P.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:L.arguments,providerMetadata:{[O]:{itemId:L.id}}});break}case"custom_tool_call":{F=!0;const G=A.toCustomToolName(L.name);P.push({type:"tool-call",toolCallId:L.call_id,toolName:G,input:JSON.stringify(L.input),providerMetadata:{[O]:{itemId:L.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName(D??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName(D??"web_search"),result:L2(L.action)});break}case"mcp_call":{const G=L.approval_request_id!=null&&(y=Y[L.approval_request_id])!=null?y:L.id,ee=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:G,toolName:ee,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-result",toolCallId:G,toolName:ee,result:{type:"call",serverLabel:L.server_label,name:L.name,arguments:L.arguments,...L.output!=null?{output:L.output}:{},...L.error!=null?{error:L.error}:{}},providerMetadata:{[O]:{itemId:L.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const G=(w=L.approval_request_id)!=null?w:L.id,ee=(T=(h=(_=this.config).generateId)==null?void 0:h.call(_))!=null?T:qt(),se=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:ee,toolName:se,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-approval-request",approvalId:G,toolCallId:ee});break}case"computer_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:L.status||"completed"}});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),result:{queries:L.queries,results:(k=(b=L.results)==null?void 0:b.map(G=>({attributes:G.attributes,fileId:G.file_id,filename:G.filename,score:G.score,text:G.text})))!=null?k:null}});break}case"code_interpreter_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),input:JSON.stringify({code:L.code,containerId:L.container_id}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),result:{outputs:L.outputs}});break}case"apply_patch_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("apply_patch"),input:JSON.stringify({callId:L.call_id,operation:L.operation}),providerMetadata:{[O]:{itemId:L.id}}});break}}const E={[O]:{responseId:pe.id,...B.length>0?{logprobs:B}:{},...typeof pe.service_tier=="string"?{serviceTier:pe.service_tier}:{}}},N=pe.usage;return{content:P,finishReason:{unified:N2({finishReason:(S=pe.incomplete_details)==null?void 0:S.reason,hasFunctionCall:F}),raw:(x=(I=pe.incomplete_details)==null?void 0:I.reason)!=null?x:void 0},usage:R2(N),request:{body:j},response:{id:pe.id,timestamp:new Date(pe.created_at*1e3),modelId:pe.model,headers:W,body:Z},providerMetadata:E,warnings:M}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:i,isShellProviderExecuted:a}=await this.getArgs(e),{responseHeaders:l,value:c}=await Vt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:fr,successfulResponseHandler:Js(QI),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,m=A2(e.prompt),p=new Map;let f={unified:"other",raw:void 0},g;const v=[];let y=null;const w={},_=[];let h,T=!1;const b={};let k;return{stream:c.pipeThrough(new TransformStream({start(S){S.enqueue({type:"stream-start",warnings:r})},transform(S,I){var x,j,M,D,A,O,H,Q,Y,W,pe,Z,P,B,F,E,N,L,G,ee,se,ke,z,V,K,X,le,Te,Fe,tt,ut,Ye;if(e.includeRawChunks&&I.enqueue({type:"raw",rawValue:S.rawValue}),!S.success){f={unified:"error",raw:void 0},I.enqueue({type:"error",error:S.error});return}const $=S.value;if(q2($)){if($.item.type==="function_call")w[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="custom_tool_call"){const re=o.toCustomToolName($.item.name);w[$.output_index]={toolName:re,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:re})}else if($.item.type==="web_search_call")w[$.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")w[$.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if($.item.type==="code_interpreter_call")w[$.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!($.item.type==="mcp_call"||$.item.type==="mcp_list_tools"||$.item.type==="mcp_approval_request"))if($.item.type==="apply_patch_call"){const{call_id:re,operation:Ae}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:re,applyPatch:{hasDiff:Ae.type==="delete_file",endEmitted:Ae.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:re,toolName:o.toCustomToolName("apply_patch")}),Ae.type==="delete_file"){const yt=JSON.stringify({callId:re,operation:Ae});I.enqueue({type:"tool-input-delta",id:re,delta:yt}),I.enqueue({type:"tool-input-end",id:re})}else I.enqueue({type:"tool-input-delta",id:re,delta:`{"callId":"${An(re)}","operation":{"type":"${An(Ae.type)}","path":"${An(Ae.path)}","diff":"`})}else $.item.type==="shell_call"?w[$.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:$.item.call_id}:$.item.type==="shell_call_output"||($.item.type==="message"?(_.splice(0,_.length),h=(x=$.item.phase)!=null?x:void 0,I.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[i]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):q2($)&&$.item.type==="reasoning"&&(b[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[i]:{itemId:$.item.id,reasoningEncryptedContent:(j=$.item.encrypted_content)!=null?j:null}}})))}else if(s8($)){if($.item.type==="message"){const re=(M=$.item.phase)!=null?M:h;h=void 0,I.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[i]:{itemId:$.item.id,...re!=null&&{phase:re},..._.length>0&&{annotations:_}}}})}else if($.item.type==="function_call")w[$.output_index]=void 0,T=!0,I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="custom_tool_call"){w[$.output_index]=void 0,T=!0;const re=o.toCustomToolName($.item.name);I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:re,input:JSON.stringify($.item.input),providerMetadata:{[i]:{itemId:$.item.id}}})}else if($.item.type==="web_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),result:L2($.item.action)});else if($.item.type==="computer_call")w[$.output_index]=void 0,I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$.item.status||"completed"}});else if($.item.type==="file_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:$.item.queries,results:(A=(D=$.item.results)==null?void 0:D.map(re=>({attributes:re.attributes,fileId:re.file_id,filename:re.filename,score:re.score,text:re.text})))!=null?A:null}});else if($.item.type==="code_interpreter_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:$.item.outputs}});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:$.item.result}});else if($.item.type==="mcp_call"){w[$.output_index]=void 0;const re=(O=$.item.approval_request_id)!=null?O:void 0,Ae=re!=null&&(Q=(H=p.get(re))!=null?H:m[re])!=null?Q:$.item.id,yt=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:Ae,toolName:yt,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:Ae,toolName:yt,result:{type:"call",serverLabel:$.item.server_label,name:$.item.name,arguments:$.item.arguments,...$.item.output!=null?{output:$.item.output}:{},...$.item.error!=null?{error:$.item.error}:{}},providerMetadata:{[i]:{itemId:$.item.id}}})}else if($.item.type==="mcp_list_tools")w[$.output_index]=void 0;else if($.item.type==="apply_patch_call"){const re=w[$.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&$.item.operation.type!=="delete_file"&&(re.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:An($.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0),re&&$.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$.item.call_id,operation:$.item.operation}),providerMetadata:{[i]:{itemId:$.item.id}}}),w[$.output_index]=void 0}else if($.item.type==="mcp_approval_request"){w[$.output_index]=void 0;const re=(pe=(W=(Y=u.config).generateId)==null?void 0:W.call(Y))!=null?pe:qt(),Ae=(Z=$.item.approval_request_id)!=null?Z:$.item.id;p.set(Ae,re);const yt=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:re,toolName:yt,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:Ae,toolCallId:re})}else if($.item.type==="local_shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$.item.action.commands}}),...a&&{providerExecuted:!0},providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:$.item.output.map(re=>({stdout:re.stdout,stderr:re.stderr,outcome:re.outcome.type==="exit"?{type:"exit",exitCode:re.outcome.exit_code}:{type:"timeout"}}))}});else if($.item.type==="reasoning"){const re=b[$.item.id],Ae=Object.entries(re.summaryParts).filter(([yt,Dt])=>Dt==="active"||Dt==="can-conclude").map(([yt])=>yt);for(const yt of Ae)I.enqueue({type:"reasoning-end",id:`${$.item.id}:${yt}`,providerMetadata:{[i]:{itemId:$.item.id,reasoningEncryptedContent:(P=$.item.encrypted_content)!=null?P:null}}});delete b[$.item.id]}}else if(l8($)){const re=w[$.output_index];re!=null&&I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:$.delta})}else if(c8($)){const re=w[$.output_index];re!=null&&I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:$.delta})}else if(f8($)){const re=w[$.output_index];re?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:An($.delta)}),re.applyPatch.hasDiff=!0)}else if(h8($)){const re=w[$.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&(re.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:An($.diff)}),re.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0)}else if(u8($))I.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(d8($)){const re=w[$.output_index];re!=null&&I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:An($.delta)})}else if(p8($)){const re=w[$.output_index];re!=null&&(I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:re.toolCallId}),I.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$.code,containerId:re.codeInterpreter.containerId}),providerExecuted:!0}))}else if(i8($))y=$.response.id,I.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(o8($))I.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(F=(B=e.providerOptions)==null?void 0:B[i])!=null&&F.logprobs&&$.logprobs&&v.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const re=b[$.item_id];re.summaryParts[$.summary_index]="active";for(const Ae of Object.keys(re.summaryParts))re.summaryParts[Ae]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${Ae}`,providerMetadata:{[i]:{itemId:$.item_id}}}),re.summaryParts[Ae]="concluded");I.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id,reasoningEncryptedContent:(N=(E=b[$.item_id])==null?void 0:E.encryptedContent)!=null?N:null}}})}}else $.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[i]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude":a8($)?(f={unified:N2({finishReason:(L=$.response.incomplete_details)==null?void 0:L.reason,hasFunctionCall:T}),raw:(ee=(G=$.response.incomplete_details)==null?void 0:G.reason)!=null?ee:void 0},g=$.response.usage,typeof $.response.service_tier=="string"&&(k=$.response.service_tier)):m8($)?(_.push($.annotation),$.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(z=(ke=(se=u.config).generateId)==null?void 0:ke.call(se))!=null?z:qt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(X=(K=(V=u.config).generateId)==null?void 0:K.call(V))!=null?X:qt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}}):$.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Fe=(Te=(le=u.config).generateId)==null?void 0:Te.call(le))!=null?Fe:qt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,containerId:$.annotation.container_id}}}):$.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(Ye=(ut=(tt=u.config).generateId)==null?void 0:ut.call(tt))!=null?Ye:qt(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):g8($)&&I.enqueue({type:"error",error:$})},flush(S){const I={[i]:{responseId:y,...v.length>0?{logprobs:v}:{},...k!==void 0?{serviceTier:k}:{}}};S.enqueue({type:"finish",finishReason:f,usage:R2(g),providerMetadata:I})}})),request:{body:t},response:{headers:l}}}};function o8(e){return e.type==="response.output_text.delta"}function s8(e){return e.type==="response.output_item.done"}function a8(e){return e.type==="response.completed"||e.type==="response.incomplete"}function i8(e){return e.type==="response.created"}function l8(e){return e.type==="response.function_call_arguments.delta"}function c8(e){return e.type==="response.custom_tool_call_input.delta"}function u8(e){return e.type==="response.image_generation_call.partial_image"}function d8(e){return e.type==="response.code_interpreter_call_code.delta"}function p8(e){return e.type==="response.code_interpreter_call_code.done"}function f8(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function h8(e){return e.type==="response.apply_patch_call_operation_diff.done"}function q2(e){return e.type==="response.output_item.added"}function m8(e){return e.type==="response.output_text.annotation.added"}function g8(e){return e.type==="error"}function L2(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 An(e){return JSON.stringify(e).slice(1,-1)}var y8=ve(()=>_e(C({instructions:d().nullish(),speed:U().min(.25).max(4).default(1).nullish()}))),_8=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:i}){const a=[],l=await Ar({provider:"openai",providerOptions:i,schema:y8}),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",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&&a.push({type:"unsupported",feature:"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 Vt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:s,failedResponseHandler:fr,successfulResponseHandler:X9(),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}}}},v8=ve(()=>_e(C({text:d(),language:d().nullish(),duration:U().nullish(),words:q(C({word:d(),start:U(),end:U()})).nullish(),segments:q(C({id:U(),seek:U(),start:U(),end:U(),text:d(),tokens:q(U()),temperature:U(),avg_logprob:U(),compression_ratio:U(),no_speech_prob:U()})).nullish()}))),w8=ve(()=>_e(C({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:U().min(0).max(1).default(0).optional(),timestampGranularities:q(me(["word","segment"])).default(["segment"]).optional()}))),j2={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"},b8=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 Ar({provider:"openai",providerOptions:r,schema:w8}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([Qn(e)]);s.append("model",this.modelId);const a=t9(t);if(s.append("file",new File([i],"audio",{type:t}),`audio.${a}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const m of u)s.append(`${c}[]`,String(m));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,i,a,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:m}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:g}=await jf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),formData:u,failedResponseHandler:fr,successfulResponseHandler:tr(v8),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in j2?j2[p.language]:void 0;return{text:p.text,segments:(a=(i=(o=p.segments)==null?void 0:o.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?i:(s=p.words)==null?void 0:s.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?a:[],language:v,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:m,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},k8="3.0.41";function U2(e={}){var t,r;const n=(t=zf(to({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>nn({Authorization:`Bearer ${e9({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${k8}`),i=v=>new XS(v,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),a=v=>new nI(v,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=v=>new aI(v,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=v=>new uI(v,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=v=>new b8(v,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),m=v=>new _8(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 n8(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=i,g.completion=a,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=WI,g}U2();var D2="vercel.ai.error",C8=Symbol.for(D2),z2,T8=class av extends Error{constructor({name:t,message:r,cause:n}){super(r),this[z2]=!0,this.name=t,this.cause=n}static isInstance(t){return av.hasMarker(t,D2)}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}};z2=C8;var Tt=T8,F2="AI_APICallError",V2=`vercel.ai.error.${F2}`,S8=Symbol.for(V2),Z2,jr=class extends Tt{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:F2,message:e,cause:i}),this[Z2]=!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 Tt.hasMarker(e,V2)}};Z2=S8;var B2="AI_EmptyResponseBodyError",H2=`vercel.ai.error.${B2}`,I8=Symbol.for(H2),J2,x8=class extends Tt{constructor({message:e="Empty response body"}={}){super({name:B2,message:e}),this[J2]=!0}static isInstance(e){return Tt.hasMarker(e,H2)}};J2=I8;function G2(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var W2="AI_InvalidArgumentError",K2=`vercel.ai.error.${W2}`,E8=Symbol.for(K2),Y2,Q2=class extends Tt{constructor({message:e,cause:t,argument:r}){super({name:W2,message:e,cause:t}),this[Y2]=!0,this.argument=r}static isInstance(e){return Tt.hasMarker(e,K2)}};Y2=E8;var X2="AI_InvalidResponseDataError",eg=`vercel.ai.error.${X2}`,$8=Symbol.for(eg),tg,rg=class extends Tt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:X2,message:t}),this[tg]=!0,this.data=e}static isInstance(e){return Tt.hasMarker(e,eg)}};tg=$8;var ng="AI_JSONParseError",og=`vercel.ai.error.${ng}`,R8=Symbol.for(og),sg,Ta=class extends Tt{constructor({text:e,cause:t}){super({name:ng,message:`JSON parsing failed: Text: ${e}.
|
|
80
|
-
Error message: ${
|
|
81
|
-
Error message: ${G2(r)}`,cause:r}),this[mg]=!0,this.value=t}static isInstance(t){return Tt.hasMarker(t,hg)}static wrap({value:t,cause:r}){return td.isInstance(r)&&r.value===t?r:new td({value:t,cause:r})}};mg=M8;var ss=O8,gg="AI_UnsupportedFunctionalityError",yg=`vercel.ai.error.${gg}`,A8=Symbol.for(yg),_g,vg=class extends Tt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:gg,message:t}),this[_g]=!0,this.functionality=e}static isInstance(e){return Tt.hasMarker(e,yg)}};_g=A8;function wg(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Ia(e){return Object.fromEntries([...e.headers])}var q8=({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 Q2({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},xa=q8();function Hc(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var L8=["fetch failed","failed to fetch"];function j8({error:e,url:t,requestBodyValues:r}){if(Hc(e))return e;if(e instanceof TypeError&&L8.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new jr({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function U8(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 D8(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 bg(e,...t){const r=new Headers(D8(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var z8="3.0.18";function F8({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Sa({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Sa({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 Sa({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Sa({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var V8=/"__proto__"\s*:/,Z8=/"constructor"\s*:/;function kg(e){const t=JSON.parse(e);return t===null||typeof t!="object"||V8.test(e)===!1&&Z8.test(e)===!1?t:B8(t)}function B8(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 Jc(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return kg(e)}try{return kg(e)}finally{Error.stackTraceLimit=t}}var Gc=Symbol.for("vercel.ai.validator");function H8(e){return{[Gc]:!0,validate:e}}function J8(e){return typeof e=="object"&&e!==null&&Gc in e&&e[Gc]===!0&&"validate"in e}function G8(e){return J8(e)?e:typeof e=="function"?e():W8(e)}function W8(e){return H8(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new ss({value:t,cause:r.issues})}})}async function K8({value:e,schema:t}){const r=await as({value:e,schema:t});if(!r.success)throw ss.wrap({value:e,cause:r.error});return r.value}async function as({value:e,schema:t}){const r=G8(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:ss.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:ss.wrap({value:e,cause:n}),rawValue:e}}}async function Y8({text:e,schema:t}){try{const r=Jc(e);return t==null?r:K8({value:r,schema:t})}catch(r){throw Ta.isInstance(r)||ss.isInstance(r)?r:new Ta({text:e,cause:r})}}async function Cg({text:e,schema:t}){try{const r=Jc(e);return t==null?{success:!0,value:r,rawValue:r}:await as({value:r,schema:t})}catch(r){return{success:!1,error:Ta.isInstance(r)?r:new Ta({text:e,cause:r}),rawValue:void 0}}}function Tg(e){try{return Jc(e),!0}catch{return!1}}function Q8({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Cg({text:r,schema:t}))}}))}async function Sg({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await as({value:t[e],schema:r});if(!n.success)throw new Q2({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var X8=()=>globalThis.fetch,Ig=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>ex({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),ex=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=X8()})=>{try{const a=await i(e,{method:"POST",headers:bg(t,`ai-sdk/provider-utils/${z8}`,U8()),body:r.content,signal:s}),l=Ia(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw Hc(u)||jr.isInstance(u)?u:new jr({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&&(Hc(c)||jr.isInstance(c))?c:new jr({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw j8({error:a,url:e,requestBodyValues:r.values})}},tx=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=Ia(n);if(i.trim()==="")return{responseHeaders:a,value:new jr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await Y8({text:i,schema:e});return{responseHeaders:a,value:new jr({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 jr({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},rx=e=>async({response:t})=>{const r=Ia(t);if(t.body==null)throw new x8({});return{responseHeaders:r,value:Q8({stream:t.body,schema:e})}},nx=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Cg({text:o,schema:e}),i=Ia(t);if(!s.success)throw new jr({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}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:ox}=globalThis;function sx(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return ox(t)}function ax(e){return e instanceof Uint8Array?sx(e):e}function ix(e){return e?.replace(/\/$/,"")}function is(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function lx(e){const t=[];for(const{role:r,content:n,...o}of e){const s=is({...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,...is(n[0])});break}t.push({role:"user",content:n.map(i=>{const a=is(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,${ax(i.data)}`},...a}}else throw new vg({functionality:`file part media type ${i.mediaType}`})}}),...s});break}case"assistant":{let i="";const a=[];for(const l of n){const c=is(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=is(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 xg({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 Eg(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 Wc=C({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),cx=C({error:C({message:d(),type:d().nullish(),param:bt().nullish(),code:ae([d(),U()]).nullish()})}),ux={errorSchema:cx,errorToMessage:e=>e.error.message};function dx({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 vg({functionality:`tool choice type: ${s}`})}}}var px=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:ux;this.chunkSchema=hx(o.errorSchema),this.failedResponseHandler=tx(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:i,providerOptions:a,stopSequences:l,responseFormat:c,seed:u,toolChoice:m,tools:p}){var f,g,v,y;const w=[],_=Object.assign((f=await Sg({provider:"openai-compatible",providerOptions:a,schema:Wc}))!=null?f:{},(g=await Sg({provider:this.providerOptionsName,providerOptions:a,schema:Wc}))!=null?g:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:h,toolChoice:T,toolWarnings:b}=dx({tools:p,toolChoice:m});return{args:{model:this.modelId,user:_.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((y=a?.[this.providerOptionsName])!=null?y:{}).filter(([k])=>!Object.keys(Wc.shape).includes(k))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:lx(e),tools:h,tool_choice:T},warnings:[...w,...b]}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,m,p,f,g,v,y,w;const{args:_,warnings:h}=await this.getArgs({...e}),T=JSON.stringify(_),{responseHeaders:b,value:k,rawValue:S}=await Ig({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:wg(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:nx(fx),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=k.choices[0],x=[],j=I.message.content;j!=null&&j.length>0&&x.push({type:"text",text:j});const M=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(M!=null&&M.length>0&&x.push({type:"reasoning",text:M}),I.message.tool_calls!=null)for(const O of I.message.tool_calls)x.push({type:"tool-call",toolCallId:(r=O.id)!=null?r:xa(),toolName:O.function.name,input:O.function.arguments});const D={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},A=(s=k.usage)==null?void 0:s.completion_tokens_details;return A?.accepted_prediction_tokens!=null&&(D[this.providerOptionsName].acceptedPredictionTokens=A?.accepted_prediction_tokens),A?.rejected_prediction_tokens!=null&&(D[this.providerOptionsName].rejectedPredictionTokens=A?.rejected_prediction_tokens),{content:x,finishReason:Eg(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:(m=(u=k.usage)==null?void 0:u.total_tokens)!=null?m:void 0,reasoningTokens:(g=(f=(p=k.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(y=(v=k.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:D,request:{body:T},response:{...xg(k),headers:b,body:S},warnings:h}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:i,value:a}=await Ig({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:wg(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:rx(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:a.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,y){var w,_,h,T,b,k,S,I,x,j,M,D,A;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",y.enqueue({type:"error",error:v.error});return}const O=v.value;if(s?.processChunk(v.rawValue),"error"in O){c="error",y.enqueue({type:"error",error:O.error.message});return}if(m&&(m=!1,y.enqueue({type:"response-metadata",...xg(O)})),O.usage!=null){const{prompt_tokens:W,completion_tokens:pe,total_tokens:Z,prompt_tokens_details:P,completion_tokens_details:B}=O.usage;u.promptTokens=W??void 0,u.completionTokens=pe??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),P?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=P?.cached_tokens)}const H=O.choices[0];if(H?.finish_reason!=null&&(c=Eg(H.finish_reason)),H?.delta==null)return;const Q=H.delta,Y=(w=Q.reasoning_content)!=null?w:Q.reasoning;if(Y&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Y})),Q.content&&(g||(y.enqueue({type:"text-start",id:"txt-0"}),g=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:Q.content})),Q.tool_calls!=null)for(const W of Q.tool_calls){const pe=W.index;if(l[pe]==null){if(W.id==null)throw new rg({data:W,message:"Expected 'id' to be a string."});if(((_=W.function)==null?void 0:_.name)==null)throw new rg({data:W,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:W.id,toolName:W.function.name}),l[pe]={id:W.id,type:"function",function:{name:W.function.name,arguments:(h=W.function.arguments)!=null?h:""},hasFinished:!1};const P=l[pe];((T=P.function)==null?void 0:T.name)!=null&&((b=P.function)==null?void 0:b.arguments)!=null&&(P.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),Tg(P.function.arguments)&&(y.enqueue({type:"tool-input-end",id:P.id}),y.enqueue({type:"tool-call",toolCallId:(k=P.id)!=null?k:xa(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const Z=l[pe];Z.hasFinished||(((S=W.function)==null?void 0:S.arguments)!=null&&(Z.function.arguments+=(x=(I=W.function)==null?void 0:I.arguments)!=null?x:""),y.enqueue({type:"tool-input-delta",id:Z.id,delta:(j=W.function.arguments)!=null?j:""}),((M=Z.function)==null?void 0:M.name)!=null&&((D=Z.function)==null?void 0:D.arguments)!=null&&Tg(Z.function.arguments)&&(y.enqueue({type:"tool-input-end",id:Z.id}),y.enqueue({type:"tool-call",toolCallId:(A=Z.id)!=null?A:xa(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}},flush(v){var y,w,_,h,T,b;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(I=>!I.hasFinished))v.enqueue({type:"tool-input-end",id:S.id}),v.enqueue({type:"tool-call",toolCallId:(y=S.id)!=null?y:xa(),toolName:S.function.name,input:S.function.arguments});const k={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(k[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(k[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(h=u.totalTokens)!=null?h:void 0,reasoningTokens:(T=u.completionTokensDetails.reasoningTokens)!=null?T:void 0,cachedInputTokens:(b=u.promptTokensDetails.cachedTokens)!=null?b:void 0},providerMetadata:k})}})),request:{body:o},response:{headers:i}}}},$g=C({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:C({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish(),fx=C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({message:C({role:R("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({id:d().nullish(),function:C({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:$g}),hx=e=>ae([C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({delta:C({role:me(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({index:U(),id:d().nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:$g}),e]);C({echo:he().optional(),logitBias:ye(d(),U()).optional(),suffix:d().optional(),user:d().optional()});var mx=C({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()});C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d()})),usage:mx.nullish()}),C({dimensions:U().optional(),user:d().optional()}),C({data:q(C({embedding:q(U())})),usage:C({prompt_tokens:U()}).nullish(),providerMetadata:ye(d(),ye(d(),bt())).optional()}),C({data:q(C({b64_json:d()}))});var Rg=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}}},gx={extractMetadata:async({parsedBody:e})=>{const t=await as({value:e,schema:yx});return!t.success||t.value.usage==null?void 0:Rg(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await as({value:t,schema:_x});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:()=>Rg(e)}}},Pg=C({prompt_cache_hit_tokens:U().nullish(),prompt_cache_miss_tokens:U().nullish()}),yx=C({usage:Pg.nullish()}),_x=C({choices:q(C({finish_reason:d().nullish()})).nullish(),usage:Pg.nullish()}),vx="1.0.30";function Ng(e={}){var t;const r=ix((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>bg({Authorization:`Bearer ${F8({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${vx}`);class o extends px{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=a=>new o(a,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:gx}),i=a=>s(a);return i.languageModel=s,i.chat=s,i.textEmbeddingModel=a=>{throw new pg({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new pg({modelId:a,modelType:"imageModel"})},i}Ng();const wx=(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})},bx=(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 kx{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=bx("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Nn.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];wx("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 Ea(e){return!!e._zod}function an(e,t){return Ea(e)?Xd(e,t):e.safeParse(t)}function Mg(e){if(!e)return;let t;if(Ea(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Cx(e){if(Ea(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 qn(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Og(e){const r=Mg(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Cx(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ag(e,t){const r=an(e,t);if(!r.success)throw r.error;return r.data}const Tx=6e4;class Sx{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(nc,r=>{this._oncancel(r)}),this.setNotificationHandler(sc,r=>{this._onprogress(r)}),this.setRequestHandler(oc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ac,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new be(xe.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(lc,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){const l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{const m=l,p=new be(m.error.code,m.error.message,m.error.data);u(p)}else{const m=a.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new be(xe.InvalidParams,`Task not found: ${s}`);if(!qn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(qn(i.status)){const a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Pn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(cc,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 be(xe.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(dc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new be(xe.InvalidParams,`Task not found: ${r.params.taskId}`);if(qn(o.status))throw new be(xe.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 be(xe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof be?o:new be(xe.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),be.fromError(xe.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),Yo(s)||G5(s)?this._onresponse(s):ec(s)?this._onrequest(s,i):J5(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=be.fromError(xe.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?.[Pn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:xe.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):o?.send(u).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const a=H5(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const m={relatedRequestId:t.id};s&&(m.relatedTask={taskId:s}),await this.notification(u,m)},sendRequest:async(u,m,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:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(i.signal.aborted)return;const m={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)},async u=>{if(i.signal.aborted)return;const m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:xe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Yo(t))n(t);else{const i=new be(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(Yo(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),Yo(t))o(t);else{const i=be.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 be?i:new be(xe.InternalError,String(i))}}return}let s;try{const i=await this.request(t,rs,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new be(xe.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},qn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new be(xe.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new be(xe.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 be?i:new be(xe.InternalError,String(i))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{const m=_=>{u(_)};if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(_){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}}),a&&(f.params={...f.params,task:a}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Pn]: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:i}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const h=_ instanceof be?_:new be(xe.RequestTimeout,String(_));u(h)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{const h=an(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??Tx,y=()=>g(be.fromError(xe.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(p,v,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const _=h=>{const T=this._responseHandlers.get(p);T?T(h):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(h=>{this._cleanupTimeout(p),u(h)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),u(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},ic,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},uc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},dT,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||{},[Pn]: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||{},[Pn]: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||{},[Pn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=Og(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const i=Ag(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=Og(t);this._notificationHandlers.set(n,o=>{const s=Ag(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"&&ec(o.message)){const s=o.message.id,i=this._requestResolvers.get(s);i?(i(new be(xe.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 be(xe.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new be(xe.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 be(xe.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=ma.parse({method:"notifications/tasks/status",params:a});await this.notification(l),qn(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 be(xe.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(qn(a.status))throw new be(xe.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=ma.parse({method:"notifications/tasks/status",params:l});await this.notification(c),qn(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function qg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ix(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];qg(i)&&qg(s)?r[o]={...i,...s}:r[o]=s}return r}var $a={exports:{}},Kc={},Ur={},Ln={},Yc={},Qc={},Xc={},Lg;function Ra(){return Lg||(Lg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((h,T)=>`${h}${T}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((h,T)=>(T instanceof r&&(h[T.str]=(h[T.str]||0)+1),h),{})}}e._Code=n,e.nil=new n("");function o(w,..._){const h=[w[0]];let T=0;for(;T<_.length;)a(h,_[T]),h.push(w[++T]);return new n(h)}e._=o;const s=new n("+");function i(w,..._){const h=[f(w[0])];let T=0;for(;T<_.length;)h.push(s),a(h,_[T]),h.push(s,f(w[++T]));return l(h),new n(h)}e.str=i;function a(w,_){_ instanceof n?w.push(..._._items):_ instanceof r?w.push(_):w.push(m(_))}e.addCodeArg=a;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()?_:i`${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})(Xc)),Xc}var eu={},jg;function Ug(){return jg||(jg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Ra();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,m;if(!((m=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||m===void 0)&&m.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:m}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${m}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?i:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var m;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const 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=a})(eu)),eu}var Dg;function Re(){return Dg||(Dg=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=Ra(),r=Ug();var n=Ra();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=Ug();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(E,N){return this}}class i extends s{constructor(E,N,L){super(),this.varKind=E,this.name=N,this.rhs=L}render({es5:E,_n:N}){const L=E?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${L} ${this.name}${G};`+N}optimizeNames(E,N){if(E[this.name.str])return this.rhs&&(this.rhs=O(this.rhs,E,N)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(E,N,L){super(),this.lhs=E,this.rhs=N,this.sideEffects=L}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,N){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,E,N),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(E,this.rhs)}}class l extends a{constructor(E,N,L,G){super(E,L,G),this.op=N}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class m extends s{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class p extends s{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,N){return this.code=O(this.code,E,N),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((N,L)=>N+L.render(E),"")}optimizeNodes(){const{nodes:E}=this;let N=E.length;for(;N--;){const L=E[N].optimizeNodes();Array.isArray(L)?E.splice(N,1,...L):L?E[N]=L:E.splice(N,1)}return E.length>0?this:void 0}optimizeNames(E,N){const{nodes:L}=this;let G=L.length;for(;G--;){const ee=L[G];ee.optimizeNames(E,N)||(H(E,ee.names),L.splice(G,1))}return L.length>0?this:void 0}get names(){return this.nodes.reduce((E,N)=>D(E,N.names),{})}}class g extends f{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class v extends f{}class y extends g{}y.kind="else";class w extends g{constructor(E,N){super(N),this.condition=E}render(E){let N=`if(${this.condition})`+super.render(E);return this.else&&(N+="else "+this.else.render(E)),N}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let N=this.else;if(N){const L=N.optimizeNodes();N=this.else=Array.isArray(L)?new y(L):L}if(N)return E===!1?N instanceof w?N:N.nodes:this.nodes.length?this:new w(Q(E),N instanceof w?[N]:N.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,N){var L;if(this.else=(L=this.else)===null||L===void 0?void 0:L.optimizeNames(E,N),!!(super.optimizeNames(E,N)||this.else))return this.condition=O(this.condition,E,N),this}get names(){const E=super.names;return A(E,this.condition),this.else&&D(E,this.else.names),E}}w.kind="if";class _ extends g{}_.kind="for";class h extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,N){if(super.optimizeNames(E,N))return this.iteration=O(this.iteration,E,N),this}get names(){return D(super.names,this.iteration.names)}}class T extends _{constructor(E,N,L,G){super(),this.varKind=E,this.name=N,this.from=L,this.to=G}render(E){const N=E.es5?r.varKinds.var:this.varKind,{name:L,from:G,to:ee}=this;return`for(${N} ${L}=${G}; ${L}<${ee}; ${L}++)`+super.render(E)}get names(){const E=A(super.names,this.from);return A(E,this.to)}}class b extends _{constructor(E,N,L,G){super(),this.loop=E,this.varKind=N,this.name=L,this.iterable=G}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,N){if(super.optimizeNames(E,N))return this.iterable=O(this.iterable,E,N),this}get names(){return D(super.names,this.iterable.names)}}class k extends g{constructor(E,N,L){super(),this.name=E,this.args=N,this.async=L}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}k.kind="func";class S extends f{render(E){return"return "+super.render(E)}}S.kind="return";class I extends g{render(E){let N="try"+super.render(E);return this.catch&&(N+=this.catch.render(E)),this.finally&&(N+=this.finally.render(E)),N}optimizeNodes(){var E,N;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(N=this.finally)===null||N===void 0||N.optimizeNodes(),this}optimizeNames(E,N){var L,G;return super.optimizeNames(E,N),(L=this.catch)===null||L===void 0||L.optimizeNames(E,N),(G=this.finally)===null||G===void 0||G.optimizeNames(E,N),this}get names(){const E=super.names;return this.catch&&D(E,this.catch.names),this.finally&&D(E,this.finally.names),E}}class x extends g{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}x.kind="catch";class j extends g{render(E){return"finally"+super.render(E)}}j.kind="finally";class M{constructor(E,N={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...N,_n:N.lines?`
|
|
82
|
-
`:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,N){const L=this._extScope.value(E,N);return(this._values[L.prefix]||(this._values[L.prefix]=new Set)).add(L),L}getScopeValue(E,N){return this._extScope.getValue(E,N)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,N,L,G){const ee=this._scope.toName(N);return L!==void 0&&G&&(this._constants[ee.str]=L),this._leafNode(new i(E,ee,L)),ee}const(E,N,L){return this._def(r.varKinds.const,E,N,L)}let(E,N,L){return this._def(r.varKinds.let,E,N,L)}var(E,N,L){return this._def(r.varKinds.var,E,N,L)}assign(E,N,L){return this._leafNode(new a(E,N,L))}add(E,N){return this._leafNode(new l(E,e.operators.ADD,N))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new p(E)),this}object(...E){const N=["{"];for(const[L,G]of E)N.length>1&&N.push(","),N.push(L),(L!==G||this.opts.es5)&&(N.push(":"),(0,t.addCodeArg)(N,G));return N.push("}"),new t._Code(N)}if(E,N,L){if(this._blockNode(new w(E)),N&&L)this.code(N).else().code(L).endIf();else if(N)this.code(N).endIf();else if(L)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(E,N){return this._blockNode(E),N&&this.code(N).endFor(),this}for(E,N){return this._for(new h(E),N)}forRange(E,N,L,G,ee=this.opts.es5?r.varKinds.var:r.varKinds.let){const se=this._scope.toName(E);return this._for(new T(ee,se,N,L),()=>G(se))}forOf(E,N,L,G=r.varKinds.const){const ee=this._scope.toName(E);if(this.opts.es5){const se=N instanceof t.Name?N:this.var("_arr",N);return this.forRange("_i",0,(0,t._)`${se}.length`,ke=>{this.var(ee,(0,t._)`${se}[${ke}]`),L(ee)})}return this._for(new b("of",G,ee,N),()=>L(ee))}forIn(E,N,L,G=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${N})`,L);const ee=this._scope.toName(E);return this._for(new b("in",G,ee,N),()=>L(ee))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const N=new S;if(this._blockNode(N),this.code(E),N.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(E,N,L){if(!N&&!L)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new I;if(this._blockNode(G),this.code(E),N){const ee=this.name("e");this._currNode=G.catch=new x(ee),N(ee)}return L&&(this._currNode=G.finally=new j,this.code(L)),this._endBlockNode(x,j)}throw(E){return this._leafNode(new m(E))}block(E,N){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(N),this}endBlock(E){const N=this._blockStarts.pop();if(N===void 0)throw new Error("CodeGen: not in self-balancing block");const L=this._nodes.length-N;if(L<0||E!==void 0&&L!==E)throw new Error(`CodeGen: wrong number of nodes: ${L} vs ${E} expected`);return this._nodes.length=N,this}func(E,N=t.nil,L,G){return this._blockNode(new k(E,N,L)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,N){const L=this._currNode;if(L instanceof E||N&&L instanceof N)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${N?`${E.kind}/${N.kind}`:E.kind}"`)}_elseNode(E){const N=this._currNode;if(!(N instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=N.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const N=this._nodes;N[N.length-1]=E}}e.CodeGen=M;function D(F,E){for(const N in E)F[N]=(F[N]||0)+(E[N]||0);return F}function A(F,E){return E instanceof t._CodeOrName?D(F,E.names):F}function O(F,E,N){if(F instanceof t.Name)return L(F);if(!G(F))return F;return new t._Code(F._items.reduce((ee,se)=>(se instanceof t.Name&&(se=L(se)),se instanceof t._Code?ee.push(...se._items):ee.push(se),ee),[]));function L(ee){const se=N[ee.str];return se===void 0||E[ee.str]!==1?ee:(delete E[ee.str],se)}function G(ee){return ee instanceof t._Code&&ee._items.some(se=>se instanceof t.Name&&E[se.str]===1&&N[se.str]!==void 0)}}function H(F,E){for(const N in E)F[N]=(F[N]||0)-(E[N]||0)}function Q(F){return typeof F=="boolean"||typeof F=="number"||F===null?!F:(0,t._)`!${B(F)}`}e.not=Q;const Y=P(e.operators.AND);function W(...F){return F.reduce(Y)}e.and=W;const pe=P(e.operators.OR);function Z(...F){return F.reduce(pe)}e.or=Z;function P(F){return(E,N)=>E===t.nil?N:N===t.nil?E:(0,t._)`${B(E)} ${F} ${B(N)}`}function B(F){return F instanceof t.Name?F:(0,t._)`(${F})`}})(Qc)),Qc}var Pe={},zg;function Le(){if(zg)return Pe;zg=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.checkStrictMode=Pe.getErrorPath=Pe.Type=Pe.useFunc=Pe.setEvaluated=Pe.evaluatedPropsToName=Pe.mergeEvaluated=Pe.eachItem=Pe.unescapeJsonPointer=Pe.escapeJsonPointer=Pe.escapeFragment=Pe.unescapeFragment=Pe.schemaRefOrVal=Pe.schemaHasRulesButRef=Pe.schemaHasRules=Pe.checkUnknownRules=Pe.alwaysValidSchema=Pe.toHash=void 0;const e=Re(),t=Ra();function r(b){const k={};for(const S of b)k[S]=!0;return k}Pe.toHash=r;function n(b,k){return typeof k=="boolean"?k:Object.keys(k).length===0?!0:(o(b,k),!s(k,b.self.RULES.all))}Pe.alwaysValidSchema=n;function o(b,k=b.schema){const{opts:S,self:I}=b;if(!S.strictSchema||typeof k=="boolean")return;const x=I.RULES.keywords;for(const j in k)x[j]||T(b,`unknown keyword: "${j}"`)}Pe.checkUnknownRules=o;function s(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(k[S])return!0;return!1}Pe.schemaHasRules=s;function i(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(S!=="$ref"&&k.all[S])return!0;return!1}Pe.schemaHasRulesButRef=i;function a({topSchemaRef:b,schemaPath:k},S,I,x){if(!x){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${b}${k}${(0,e.getProperty)(I)}`}Pe.schemaRefOrVal=a;function l(b){return m(decodeURIComponent(b))}Pe.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}Pe.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}Pe.escapeJsonPointer=u;function m(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Pe.unescapeJsonPointer=m;function p(b,k){if(Array.isArray(b))for(const S of b)k(S);else k(b)}Pe.eachItem=p;function f({mergeNames:b,mergeToName:k,mergeValues:S,resultToName:I}){return(x,j,M,D)=>{const A=M===void 0?j:M instanceof e.Name?(j instanceof e.Name?b(x,j,M):k(x,j,M),M):j instanceof e.Name?(k(x,M,j),j):S(j,M);return D===e.Name&&!(A instanceof e.Name)?I(x,A):A}}Pe.mergeEvaluated={props:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>{b.if((0,e._)`${k} === true`,()=>b.assign(S,!0),()=>b.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${k})`))}),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>{k===!0?b.assign(S,!0):(b.assign(S,(0,e._)`${S} || {}`),v(b,S,k))}),mergeValues:(b,k)=>b===!0?!0:{...b,...k},resultToName:g}),items:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>b.assign(S,(0,e._)`${k} === true ? true : ${S} > ${k} ? ${S} : ${k}`)),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>b.assign(S,k===!0?!0:(0,e._)`${S} > ${k} ? ${S} : ${k}`)),mergeValues:(b,k)=>b===!0?!0:Math.max(b,k),resultToName:(b,k)=>b.var("items",k)})};function g(b,k){if(k===!0)return b.var("props",!0);const S=b.var("props",(0,e._)`{}`);return k!==void 0&&v(b,S,k),S}Pe.evaluatedPropsToName=g;function v(b,k,S){Object.keys(S).forEach(I=>b.assign((0,e._)`${k}${(0,e.getProperty)(I)}`,!0))}Pe.setEvaluated=v;const y={};function w(b,k){return b.scopeValue("func",{ref:k,code:y[k.code]||(y[k.code]=new t._Code(k.code))})}Pe.useFunc=w;var _;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(_||(Pe.Type=_={}));function h(b,k,S){if(b instanceof e.Name){const I=k===_.Num;return S?I?(0,e._)`"[" + ${b} + "]"`:(0,e._)`"['" + ${b} + "']"`:I?(0,e._)`"/" + ${b}`:(0,e._)`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(b).toString():"/"+u(b)}Pe.getErrorPath=h;function T(b,k,S=b.opts.strictSchema){if(S){if(k=`strict mode: ${k}`,S===!0)throw new Error(k);b.self.logger.warn(k)}}return Pe.checkStrictMode=T,Pe}var Pa={},Fg;function ln(){if(Fg)return Pa;Fg=1,Object.defineProperty(Pa,"__esModule",{value:!0});const e=Re(),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 Pa.default=t,Pa}var Vg;function Na(){return Vg||(Vg=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=Re(),r=Le(),n=ln();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,t.str)`"${y}" keyword must be ${w} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,w=e.keywordError,_,h){const{it:T}=y,{gen:b,compositeRule:k,allErrors:S}=T,I=m(y,w,_);h??(k||S)?l(b,I):c(T,(0,t._)`[${I}]`)}e.reportError=o;function s(y,w=e.keywordError,_){const{it:h}=y,{gen:T,compositeRule:b,allErrors:k}=h,S=m(y,w,_);l(T,S),b||k||c(h,n.default.vErrors)}e.reportExtraError=s;function i(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=i;function a({gen:y,keyword:w,schemaValue:_,data:h,errsCount:T,it:b}){if(T===void 0)throw new Error("ajv implementation error");const k=y.name("err");y.forRange("i",T,n.default.errors,S=>{y.const(k,(0,t._)`${n.default.vErrors}[${S}]`),y.if((0,t._)`${k}.instancePath === undefined`,()=>y.assign((0,t._)`${k}.instancePath`,(0,t.strConcat)(n.default.instancePath,b.errorPath))),y.assign((0,t._)`${k}.schemaPath`,(0,t.str)`${b.errSchemaPath}/${w}`),b.opts.verbose&&(y.assign((0,t._)`${k}.schema`,_),y.assign((0,t._)`${k}.data`,h))})}e.extendErrors=a;function l(y,w){const _=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:_,validateName:h,schemaEnv:T}=y;T.$async?_.throw((0,t._)`new ${y.ValidationError}(${w})`):(_.assign((0,t._)`${h}.errors`,w),_.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function m(y,w,_){const{createErrors:h}=y.it;return h===!1?(0,t._)`{}`:p(y,w,_)}function p(y,w,_={}){const{gen:h,it:T}=y,b=[f(T,_),g(y,_)];return v(y,w,b),h.object(...b)}function f({errorPath:y},{instancePath:w}){const _=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function g({keyword:y,it:{errSchemaPath:w}},{schemaPath:_,parentSchema:h}){let T=h?w:(0,t.str)`${w}/${y}`;return _&&(T=(0,t.str)`${T}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,T]}function v(y,{params:w,message:_},h){const{keyword:T,data:b,schemaValue:k,it:S}=y,{opts:I,propertyName:x,topSchemaRef:j,schemaPath:M}=S;h.push([u.keyword,T],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),I.messages&&h.push([u.message,typeof _=="function"?_(y):_]),I.verbose&&h.push([u.schema,k],[u.parentSchema,(0,t._)`${j}${M}`],[n.default.data,b]),x&&h.push([u.propertyName,x])}})(Yc)),Yc}var Zg;function xx(){if(Zg)return Ln;Zg=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.boolOrEmptySchema=Ln.topBoolOrEmptySchema=void 0;const e=Na(),t=Re(),r=ln(),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))}Ln.topBoolOrEmptySchema=o;function s(a,l){const{gen:c,schema:u}=a;u===!1?(c.var(l,!1),i(a)):c.var(l,!0)}Ln.boolOrEmptySchema=s;function i(a,l){const{gen:c,data:u}=a,m={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(m,n,void 0,l)}return Ln}var Pt={},jn={},Bg;function Hg(){if(Bg)return jn;Bg=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.getRules=jn.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)}jn.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 jn.getRules=n,jn}var Dr={},Jg;function Gg(){if(Jg)return Dr;Jg=1,Object.defineProperty(Dr,"__esModule",{value:!0}),Dr.shouldUseRule=Dr.shouldUseGroup=Dr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(n,i)}Dr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}Dr.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 Dr.shouldUseRule=r,Dr}var Wg;function Ma(){if(Wg)return Pt;Wg=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.reportTypeError=Pt.checkDataTypes=Pt.checkDataType=Pt.coerceAndCheckDataType=Pt.getJSONTypes=Pt.getSchemaTypes=Pt.DataType=void 0;const e=Hg(),t=Gg(),r=Na(),n=Re(),o=Le();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||(Pt.DataType=s={}));function i(_){const h=a(_.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}Pt.getSchemaTypes=i;function a(_){const h=Array.isArray(_)?_:_?[_]:[];if(h.every(e.isJSONType))return h;throw new Error("type must be JSONType or JSONType[]: "+h.join(","))}Pt.getJSONTypes=a;function l(_,h){const{gen:T,data:b,opts:k}=_,S=u(h,k.coerceTypes),I=h.length>0&&!(S.length===0&&h.length===1&&(0,t.schemaHasRulesForType)(_,h[0]));if(I){const x=g(h,b,k.strictNumbers,s.Wrong);T.if(x,()=>{S.length?m(_,h,S):y(_)})}return I}Pt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,h){return h?_.filter(T=>c.has(T)||h==="array"&&T==="array"):[]}function m(_,h,T){const{gen:b,data:k,opts:S}=_,I=b.let("dataType",(0,n._)`typeof ${k}`),x=b.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&b.if((0,n._)`${I} == 'object' && Array.isArray(${k}) && ${k}.length == 1`,()=>b.assign(k,(0,n._)`${k}[0]`).assign(I,(0,n._)`typeof ${k}`).if(g(h,k,S.strictNumbers),()=>b.assign(x,k))),b.if((0,n._)`${x} !== undefined`);for(const M of T)(c.has(M)||M==="array"&&S.coerceTypes==="array")&&j(M);b.else(),y(_),b.endIf(),b.if((0,n._)`${x} !== undefined`,()=>{b.assign(k,x),p(_,x)});function j(M){switch(M){case"string":b.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(x,(0,n._)`"" + ${k}`).elseIf((0,n._)`${k} === null`).assign(x,(0,n._)`""`);return;case"number":b.elseIf((0,n._)`${I} == "boolean" || ${k} === null
|
|
79
|
+
${t}:`]}}function k2({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 C2(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var iI=ve(()=>_e(C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d(),logprobs:C({tokens:q(d()),token_logprobs:q(U()),top_logprobs:q(ye(d(),U())).nullish()}).nullish()})),usage:C({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()}).nullish()}))),lI=ve(()=>_e(ae([C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d().nullish(),index:U(),logprobs:C({tokens:q(d()),token_logprobs:q(U()),top_logprobs:q(ye(d(),U())).nullish()}).nullish()})),usage:C({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()}).nullish()}),Qc]))),T2=ve(()=>_e(C({echo:he().optional(),logitBias:ye(d(),U()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([he(),U()]).optional()}))),cI=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:i,stopSequences:a,responseFormat:l,tools:c,toolChoice:u,seed:m,providerOptions:p}){const f=[],g={...await Ar({provider:"openai",providerOptions:p,schema:T2}),...await Ar({provider:this.providerOptionsName,providerOptions:p,schema:T2})};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}=aI({prompt:e}),w=[...y??[],...a??[]];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:i,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:i}=await Vt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:r,failedResponseHandler:hr,successfulResponseHandler:tr(iI),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=s.choices[0],l={openai:{}};return a.logprobs!=null&&(l.openai.logprobs=a.logprobs),{content:[{type:"text",text:a.text}],usage:b2(s.usage),finishReason:{unified:C2(a.finish_reason),raw:(t=a.finish_reason)!=null?t:void 0},request:{body:r},response:{...k2(s),headers:o,body:i},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 Vt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:n,failedResponseHandler:hr,successfulResponseHandler:Js(lI),abortSignal:e.abortSignal,fetch:this.config.fetch});let i={unified:"other",raw:void 0};const a={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){i={unified:"error",raw:void 0},m.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){i={unified:"error",raw:void 0},m.enqueue({type:"error",error:p.error});return}c&&(c=!1,m.enqueue({type:"response-metadata",...k2(p)}),m.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const f=p.choices[0];f?.finish_reason!=null&&(i={unified:C2(f.finish_reason),raw:f.finish_reason}),f?.logprobs!=null&&(a.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:i,providerMetadata:a,usage:b2(l)})}})),request:{body:n},response:{headers:o}}}},uI=ve(()=>_e(C({dimensions:U().optional(),user:d().optional()}))),dI=ve(()=>_e(C({data:q(C({embedding:q(U())})),usage:C({prompt_tokens:U()}).nullish()}))),pI=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 wv({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await Ar({provider:"openai",providerOptions:n,schema:uI}))!=null?o:{},{responseHeaders:i,value:a,rawValue:l}=await Vt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Mt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:hr,successfulResponseHandler:tr(dI),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:a.data.map(c=>c.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:i,body:l}}}},S2=ve(()=>_e(C({created:U().nullish(),data:q(C({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:C({input_tokens:U().nullish(),output_tokens:U().nullish(),total_tokens:U().nullish(),input_tokens_details:C({image_tokens:U().nullish(),text_tokens:U().nullish()}).nullish()}).nullish()}))),fI={"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},hI=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function mI(e){return hI.some(t=>e.startsWith(t))}var gI=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=fI[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:i,providerOptions:a,headers:l,abortSignal:c}){var u,m,p,f,g,v,y,w,_,h,T;const b=[];s!=null&&b.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&b.push({type:"unsupported",feature:"seed"});const k=(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:x,responseHeaders:j}=await jf({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Mt(this.config.headers(),l),formData:G3({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([Qn(M.data)],{type:M.mediaType})],{type:M.mediaType}):Tf(M.url))),mask:r!=null?await yI(r):void 0,n,size:o,...(f=a.openai)!=null?f:{}}),failedResponseHandler:hr,successfulResponseHandler:tr(S2),abortSignal:c,fetch:this.config.fetch});return{images:x.data.map(M=>M.b64_json),warnings:b,usage:x.usage!=null?{inputTokens:(g=x.usage.input_tokens)!=null?g:void 0,outputTokens:(v=x.usage.output_tokens)!=null?v:void 0,totalTokens:(y=x.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:j},providerMetadata:{openai:{images:x.data.map((M,D)=>{var A,O,H,Q,Y,W;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(A=x.created)!=null?A:void 0,size:(O=x.size)!=null?O:void 0,quality:(H=x.quality)!=null?H:void 0,background:(Q=x.background)!=null?Q:void 0,outputFormat:(Y=x.output_format)!=null?Y:void 0,...I2((W=x.usage)==null?void 0:W.input_tokens_details,D,x.data.length)}})}}}}const{value:S,responseHeaders:I}=await Vt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Mt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=a.openai)!=null?w:{},...mI(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:hr,successfulResponseHandler:tr(S2),abortSignal:c,fetch:this.config.fetch});return{images:S.data.map(x=>x.b64_json),warnings:b,usage:S.usage!=null?{inputTokens:(_=S.usage.input_tokens)!=null?_:void 0,outputTokens:(h=S.usage.output_tokens)!=null?h:void 0,totalTokens:(T=S.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:I},providerMetadata:{openai:{images:S.data.map((x,j)=>{var M,D,A,O,H,Q;return{...x.revised_prompt?{revisedPrompt:x.revised_prompt}:{},created:(M=S.created)!=null?M:void 0,size:(D=S.size)!=null?D:void 0,quality:(A=S.quality)!=null?A:void 0,background:(O=S.background)!=null?O:void 0,outputFormat:(H=S.output_format)!=null?H:void 0,...I2((Q=S.usage)==null?void 0:Q.input_tokens_details,j,S.data.length)}})}}}}};function I2(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 yI(e){if(!e)return;if(e.type==="url")return Tf(e.url);const t=e.data instanceof Uint8Array?e.data:Qn(e.data);return new Blob([t],{type:e.mediaType})}var x2=ve(()=>_e(C({callId:d(),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}))),E2=ve(()=>_e(C({status:me(["completed","failed"]),output:d().optional()}))),_I=ur({id:"openai.apply_patch",inputSchema:x2,outputSchema:E2}),vI=_I,wI=ve(()=>_e(C({code:d().nullish(),containerId:d()}))),bI=ve(()=>_e(C({outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullish()}))),kI=ve(()=>_e(C({container:ae([d(),C({fileIds:q(d()).optional()})]).optional()}))),CI=ur({id:"openai.code_interpreter",inputSchema:wI,outputSchema:bI}),TI=(e={})=>CI(e),SI=ve(()=>_e(C({name:d(),description:d().optional(),format:ae([C({type:R("grammar"),syntax:me(["regex","lark"]),definition:d()}),C({type:R("text")})]).optional()}))),II=ve(()=>_e(d())),xI=t4({id:"openai.custom",inputSchema:II}),EI=e=>xI(e),$2=C({key:d(),type:me(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),U(),he(),q(d())])}),R2=C({type:me(["and","or"]),filters:q(ae([$2,tl(()=>R2)]))}),$I=ve(()=>_e(C({vectorStoreIds:q(d()),maxNumResults:U().optional(),ranking:C({ranker:d().optional(),scoreThreshold:U().optional()}).optional(),filters:ae([$2,R2]).optional()}))),RI=ve(()=>_e(C({queries:q(d()),results:q(C({attributes:ye(d(),$e()),fileId:d(),filename:d(),score:U(),text:d()})).nullable()}))),PI=ur({id:"openai.file_search",inputSchema:C({}),outputSchema:RI}),NI=ve(()=>_e(C({background:me(["auto","opaque","transparent"]).optional(),inputFidelity:me(["low","high"]).optional(),inputImageMask:C({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:me(["auto"]).optional(),outputCompression:U().int().min(0).max(100).optional(),outputFormat:me(["png","jpeg","webp"]).optional(),partialImages:U().int().min(0).max(3).optional(),quality:me(["auto","low","medium","high"]).optional(),size:me(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),MI=ve(()=>_e(C({}))),OI=ve(()=>_e(C({result:d()}))),AI=ur({id:"openai.image_generation",inputSchema:MI,outputSchema:OI}),qI=(e={})=>AI(e),P2=ve(()=>_e(C({action:C({type:R("exec"),command:q(d()),timeoutMs:U().optional(),user:d().optional(),workingDirectory:d().optional(),env:ye(d(),d()).optional()})}))),N2=ve(()=>_e(C({output:d()}))),LI=ur({id:"openai.local_shell",inputSchema:P2,outputSchema:N2}),M2=ve(()=>_e(C({action:C({commands:q(d()),timeoutMs:U().optional(),maxOutputLength:U().optional()})}))),eu=ve(()=>_e(C({output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exitCode:U()})])}))}))),jI=q(je("type",[C({type:R("skillReference"),skillId:d(),version:d().optional()}),C({type:R("inline"),name:d(),description:d(),source:C({type:R("base64"),mediaType:R("application/zip"),data:d()})})])).optional(),UI=ve(()=>_e(C({environment:ae([C({type:R("containerAuto"),fileIds:q(d()).optional(),memoryLimit:me(["1g","4g","16g","64g"]).optional(),networkPolicy:je("type",[C({type:R("disabled")}),C({type:R("allowlist"),allowedDomains:q(d()),domainSecrets:q(C({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:jI}),C({type:R("containerReference"),containerId:d()}),C({type:R("local").optional(),skills:q(C({name:d(),description:d(),path:d()})).optional()})]).optional()}))),DI=ur({id:"openai.shell",inputSchema:M2,outputSchema:eu}),zI=ve(()=>_e(C({externalWebAccess:he().optional(),filters:C({allowedDomains:q(d()).optional()}).optional(),searchContextSize:me(["low","medium","high"]).optional(),userLocation:C({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),FI=ve(()=>_e(C({}))),VI=ve(()=>_e(C({action:je("type",[C({type:R("search"),query:d().optional()}),C({type:R("openPage"),url:d().nullish()}),C({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(je("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).optional()}))),ZI=ur({id:"openai.web_search",inputSchema:FI,outputSchema:VI}),BI=(e={})=>ZI(e),HI=ve(()=>_e(C({searchContextSize:me(["low","medium","high"]).optional(),userLocation:C({type:R("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),JI=ve(()=>_e(C({}))),GI=ve(()=>_e(C({action:je("type",[C({type:R("search"),query:d().optional()}),C({type:R("openPage"),url:d().nullish()}),C({type:R("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),WI=ur({id:"openai.web_search_preview",inputSchema:JI,outputSchema:GI}),tu=tl(()=>ae([d(),U(),he(),Us(),q(tu),ye(d(),tu)])),KI=ve(()=>_e(C({serverLabel:d(),allowedTools:ae([q(d()),C({readOnly:he().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:ye(d(),d()).optional(),requireApproval:ae([me(["always","never"]),C({never:C({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),YI=ve(()=>_e(C({}))),QI=ve(()=>_e(C({type:R("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),tu]).optional()}))),XI=ur({id:"openai.mcp",inputSchema:YI,outputSchema:QI}),e8=e=>XI(e),t8={applyPatch:vI,customTool:EI,codeInterpreter:TI,fileSearch:PI,imageGeneration:qI,localShell:LI,shell:DI,webSearchPreview:WI,webSearch:BI,mcp:e8};function O2(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,i=e.output_tokens,a=(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-a,cacheRead:a,cacheWrite:void 0},outputTokens:{total:i,text:i-l,reasoning:l},raw:e}}function A2(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function r8({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:i=!1,hasLocalShellTool:a=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1,customProviderToolNames:u}){var m,p,f,g,v,y,w,_,h,T,b,k,S;const I=[],x=[],j=new Set;for(const{role:M,content:D}of e)switch(M){case"system":{switch(r){case"system":{I.push({role:"system",content:D});break}case"developer":{I.push({role:"developer",content:D});break}case"remove":{x.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":{I.push({role:"user",content:D.map((A,O)=>{var H,Q,Y;switch(A.type){case"text":return{type:"input_text",text:A.text};case"file":if(A.mediaType.startsWith("image/")){const W=A.mediaType==="image/*"?"image/jpeg":A.mediaType;return{type:"input_image",...A.data instanceof URL?{image_url:A.data.toString()}:typeof A.data=="string"&&A2(A.data,o)?{file_id:A.data}:{image_url:`data:${W};base64,${eo(A.data)}`},detail:(Q=(H=A.providerOptions)==null?void 0:H[n])==null?void 0:Q.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"&&A2(A.data,o)?{file_id:A.data}:{filename:(Y=A.filename)!=null?Y:`part-${O}.pdf`,file_data:`data:application/pdf;base64,${eo(A.data)}`}};throw new Cr({functionality:`file part media type ${A.mediaType}`})}}})});break}case"assistant":{const A={};for(const O of D)switch(O.type){case"text":{const H=(m=O.providerOptions)==null?void 0:m[n],Q=H?.itemId,Y=H?.phase;if(i&&Q!=null)break;if(s&&Q!=null){I.push({type:"item_reference",id:Q});break}I.push({role:"assistant",content:[{type:"output_text",text:O.text}],id:Q,...Y!=null&&{phase:Y}});break}case"tool-call":{const H=(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(i&&H!=null)break;if(O.providerExecuted){s&&H!=null&&I.push({type:"item_reference",id:H});break}if(s&&H!=null){I.push({type:"item_reference",id:H});break}const Q=t.toProviderToolName(O.toolName);if(a&&Q==="local_shell"){const Y=await kt({value:O.input,schema:P2});I.push({type:"local_shell_call",call_id:O.toolCallId,id:H,action:{type:"exec",command:Y.action.command,timeout_ms:Y.action.timeoutMs,user:Y.action.user,working_directory:Y.action.workingDirectory,env:Y.action.env}});break}if(l&&Q==="shell"){const Y=await kt({value:O.input,schema:M2});I.push({type:"shell_call",call_id:O.toolCallId,id:H,status:"completed",action:{commands:Y.action.commands,timeout_ms:Y.action.timeoutMs,max_output_length:Y.action.maxOutputLength}});break}if(c&&Q==="apply_patch"){const Y=await kt({value:O.input,schema:x2});I.push({type:"apply_patch_call",call_id:Y.callId,id:H,status:"completed",operation:Y.operation});break}if(u?.has(Q)){I.push({type:"custom_tool_call",call_id:O.toolCallId,name:Q,input:typeof O.input=="string"?O.input:JSON.stringify(O.input),id:H});break}I.push({type:"function_call",call_id:O.toolCallId,name:Q,arguments:JSON.stringify(O.input),id:H});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"||i)break;const H=t.toProviderToolName(O.toolName);if(l&&H==="shell"){if(O.output.type==="json"){const Q=await kt({value:O.output.value,schema:eu});I.push({type:"shell_call_output",call_id:O.toolCallId,output:Q.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Y.outcome.exitCode}}))})}break}if(s){const Q=(h=(_=(w=O.providerOptions)==null?void 0:w[n])==null?void 0:_.itemId)!=null?h:O.toolCallId;I.push({type:"item_reference",id:Q})}else x.push({type:"other",message:`Results for OpenAI tool ${O.toolName} are not sent to the API when store is false`});break}case"reasoning":{const H=await Ar({provider:n,providerOptions:O.providerOptions,schema:n8}),Q=H?.itemId;if(i&&Q!=null)break;if(Q!=null){const Y=A[Q];if(s)Y===void 0&&(I.push({type:"item_reference",id:Q}),A[Q]={type:"reasoning",id:Q,summary:[]});else{const W=[];O.text.length>0?W.push({type:"summary_text",text:O.text}):Y!==void 0&&x.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(O)}.`}),Y===void 0?(A[Q]={type:"reasoning",id:Q,encrypted_content:H?.reasoningEncryptedContent,summary:W},I.push(A[Q])):(Y.summary.push(...W),H?.reasoningEncryptedContent!=null&&(Y.encrypted_content=H.reasoningEncryptedContent))}}else{const Y=H?.reasoningEncryptedContent;if(Y!=null){const W=[];O.text.length>0&&W.push({type:"summary_text",text:O.text}),I.push({type:"reasoning",encrypted_content:Y,summary:W})}else x.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 D){if(A.type==="tool-approval-response"){const Y=A;if(j.has(Y.approvalId))continue;j.add(Y.approvalId),s&&I.push({type:"item_reference",id:Y.approvalId}),I.push({type:"mcp_approval_response",approval_request_id:Y.approvalId,approve:Y.approved});continue}const O=A.output;if(O.type==="execution-denied"&&((b=(T=O.providerOptions)==null?void 0:T.openai)==null?void 0:b.approvalId))continue;const H=t.toProviderToolName(A.toolName);if(a&&H==="local_shell"&&O.type==="json"){const Y=await kt({value:O.value,schema:N2});I.push({type:"local_shell_call_output",call_id:A.toolCallId,output:Y.output});continue}if(l&&H==="shell"&&O.type==="json"){const Y=await kt({value:O.value,schema:eu});I.push({type:"shell_call_output",call_id:A.toolCallId,output:Y.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:W.outcome.exitCode}}))});continue}if(c&&A.toolName==="apply_patch"&&O.type==="json"){const Y=await kt({value:O.value,schema:E2});I.push({type:"apply_patch_call_output",call_id:A.toolCallId,status:Y.status,output:Y.output});continue}if(u?.has(H)){let Y;switch(O.type){case"text":case"error-text":Y=O.value;break;case"execution-denied":Y=(k=O.reason)!=null?k:"Tool execution denied.";break;case"json":case"error-json":Y=JSON.stringify(O.value);break;case"content":Y=O.value.map(W=>{var pe;switch(W.type){case"text":return{type:"input_text",text:W.text};case"image-data":return{type:"input_image",image_url:`data:${W.mediaType};base64,${W.data}`};case"image-url":return{type:"input_image",image_url:W.url};case"file-data":return{type:"input_file",filename:(pe=W.filename)!=null?pe:"data",file_data:`data:${W.mediaType};base64,${W.data}`};default:x.push({type:"other",message:`unsupported custom tool content part type: ${W.type}`});return}}).filter(Ef);break;default:Y=""}I.push({type:"custom_tool_call_output",call_id:A.toolCallId,output:Y});continue}let Q;switch(O.type){case"text":case"error-text":Q=O.value;break;case"execution-denied":Q=(S=O.reason)!=null?S:"Tool execution denied.";break;case"json":case"error-json":Q=JSON.stringify(O.value);break;case"content":Q=O.value.map(Y=>{var W;switch(Y.type){case"text":return{type:"input_text",text:Y.text};case"image-data":return{type:"input_image",image_url:`data:${Y.mediaType};base64,${Y.data}`};case"image-url":return{type:"input_image",image_url:Y.url};case"file-data":return{type:"input_file",filename:(W=Y.filename)!=null?W:"data",file_data:`data:${Y.mediaType};base64,${Y.data}`};default:{x.push({type:"other",message:`unsupported tool content part type: ${Y.type}`});return}}}).filter(Ef);break}I.push({type:"function_call_output",call_id:A.toolCallId,output:Q})}break}default:{const A=M;throw new Error(`Unsupported role: ${A}`)}}return{input:I,warnings:x}}var n8=C({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function q2({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 o8=ve(()=>_e(ae([C({type:R("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish()}),C({type:me(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:U(),input_tokens_details:C({cached_tokens:U().nullish()}).nullish(),output_tokens:U(),output_tokens_details:C({reasoning_tokens:U().nullish()}).nullish()}),service_tier:d().nullish()})}),C({type:R("response.created"),response:C({id:d(),created_at:U(),model:d(),service_tier:d().nullish()})}),C({type:R("response.output_item.added"),output_index:U(),item:je("type",[C({type:R("message"),id:d(),phase:me(["commentary","final_answer"]).nullish()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),C({type:R("web_search_call"),id:d(),status:d()}),C({type:R("computer_call"),id:d(),status:d()}),C({type:R("file_search_call"),id:d()}),C({type:R("image_generation_call"),id:d()}),C({type:R("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable(),status:d()}),C({type:R("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d()}),C({type:R("mcp_approval_request"),id:d()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),C({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:U()})])}))})])}),C({type:R("response.output_item.done"),output_index:U(),item:je("type",[C({type:R("message"),id:d(),phase:me(["commentary","final_answer"]).nullish()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish()}),C({type:R("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:R("completed")}),C({type:R("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:R("completed")}),C({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable()}),C({type:R("image_generation_call"),id:d(),result:d()}),C({type:R("web_search_call"),id:d(),status:d(),action:je("type",[C({type:R("search"),query:d().nullish(),sources:q(je("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).nullish()}),C({type:R("open_page"),url:d().nullish()}),C({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:R("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ye(d(),ae([d(),U(),he()])),file_id:d(),filename:d(),score:U(),text:d()})).nullish()}),C({type:R("local_shell_call"),id:d(),call_id:d(),action:C({type:R("exec"),command:q(d()),timeout_ms:U().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),C({type:R("computer_call"),id:d(),status:R("completed")}),C({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:bt(),annotations:ye(d(),$e()).optional()})),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:U()})])}))})])}),C({type:R("response.function_call_arguments.delta"),item_id:d(),output_index:U(),delta:d()}),C({type:R("response.custom_tool_call_input.delta"),item_id:d(),output_index:U(),delta:d()}),C({type:R("response.image_generation_call.partial_image"),item_id:d(),output_index:U(),partial_image_b64:d()}),C({type:R("response.code_interpreter_call_code.delta"),item_id:d(),output_index:U(),delta:d()}),C({type:R("response.code_interpreter_call_code.done"),item_id:d(),output_index:U(),code:d()}),C({type:R("response.output_text.annotation.added"),annotation:je("type",[C({type:R("url_citation"),start_index:U(),end_index:U(),url:d(),title:d()}),C({type:R("file_citation"),file_id:d(),filename:d(),index:U()}),C({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:U(),end_index:U()}),C({type:R("file_path"),file_id:d(),index:U()})])}),C({type:R("response.reasoning_summary_part.added"),item_id:d(),summary_index:U()}),C({type:R("response.reasoning_summary_text.delta"),item_id:d(),summary_index:U(),delta:d()}),C({type:R("response.reasoning_summary_part.done"),item_id:d(),summary_index:U()}),C({type:R("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:U(),delta:d(),obfuscation:d().nullish()}),C({type:R("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:U(),diff:d()}),C({type:R("error"),sequence_number:U(),error:C({type:d(),code:d(),message:d(),param:d().nullish()})}),C({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),s8=ve(()=>_e(C({id:d().optional(),created_at:U().optional(),error:C({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(je("type",[C({type:R("message"),role:R("assistant"),id:d(),phase:me(["commentary","final_answer"]).nullish(),content:q(C({type:R("output_text"),text:d(),logprobs:q(C({token:d(),logprob:U(),top_logprobs:q(C({token:d(),logprob:U()}))})).nullish(),annotations:q(je("type",[C({type:R("url_citation"),start_index:U(),end_index:U(),url:d(),title:d()}),C({type:R("file_citation"),file_id:d(),filename:d(),index:U()}),C({type:R("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:U(),end_index:U()}),C({type:R("file_path"),file_id:d(),index:U()})]))}))}),C({type:R("web_search_call"),id:d(),status:d(),action:je("type",[C({type:R("search"),query:d().nullish(),sources:q(je("type",[C({type:R("url"),url:d()}),C({type:R("api"),name:d()})])).nullish()}),C({type:R("open_page"),url:d().nullish()}),C({type:R("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),C({type:R("file_search_call"),id:d(),queries:q(d()),results:q(C({attributes:ye(d(),ae([d(),U(),he()])),file_id:d(),filename:d(),score:U(),text:d()})).nullish()}),C({type:R("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(je("type",[C({type:R("logs"),logs:d()}),C({type:R("image"),url:d()})])).nullable()}),C({type:R("image_generation_call"),id:d(),result:d()}),C({type:R("local_shell_call"),id:d(),call_id:d(),action:C({type:R("exec"),command:q(d()),timeout_ms:U().optional(),user:d().optional(),working_directory:d().optional(),env:ye(d(),d()).optional()})}),C({type:R("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),C({type:R("custom_tool_call"),call_id:d(),name:d(),input:d(),id:d()}),C({type:R("computer_call"),id:d(),status:d().optional()}),C({type:R("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(C({type:R("summary_text"),text:d()}))}),C({type:R("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),C({type:R("mcp_list_tools"),id:d(),server_label:d(),tools:q(C({name:d(),description:d().optional(),input_schema:bt(),annotations:ye(d(),$e()).optional()})),error:ae([d(),C({type:d().optional(),code:ae([U(),d()]).optional(),message:d().optional()}).loose()]).optional()}),C({type:R("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),C({type:R("apply_patch_call"),id:d(),call_id:d(),status:me(["in_progress","completed"]),operation:je("type",[C({type:R("create_file"),path:d(),diff:d()}),C({type:R("delete_file"),path:d()}),C({type:R("update_file"),path:d(),diff:d()})])}),C({type:R("shell_call"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),action:C({commands:q(d())})}),C({type:R("shell_call_output"),id:d(),call_id:d(),status:me(["in_progress","completed","incomplete"]),output:q(C({stdout:d(),stderr:d(),outcome:je("type",[C({type:R("timeout")}),C({type:R("exit"),exit_code:U()})])}))})])).optional(),service_tier:d().nullish(),incomplete_details:C({reason:d()}).nullish(),usage:C({input_tokens:U(),input_tokens_details:C({cached_tokens:U().nullish()}).nullish(),output_tokens:U(),output_tokens_details:C({reasoning_tokens:U().nullish()}).nullish()}).optional()}))),L2=20,j2=ve(()=>_e(C({conversation:d().nullish(),include:q(me(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([he(),U().min(1).max(L2)]).optional(),maxToolCalls:U().nullish(),metadata:bt().nullish(),parallelToolCalls:he().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:me(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:me(["auto","flex","priority","default"]).nullish(),store:he().nullish(),strictJsonSchema:he().nullish(),textVerbosity:me(["low","medium","high"]).nullish(),truncation:me(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:me(["system","developer","remove"]).optional(),forceReasoning:he().optional()})));async function a8({tools:e,toolChoice:t,toolNameMapping:r,customProviderToolNames:n}){var o;e=e?.length?e:void 0;const s=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const i=[],a=n??new Set;for(const c of e)switch(c.type){case"function":i.push({type:"function",name:c.name,description:c.description,parameters:c.inputSchema,...c.strict!=null?{strict:c.strict}:{}});break;case"provider":{switch(c.id){case"openai.file_search":{const u=await kt({value:c.args,schema:$I});i.push({type:"file_search",vector_store_ids:u.vectorStoreIds,max_num_results:u.maxNumResults,ranking_options:u.ranking?{ranker:u.ranking.ranker,score_threshold:u.ranking.scoreThreshold}:void 0,filters:u.filters});break}case"openai.local_shell":{i.push({type:"local_shell"});break}case"openai.shell":{const u=await kt({value:c.args,schema:UI});i.push({type:"shell",...u.environment&&{environment:i8(u.environment)}});break}case"openai.apply_patch":{i.push({type:"apply_patch"});break}case"openai.web_search_preview":{const u=await kt({value:c.args,schema:HI});i.push({type:"web_search_preview",search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.web_search":{const u=await kt({value:c.args,schema:zI});i.push({type:"web_search",filters:u.filters!=null?{allowed_domains:u.filters.allowedDomains}:void 0,external_web_access:u.externalWebAccess,search_context_size:u.searchContextSize,user_location:u.userLocation});break}case"openai.code_interpreter":{const u=await kt({value:c.args,schema:kI});i.push({type:"code_interpreter",container:u.container==null?{type:"auto",file_ids:void 0}:typeof u.container=="string"?u.container:{type:"auto",file_ids:u.container.fileIds}});break}case"openai.image_generation":{const u=await kt({value:c.args,schema:NI});i.push({type:"image_generation",background:u.background,input_fidelity:u.inputFidelity,input_image_mask:u.inputImageMask?{file_id:u.inputImageMask.fileId,image_url:u.inputImageMask.imageUrl}:void 0,model:u.model,moderation:u.moderation,partial_images:u.partialImages,quality:u.quality,output_compression:u.outputCompression,output_format:u.outputFormat,size:u.size});break}case"openai.mcp":{const u=await kt({value:c.args,schema:KI}),m=g=>({tool_names:g.toolNames}),p=u.requireApproval,f=p==null?void 0:typeof p=="string"?p:p.never!=null?{never:m(p.never)}:void 0;i.push({type:"mcp",server_label:u.serverLabel,allowed_tools:Array.isArray(u.allowedTools)?u.allowedTools:u.allowedTools?{read_only:u.allowedTools.readOnly,tool_names:u.allowedTools.toolNames}:void 0,authorization:u.authorization,connector_id:u.connectorId,headers:u.headers,require_approval:f??"never",server_description:u.serverDescription,server_url:u.serverUrl});break}case"openai.custom":{const u=await kt({value:c.args,schema:SI});i.push({type:"custom",name:u.name,description:u.description,format:u.format}),a.add(u.name);break}}break}default:s.push({type:"unsupported",feature:`function tool ${c}`});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:s};const l=t.type;switch(l){case"auto":case"none":case"required":return{tools:i,toolChoice:l,toolWarnings:s};case"tool":{const c=(o=r?.toProviderToolName(t.toolName))!=null?o:t.toolName;return{tools:i,toolChoice:c==="code_interpreter"||c==="file_search"||c==="image_generation"||c==="web_search_preview"||c==="web_search"||c==="mcp"||c==="apply_patch"?{type:c}:a.has(c)?{type:"custom",name:c}:{type:"function",name:c},toolWarnings:s}}default:{const c=l;throw new Cr({functionality:`tool choice type: ${c}`})}}}function i8(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:l8(r.skills)}}return{type:"local",skills:e.skills}}function l8(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 U2(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 i=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;i!=null&&(n[i]=s.toolCallId)}return n}var c8=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:i,seed:a,prompt:l,providerOptions:c,tools:u,toolChoice:m,responseFormat:p}){var f,g,v,y,w,_,h,T,b;const k=[],S=_2(this.modelId);o!=null&&k.push({type:"unsupported",feature:"topK"}),a!=null&&k.push({type:"unsupported",feature:"seed"}),s!=null&&k.push({type:"unsupported",feature:"presencePenalty"}),i!=null&&k.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&k.push({type:"unsupported",feature:"stopSequences"});const I=this.config.provider.includes("azure")?"azure":"openai";let x=await Ar({provider:I,providerOptions:c,schema:j2});x==null&&I!=="openai"&&(x=await Ar({provider:"openai",providerOptions:c,schema:j2}));const j=(f=x?.forceReasoning)!=null?f:S.isReasoningModel;x?.conversation&&x?.previousResponseId&&k.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const M=Z3({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"},resolveProviderToolName:ee=>ee.id==="openai.custom"?ee.args.name:void 0}),D=new Set,{tools:A,toolChoice:O,toolWarnings:H}=await a8({tools:u,toolChoice:m,toolNameMapping:M,customProviderToolNames:D}),{input:Q,warnings:Y}=await r8({prompt:l,toolNameMapping:M,systemMessageMode:(g=x?.systemMessageMode)!=null?g:j?"developer":S.systemMessageMode,providerOptionsName:I,fileIdPrefixes:this.config.fileIdPrefixes,store:(v=x?.store)!=null?v:!0,hasConversation:x?.conversation!=null,hasLocalShellTool:P("openai.local_shell"),hasShellTool:P("openai.shell"),hasApplyPatchTool:P("openai.apply_patch"),customProviderToolNames:D.size>0?D:void 0});k.push(...Y);const W=(y=x?.strictJsonSchema)!=null?y:!0;let pe=x?.include;function Z(ee){pe==null?pe=[ee]:pe.includes(ee)||(pe=[...pe,ee])}function P(ee){return u?.find(se=>se.type==="provider"&&se.id===ee)!=null}const B=typeof x?.logprobs=="number"?x?.logprobs:x?.logprobs===!0?L2:void 0;B&&Z("message.output_text.logprobs");const F=(w=u?.find(ee=>ee.type==="provider"&&(ee.id==="openai.web_search"||ee.id==="openai.web_search_preview")))==null?void 0:w.name;F&&Z("web_search_call.action.sources"),P("openai.code_interpreter")&&Z("code_interpreter_call.outputs");const E=x?.store;E===!1&&j&&Z("reasoning.encrypted_content");const N={model:this.modelId,input:Q,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||x?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:W,name:(_=p.name)!=null?_:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...x?.textVerbosity&&{verbosity:x.textVerbosity}}},conversation:x?.conversation,max_tool_calls:x?.maxToolCalls,metadata:x?.metadata,parallel_tool_calls:x?.parallelToolCalls,previous_response_id:x?.previousResponseId,store:E,user:x?.user,instructions:x?.instructions,service_tier:x?.serviceTier,include:pe,prompt_cache_key:x?.promptCacheKey,prompt_cache_retention:x?.promptCacheRetention,safety_identifier:x?.safetyIdentifier,top_logprobs:B,truncation:x?.truncation,...j&&(x?.reasoningEffort!=null||x?.reasoningSummary!=null)&&{reasoning:{...x?.reasoningEffort!=null&&{effort:x.reasoningEffort},...x?.reasoningSummary!=null&&{summary:x.reasoningSummary}}}};j?x?.reasoningEffort==="none"&&S.supportsNonReasoningParameters||(N.temperature!=null&&(N.temperature=void 0,k.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),N.top_p!=null&&(N.top_p=void 0,k.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(x?.reasoningEffort!=null&&k.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),x?.reasoningSummary!=null&&k.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),x?.serviceTier==="flex"&&!S.supportsFlexProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete N.service_tier),x?.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete N.service_tier);const L=(b=(T=(h=u?.find(ee=>ee.type==="provider"&&ee.id==="openai.shell"))==null?void 0:h.args)==null?void 0:T.environment)==null?void 0:b.type,G=L==="containerAuto"||L==="containerReference";return{webSearchToolName:F,args:{...N,tools:A,tool_choice:O},warnings:[...k,...H],store:E,toolNameMapping:M,providerOptionsName:I,isShellProviderExecuted:G}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,m,p,f,g,v,y,w,_,h,T,b,k,S,I,x;const{args:j,warnings:M,webSearchToolName:D,toolNameMapping:A,providerOptionsName:O,isShellProviderExecuted:H}=await this.getArgs(e),Q=this.config.url({path:"/responses",modelId:this.modelId}),Y=U2(e.prompt),{responseHeaders:W,value:pe,rawValue:Z}=await Vt({url:Q,headers:Mt(this.config.headers(),e.headers),body:j,failedResponseHandler:hr,successfulResponseHandler:tr(s8),abortSignal:e.abortSignal,fetch:this.config.fetch});if(pe.error)throw new ot({message:pe.error.message,url:Q,requestBodyValues:j,statusCode:400,responseHeaders:W,responseBody:Z,isRetryable:!1});const P=[],B=[];let F=!1;for(const L of pe.output)switch(L.type){case"reasoning":{L.summary.length===0&&L.summary.push({type:"summary_text",text:""});for(const G of L.summary)P.push({type:"reasoning",text:G.text,providerMetadata:{[O]:{itemId:L.id,reasoningEncryptedContent:(t=L.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("image_generation"),result:{result:L.result}});break}case"local_shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("local_shell"),input:JSON.stringify({action:L.action}),providerMetadata:{[O]:{itemId:L.id}}});break}case"shell_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),input:JSON.stringify({action:{commands:L.action.commands}}),...H&&{providerExecuted:!0},providerMetadata:{[O]:{itemId:L.id}}});break}case"shell_call_output":{P.push({type:"tool-result",toolCallId:L.call_id,toolName:A.toCustomToolName("shell"),result:{output:L.output.map(G=>({stdout:G.stdout,stderr:G.stderr,outcome:G.outcome.type==="exit"?{type:"exit",exitCode:G.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const G of L.content){(n=(r=e.providerOptions)==null?void 0:r[O])!=null&&n.logprobs&&G.logprobs&&B.push(G.logprobs);const ee={itemId:L.id,...L.phase!=null&&{phase:L.phase},...G.annotations.length>0&&{annotations:G.annotations}};P.push({type:"text",text:G.text,providerMetadata:{[O]:ee}});for(const se of G.annotations)se.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(i=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?i:qt(),url:se.url,title:se.title}):se.type==="file_citation"?P.push({type:"source",sourceType:"document",id:(c=(l=(a=this.config).generateId)==null?void 0:l.call(a))!=null?c:qt(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[O]:{type:se.type,fileId:se.file_id,index:se.index}}}):se.type==="container_file_citation"?P.push({type:"source",sourceType:"document",id:(p=(m=(u=this.config).generateId)==null?void 0:m.call(u))!=null?p:qt(),mediaType:"text/plain",title:se.filename,filename:se.filename,providerMetadata:{[O]:{type:se.type,fileId:se.file_id,containerId:se.container_id}}}):se.type==="file_path"&&P.push({type:"source",sourceType:"document",id:(v=(g=(f=this.config).generateId)==null?void 0:g.call(f))!=null?v:qt(),mediaType:"application/octet-stream",title:se.file_id,filename:se.file_id,providerMetadata:{[O]:{type:se.type,fileId:se.file_id,index:se.index}}})}break}case"function_call":{F=!0,P.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:L.arguments,providerMetadata:{[O]:{itemId:L.id}}});break}case"custom_tool_call":{F=!0;const G=A.toCustomToolName(L.name);P.push({type:"tool-call",toolCallId:L.call_id,toolName:G,input:JSON.stringify(L.input),providerMetadata:{[O]:{itemId:L.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName(D??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName(D??"web_search"),result:z2(L.action)});break}case"mcp_call":{const G=L.approval_request_id!=null&&(y=Y[L.approval_request_id])!=null?y:L.id,ee=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:G,toolName:ee,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-result",toolCallId:G,toolName:ee,result:{type:"call",serverLabel:L.server_label,name:L.name,arguments:L.arguments,...L.output!=null?{output:L.output}:{},...L.error!=null?{error:L.error}:{}},providerMetadata:{[O]:{itemId:L.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const G=(w=L.approval_request_id)!=null?w:L.id,ee=(T=(h=(_=this.config).generateId)==null?void 0:h.call(_))!=null?T:qt(),se=`mcp.${L.name}`;P.push({type:"tool-call",toolCallId:ee,toolName:se,input:L.arguments,providerExecuted:!0,dynamic:!0}),P.push({type:"tool-approval-request",approvalId:G,toolCallId:ee});break}case"computer_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:L.status||"completed"}});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("file_search"),result:{queries:L.queries,results:(k=(b=L.results)==null?void 0:b.map(G=>({attributes:G.attributes,fileId:G.file_id,filename:G.filename,score:G.score,text:G.text})))!=null?k:null}});break}case"code_interpreter_call":{P.push({type:"tool-call",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),input:JSON.stringify({code:L.code,containerId:L.container_id}),providerExecuted:!0}),P.push({type:"tool-result",toolCallId:L.id,toolName:A.toCustomToolName("code_interpreter"),result:{outputs:L.outputs}});break}case"apply_patch_call":{P.push({type:"tool-call",toolCallId:L.call_id,toolName:A.toCustomToolName("apply_patch"),input:JSON.stringify({callId:L.call_id,operation:L.operation}),providerMetadata:{[O]:{itemId:L.id}}});break}}const E={[O]:{responseId:pe.id,...B.length>0?{logprobs:B}:{},...typeof pe.service_tier=="string"?{serviceTier:pe.service_tier}:{}}},N=pe.usage;return{content:P,finishReason:{unified:q2({finishReason:(S=pe.incomplete_details)==null?void 0:S.reason,hasFunctionCall:F}),raw:(x=(I=pe.incomplete_details)==null?void 0:I.reason)!=null?x:void 0},usage:O2(N),request:{body:j},response:{id:pe.id,timestamp:new Date(pe.created_at*1e3),modelId:pe.model,headers:W,body:Z},providerMetadata:E,warnings:M}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:i,isShellProviderExecuted:a}=await this.getArgs(e),{responseHeaders:l,value:c}=await Vt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:hr,successfulResponseHandler:Js(o8),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,m=U2(e.prompt),p=new Map;let f={unified:"other",raw:void 0},g;const v=[];let y=null;const w={},_=[];let h,T=!1;const b={};let k;return{stream:c.pipeThrough(new TransformStream({start(S){S.enqueue({type:"stream-start",warnings:r})},transform(S,I){var x,j,M,D,A,O,H,Q,Y,W,pe,Z,P,B,F,E,N,L,G,ee,se,ke,z,V,K,X,le,Te,Fe,tt,ut,Ye;if(e.includeRawChunks&&I.enqueue({type:"raw",rawValue:S.rawValue}),!S.success){f={unified:"error",raw:void 0},I.enqueue({type:"error",error:S.error});return}const $=S.value;if(D2($)){if($.item.type==="function_call")w[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="custom_tool_call"){const re=o.toCustomToolName($.item.name);w[$.output_index]={toolName:re,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:re})}else if($.item.type==="web_search_call")w[$.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")w[$.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if($.item.type==="code_interpreter_call")w[$.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!($.item.type==="mcp_call"||$.item.type==="mcp_list_tools"||$.item.type==="mcp_approval_request"))if($.item.type==="apply_patch_call"){const{call_id:re,operation:Ae}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:re,applyPatch:{hasDiff:Ae.type==="delete_file",endEmitted:Ae.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:re,toolName:o.toCustomToolName("apply_patch")}),Ae.type==="delete_file"){const yt=JSON.stringify({callId:re,operation:Ae});I.enqueue({type:"tool-input-delta",id:re,delta:yt}),I.enqueue({type:"tool-input-end",id:re})}else I.enqueue({type:"tool-input-delta",id:re,delta:`{"callId":"${qn(re)}","operation":{"type":"${qn(Ae.type)}","path":"${qn(Ae.path)}","diff":"`})}else $.item.type==="shell_call"?w[$.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:$.item.call_id}:$.item.type==="shell_call_output"||($.item.type==="message"?(_.splice(0,_.length),h=(x=$.item.phase)!=null?x:void 0,I.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[i]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):D2($)&&$.item.type==="reasoning"&&(b[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[i]:{itemId:$.item.id,reasoningEncryptedContent:(j=$.item.encrypted_content)!=null?j:null}}})))}else if(d8($)){if($.item.type==="message"){const re=(M=$.item.phase)!=null?M:h;h=void 0,I.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[i]:{itemId:$.item.id,...re!=null&&{phase:re},..._.length>0&&{annotations:_}}}})}else if($.item.type==="function_call")w[$.output_index]=void 0,T=!0,I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="custom_tool_call"){w[$.output_index]=void 0,T=!0;const re=o.toCustomToolName($.item.name);I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:re,input:JSON.stringify($.item.input),providerMetadata:{[i]:{itemId:$.item.id}}})}else if($.item.type==="web_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),result:z2($.item.action)});else if($.item.type==="computer_call")w[$.output_index]=void 0,I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$.item.status||"completed"}});else if($.item.type==="file_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:$.item.queries,results:(A=(D=$.item.results)==null?void 0:D.map(re=>({attributes:re.attributes,fileId:re.file_id,filename:re.filename,score:re.score,text:re.text})))!=null?A:null}});else if($.item.type==="code_interpreter_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:$.item.outputs}});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:$.item.result}});else if($.item.type==="mcp_call"){w[$.output_index]=void 0;const re=(O=$.item.approval_request_id)!=null?O:void 0,Ae=re!=null&&(Q=(H=p.get(re))!=null?H:m[re])!=null?Q:$.item.id,yt=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:Ae,toolName:yt,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:Ae,toolName:yt,result:{type:"call",serverLabel:$.item.server_label,name:$.item.name,arguments:$.item.arguments,...$.item.output!=null?{output:$.item.output}:{},...$.item.error!=null?{error:$.item.error}:{}},providerMetadata:{[i]:{itemId:$.item.id}}})}else if($.item.type==="mcp_list_tools")w[$.output_index]=void 0;else if($.item.type==="apply_patch_call"){const re=w[$.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&$.item.operation.type!=="delete_file"&&(re.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:qn($.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0),re&&$.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$.item.call_id,operation:$.item.operation}),providerMetadata:{[i]:{itemId:$.item.id}}}),w[$.output_index]=void 0}else if($.item.type==="mcp_approval_request"){w[$.output_index]=void 0;const re=(pe=(W=(Y=u.config).generateId)==null?void 0:W.call(Y))!=null?pe:qt(),Ae=(Z=$.item.approval_request_id)!=null?Z:$.item.id;p.set(Ae,re);const yt=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:re,toolName:yt,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:Ae,toolCallId:re})}else if($.item.type==="local_shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$.item.action.commands}}),...a&&{providerExecuted:!0},providerMetadata:{[i]:{itemId:$.item.id}}});else if($.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:$.item.output.map(re=>({stdout:re.stdout,stderr:re.stderr,outcome:re.outcome.type==="exit"?{type:"exit",exitCode:re.outcome.exit_code}:{type:"timeout"}}))}});else if($.item.type==="reasoning"){const re=b[$.item.id],Ae=Object.entries(re.summaryParts).filter(([yt,Dt])=>Dt==="active"||Dt==="can-conclude").map(([yt])=>yt);for(const yt of Ae)I.enqueue({type:"reasoning-end",id:`${$.item.id}:${yt}`,providerMetadata:{[i]:{itemId:$.item.id,reasoningEncryptedContent:(P=$.item.encrypted_content)!=null?P:null}}});delete b[$.item.id]}}else if(h8($)){const re=w[$.output_index];re!=null&&I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:$.delta})}else if(m8($)){const re=w[$.output_index];re!=null&&I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:$.delta})}else if(v8($)){const re=w[$.output_index];re?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:qn($.delta)}),re.applyPatch.hasDiff=!0)}else if(w8($)){const re=w[$.output_index];re?.applyPatch&&!re.applyPatch.endEmitted&&(re.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:qn($.diff)}),re.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:re.toolCallId}),re.applyPatch.endEmitted=!0)}else if(g8($))I.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(y8($)){const re=w[$.output_index];re!=null&&I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:qn($.delta)})}else if(_8($)){const re=w[$.output_index];re!=null&&(I.enqueue({type:"tool-input-delta",id:re.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:re.toolCallId}),I.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$.code,containerId:re.codeInterpreter.containerId}),providerExecuted:!0}))}else if(f8($))y=$.response.id,I.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(u8($))I.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(F=(B=e.providerOptions)==null?void 0:B[i])!=null&&F.logprobs&&$.logprobs&&v.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const re=b[$.item_id];re.summaryParts[$.summary_index]="active";for(const Ae of Object.keys(re.summaryParts))re.summaryParts[Ae]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${Ae}`,providerMetadata:{[i]:{itemId:$.item_id}}}),re.summaryParts[Ae]="concluded");I.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id,reasoningEncryptedContent:(N=(E=b[$.item_id])==null?void 0:E.encryptedContent)!=null?N:null}}})}}else $.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[i]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[i]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude":p8($)?(f={unified:q2({finishReason:(L=$.response.incomplete_details)==null?void 0:L.reason,hasFunctionCall:T}),raw:(ee=(G=$.response.incomplete_details)==null?void 0:G.reason)!=null?ee:void 0},g=$.response.usage,typeof $.response.service_tier=="string"&&(k=$.response.service_tier)):b8($)?(_.push($.annotation),$.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(z=(ke=(se=u.config).generateId)==null?void 0:ke.call(se))!=null?z:qt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(X=(K=(V=u.config).generateId)==null?void 0:K.call(V))!=null?X:qt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}}):$.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Fe=(Te=(le=u.config).generateId)==null?void 0:Te.call(le))!=null?Fe:qt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,containerId:$.annotation.container_id}}}):$.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(Ye=(ut=(tt=u.config).generateId)==null?void 0:ut.call(tt))!=null?Ye:qt(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[i]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):k8($)&&I.enqueue({type:"error",error:$})},flush(S){const I={[i]:{responseId:y,...v.length>0?{logprobs:v}:{},...k!==void 0?{serviceTier:k}:{}}};S.enqueue({type:"finish",finishReason:f,usage:O2(g),providerMetadata:I})}})),request:{body:t},response:{headers:l}}}};function u8(e){return e.type==="response.output_text.delta"}function d8(e){return e.type==="response.output_item.done"}function p8(e){return e.type==="response.completed"||e.type==="response.incomplete"}function f8(e){return e.type==="response.created"}function h8(e){return e.type==="response.function_call_arguments.delta"}function m8(e){return e.type==="response.custom_tool_call_input.delta"}function g8(e){return e.type==="response.image_generation_call.partial_image"}function y8(e){return e.type==="response.code_interpreter_call_code.delta"}function _8(e){return e.type==="response.code_interpreter_call_code.done"}function v8(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function w8(e){return e.type==="response.apply_patch_call_operation_diff.done"}function D2(e){return e.type==="response.output_item.added"}function b8(e){return e.type==="response.output_text.annotation.added"}function k8(e){return e.type==="error"}function z2(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 qn(e){return JSON.stringify(e).slice(1,-1)}var C8=ve(()=>_e(C({instructions:d().nullish(),speed:U().min(.25).max(4).default(1).nullish()}))),T8=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:i}){const a=[],l=await Ar({provider:"openai",providerOptions:i,schema:C8}),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",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&&a.push({type:"unsupported",feature:"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 Vt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),body:s,failedResponseHandler:hr,successfulResponseHandler:r4(),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}}}},S8=ve(()=>_e(C({text:d(),language:d().nullish(),duration:U().nullish(),words:q(C({word:d(),start:U(),end:U()})).nullish(),segments:q(C({id:U(),seek:U(),start:U(),end:U(),text:d(),tokens:q(U()),temperature:U(),avg_logprob:U(),compression_ratio:U(),no_speech_prob:U()})).nullish()}))),I8=ve(()=>_e(C({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:U().min(0).max(1).default(0).optional(),timestampGranularities:q(me(["word","segment"])).default(["segment"]).optional()}))),F2={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"},x8=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 Ar({provider:"openai",providerOptions:r,schema:I8}),s=new FormData,i=e instanceof Uint8Array?new Blob([e]):new Blob([Qn(e)]);s.append("model",this.modelId);const a=o9(t);if(s.append("file",new File([i],"audio",{type:t}),`audio.${a}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const m of u)s.append(`${c}[]`,String(m));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,i,a,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:m}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:g}=await jf({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Mt(this.config.headers(),e.headers),formData:u,failedResponseHandler:hr,successfulResponseHandler:tr(S8),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=p.language!=null&&p.language in F2?F2[p.language]:void 0;return{text:p.text,segments:(a=(i=(o=p.segments)==null?void 0:o.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?i:(s=p.words)==null?void 0:s.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?a:[],language:v,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:m,response:{timestamp:c,modelId:this.modelId,headers:f,body:g}}}},E8="3.0.41";function V2(e={}){var t,r;const n=(t=zf(to({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>nn({Authorization:`Bearer ${n9({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${E8}`),i=v=>new sI(v,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),a=v=>new cI(v,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=v=>new pI(v,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=v=>new gI(v,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=v=>new x8(v,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),m=v=>new T8(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 c8(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=i,g.completion=a,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=t8,g}V2();var Z2="vercel.ai.error",$8=Symbol.for(Z2),B2,R8=class cv extends Error{constructor({name:t,message:r,cause:n}){super(r),this[B2]=!0,this.name=t,this.cause=n}static isInstance(t){return cv.hasMarker(t,Z2)}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}};B2=$8;var Tt=R8,H2="AI_APICallError",J2=`vercel.ai.error.${H2}`,P8=Symbol.for(J2),G2,Ur=class extends Tt{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:H2,message:e,cause:i}),this[G2]=!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 Tt.hasMarker(e,J2)}};G2=P8;var W2="AI_EmptyResponseBodyError",K2=`vercel.ai.error.${W2}`,N8=Symbol.for(K2),Y2,M8=class extends Tt{constructor({message:e="Empty response body"}={}){super({name:W2,message:e}),this[Y2]=!0}static isInstance(e){return Tt.hasMarker(e,K2)}};Y2=N8;function Q2(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var X2="AI_InvalidArgumentError",eg=`vercel.ai.error.${X2}`,O8=Symbol.for(eg),tg,rg=class extends Tt{constructor({message:e,cause:t,argument:r}){super({name:X2,message:e,cause:t}),this[tg]=!0,this.argument=r}static isInstance(e){return Tt.hasMarker(e,eg)}};tg=O8;var ng="AI_InvalidResponseDataError",og=`vercel.ai.error.${ng}`,A8=Symbol.for(og),sg,ag=class extends Tt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:ng,message:t}),this[sg]=!0,this.data=e}static isInstance(e){return Tt.hasMarker(e,og)}};sg=A8;var ig="AI_JSONParseError",lg=`vercel.ai.error.${ig}`,q8=Symbol.for(lg),cg,Ea=class extends Tt{constructor({text:e,cause:t}){super({name:ig,message:`JSON parsing failed: Text: ${e}.
|
|
80
|
+
Error message: ${Q2(t)}`,cause:t}),this[cg]=!0,this.text=e}static isInstance(e){return Tt.hasMarker(e,lg)}};cg=q8;var ug="AI_LoadAPIKeyError",dg=`vercel.ai.error.${ug}`,L8=Symbol.for(dg),pg,$a=class extends Tt{constructor({message:e}){super({name:ug,message:e}),this[pg]=!0}static isInstance(e){return Tt.hasMarker(e,dg)}};pg=L8;var fg="AI_NoSuchModelError",hg=`vercel.ai.error.${fg}`,j8=Symbol.for(hg),mg,gg=class extends Tt{constructor({errorName:e=fg,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[mg]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return Tt.hasMarker(e,hg)}};mg=j8;var yg="AI_TypeValidationError",_g=`vercel.ai.error.${yg}`,U8=Symbol.for(_g),vg,D8=class td extends Tt{constructor({value:t,cause:r}){super({name:yg,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
81
|
+
Error message: ${Q2(r)}`,cause:r}),this[vg]=!0,this.value=t}static isInstance(t){return Tt.hasMarker(t,_g)}static wrap({value:t,cause:r}){return td.isInstance(r)&&r.value===t?r:new td({value:t,cause:r})}};vg=U8;var cs=D8,wg="AI_UnsupportedFunctionalityError",bg=`vercel.ai.error.${wg}`,z8=Symbol.for(bg),kg,Cg=class extends Tt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:wg,message:t}),this[kg]=!0,this.functionality=e}static isInstance(e){return Tt.hasMarker(e,bg)}};kg=z8;function Tg(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Ra(e){return Object.fromEntries([...e.headers])}var F8=({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 rg({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Pa=F8();function ru(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var V8=["fetch failed","failed to fetch"];function Z8({error:e,url:t,requestBodyValues:r}){if(ru(e))return e;if(e instanceof TypeError&&V8.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new Ur({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function B8(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 H8(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 Sg(e,...t){const r=new Headers(H8(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var J8="3.0.18";function G8({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new $a({message:`${n} API key must be a string.`});if(typeof process>"u")throw new $a({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 $a({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new $a({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var W8=/"__proto__"\s*:/,K8=/"constructor"\s*:/;function Ig(e){const t=JSON.parse(e);return t===null||typeof t!="object"||W8.test(e)===!1&&K8.test(e)===!1?t:Y8(t)}function Y8(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function nu(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Ig(e)}try{return Ig(e)}finally{Error.stackTraceLimit=t}}var ou=Symbol.for("vercel.ai.validator");function Q8(e){return{[ou]:!0,validate:e}}function X8(e){return typeof e=="object"&&e!==null&&ou in e&&e[ou]===!0&&"validate"in e}function ex(e){return X8(e)?e:typeof e=="function"?e():tx(e)}function tx(e){return Q8(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new cs({value:t,cause:r.issues})}})}async function rx({value:e,schema:t}){const r=await us({value:e,schema:t});if(!r.success)throw cs.wrap({value:e,cause:r.error});return r.value}async function us({value:e,schema:t}){const r=ex(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:cs.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:cs.wrap({value:e,cause:n}),rawValue:e}}}async function nx({text:e,schema:t}){try{const r=nu(e);return t==null?r:rx({value:r,schema:t})}catch(r){throw Ea.isInstance(r)||cs.isInstance(r)?r:new Ea({text:e,cause:r})}}async function xg({text:e,schema:t}){try{const r=nu(e);return t==null?{success:!0,value:r,rawValue:r}:await us({value:r,schema:t})}catch(r){return{success:!1,error:Ea.isInstance(r)?r:new Ea({text:e,cause:r}),rawValue:void 0}}}function Eg(e){try{return nu(e),!0}catch{return!1}}function ox({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Kn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await xg({text:r,schema:t}))}}))}async function $g({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await us({value:t[e],schema:r});if(!n.success)throw new rg({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var sx=()=>globalThis.fetch,Rg=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>ax({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),ax=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=sx()})=>{try{const a=await i(e,{method:"POST",headers:Sg(t,`ai-sdk/provider-utils/${J8}`,B8()),body:r.content,signal:s}),l=Ra(a);if(!a.ok){let c;try{c=await o({response:a,url:e,requestBodyValues:r.values})}catch(u){throw ru(u)||Ur.isInstance(u)?u:new Ur({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&&(ru(c)||Ur.isInstance(c))?c:new Ur({message:"Failed to process successful response",cause:c,statusCode:a.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(a){throw Z8({error:a,url:e,requestBodyValues:r.values})}},ix=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const i=await n.text(),a=Ra(n);if(i.trim()==="")return{responseHeaders:a,value:new Ur({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})};try{const l=await nx({text:i,schema:e});return{responseHeaders:a,value:new Ur({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 Ur({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:r?.(n)})}}},lx=e=>async({response:t})=>{const r=Ra(t);if(t.body==null)throw new M8({});return{responseHeaders:r,value:ox({stream:t.body,schema:e})}},cx=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await xg({text:o,schema:e}),i=Ra(t);if(!s.success)throw new Ur({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}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:ux}=globalThis;function dx(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return ux(t)}function px(e){return e instanceof Uint8Array?dx(e):e}function fx(e){return e?.replace(/\/$/,"")}function ds(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function hx(e){const t=[];for(const{role:r,content:n,...o}of e){const s=ds({...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,...ds(n[0])});break}t.push({role:"user",content:n.map(i=>{const a=ds(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,${px(i.data)}`},...a}}else throw new Cg({functionality:`file part media type ${i.mediaType}`})}}),...s});break}case"assistant":{let i="";const a=[];for(const l of n){const c=ds(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=ds(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 Pg({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 Ng(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 su=C({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),mx=C({error:C({message:d(),type:d().nullish(),param:bt().nullish(),code:ae([d(),U()]).nullish()})}),gx={errorSchema:mx,errorToMessage:e=>e.error.message};function yx({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 Cg({functionality:`tool choice type: ${s}`})}}}var _x=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:gx;this.chunkSchema=wx(o.errorSchema),this.failedResponseHandler=ix(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:i,providerOptions:a,stopSequences:l,responseFormat:c,seed:u,toolChoice:m,tools:p}){var f,g,v,y;const w=[],_=Object.assign((f=await $g({provider:"openai-compatible",providerOptions:a,schema:su}))!=null?f:{},(g=await $g({provider:this.providerOptionsName,providerOptions:a,schema:su}))!=null?g:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:h,toolChoice:T,toolWarnings:b}=yx({tools:p,toolChoice:m});return{args:{model:this.modelId,user:_.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((y=a?.[this.providerOptionsName])!=null?y:{}).filter(([k])=>!Object.keys(su.shape).includes(k))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:hx(e),tools:h,tool_choice:T},warnings:[...w,...b]}}async doGenerate(e){var t,r,n,o,s,i,a,l,c,u,m,p,f,g,v,y,w;const{args:_,warnings:h}=await this.getArgs({...e}),T=JSON.stringify(_),{responseHeaders:b,value:k,rawValue:S}=await Rg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Tg(this.config.headers(),e.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:cx(vx),abortSignal:e.abortSignal,fetch:this.config.fetch}),I=k.choices[0],x=[],j=I.message.content;j!=null&&j.length>0&&x.push({type:"text",text:j});const M=(t=I.message.reasoning_content)!=null?t:I.message.reasoning;if(M!=null&&M.length>0&&x.push({type:"reasoning",text:M}),I.message.tool_calls!=null)for(const O of I.message.tool_calls)x.push({type:"tool-call",toolCallId:(r=O.id)!=null?r:Pa(),toolName:O.function.name,input:O.function.arguments});const D={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:S}))},A=(s=k.usage)==null?void 0:s.completion_tokens_details;return A?.accepted_prediction_tokens!=null&&(D[this.providerOptionsName].acceptedPredictionTokens=A?.accepted_prediction_tokens),A?.rejected_prediction_tokens!=null&&(D[this.providerOptionsName].rejectedPredictionTokens=A?.rejected_prediction_tokens),{content:x,finishReason:Ng(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:(m=(u=k.usage)==null?void 0:u.total_tokens)!=null?m:void 0,reasoningTokens:(g=(f=(p=k.usage)==null?void 0:p.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:void 0,cachedInputTokens:(w=(y=(v=k.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:D,request:{body:T},response:{...Pg(k),headers:b,body:S},warnings:h}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:i,value:a}=await Rg({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Tg(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:lx(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:a.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:n})},transform(v,y){var w,_,h,T,b,k,S,I,x,j,M,D,A;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",y.enqueue({type:"error",error:v.error});return}const O=v.value;if(s?.processChunk(v.rawValue),"error"in O){c="error",y.enqueue({type:"error",error:O.error.message});return}if(m&&(m=!1,y.enqueue({type:"response-metadata",...Pg(O)})),O.usage!=null){const{prompt_tokens:W,completion_tokens:pe,total_tokens:Z,prompt_tokens_details:P,completion_tokens_details:B}=O.usage;u.promptTokens=W??void 0,u.completionTokens=pe??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),P?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=P?.cached_tokens)}const H=O.choices[0];if(H?.finish_reason!=null&&(c=Ng(H.finish_reason)),H?.delta==null)return;const Q=H.delta,Y=(w=Q.reasoning_content)!=null?w:Q.reasoning;if(Y&&(f||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),f=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Y})),Q.content&&(g||(y.enqueue({type:"text-start",id:"txt-0"}),g=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:Q.content})),Q.tool_calls!=null)for(const W of Q.tool_calls){const pe=W.index;if(l[pe]==null){if(W.id==null)throw new ag({data:W,message:"Expected 'id' to be a string."});if(((_=W.function)==null?void 0:_.name)==null)throw new ag({data:W,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:W.id,toolName:W.function.name}),l[pe]={id:W.id,type:"function",function:{name:W.function.name,arguments:(h=W.function.arguments)!=null?h:""},hasFinished:!1};const P=l[pe];((T=P.function)==null?void 0:T.name)!=null&&((b=P.function)==null?void 0:b.arguments)!=null&&(P.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:P.id,delta:P.function.arguments}),Eg(P.function.arguments)&&(y.enqueue({type:"tool-input-end",id:P.id}),y.enqueue({type:"tool-call",toolCallId:(k=P.id)!=null?k:Pa(),toolName:P.function.name,input:P.function.arguments}),P.hasFinished=!0));continue}const Z=l[pe];Z.hasFinished||(((S=W.function)==null?void 0:S.arguments)!=null&&(Z.function.arguments+=(x=(I=W.function)==null?void 0:I.arguments)!=null?x:""),y.enqueue({type:"tool-input-delta",id:Z.id,delta:(j=W.function.arguments)!=null?j:""}),((M=Z.function)==null?void 0:M.name)!=null&&((D=Z.function)==null?void 0:D.arguments)!=null&&Eg(Z.function.arguments)&&(y.enqueue({type:"tool-input-end",id:Z.id}),y.enqueue({type:"tool-call",toolCallId:(A=Z.id)!=null?A:Pa(),toolName:Z.function.name,input:Z.function.arguments}),Z.hasFinished=!0))}},flush(v){var y,w,_,h,T,b;f&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),g&&v.enqueue({type:"text-end",id:"txt-0"});for(const S of l.filter(I=>!I.hasFinished))v.enqueue({type:"tool-input-end",id:S.id}),v.enqueue({type:"tool-call",toolCallId:(y=S.id)!=null?y:Pa(),toolName:S.function.name,input:S.function.arguments});const k={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(k[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(k[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(h=u.totalTokens)!=null?h:void 0,reasoningTokens:(T=u.completionTokensDetails.reasoningTokens)!=null?T:void 0,cachedInputTokens:(b=u.promptTokensDetails.cachedTokens)!=null?b:void 0},providerMetadata:k})}})),request:{body:o},response:{headers:i}}}},Mg=C({prompt_tokens:U().nullish(),completion_tokens:U().nullish(),total_tokens:U().nullish(),prompt_tokens_details:C({cached_tokens:U().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:U().nullish(),accepted_prediction_tokens:U().nullish(),rejected_prediction_tokens:U().nullish()}).nullish()}).nullish(),vx=C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({message:C({role:R("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({id:d().nullish(),function:C({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:Mg}),wx=e=>ae([C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({delta:C({role:me(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(C({index:U(),id:d().nullish(),function:C({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:Mg}),e]);C({echo:he().optional(),logitBias:ye(d(),U()).optional(),suffix:d().optional(),user:d().optional()});var bx=C({prompt_tokens:U(),completion_tokens:U(),total_tokens:U()});C({id:d().nullish(),created:U().nullish(),model:d().nullish(),choices:q(C({text:d(),finish_reason:d()})),usage:bx.nullish()}),C({dimensions:U().optional(),user:d().optional()}),C({data:q(C({embedding:q(U())})),usage:C({prompt_tokens:U()}).nullish(),providerMetadata:ye(d(),ye(d(),bt())).optional()}),C({data:q(C({b64_json:d()}))});var Og=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},kx={extractMetadata:async({parsedBody:e})=>{const t=await us({value:e,schema:Cx});return!t.success||t.value.usage==null?void 0:Og(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await us({value:t,schema:Tx});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>Og(e)}}},Ag=C({prompt_cache_hit_tokens:U().nullish(),prompt_cache_miss_tokens:U().nullish()}),Cx=C({usage:Ag.nullish()}),Tx=C({choices:q(C({finish_reason:d().nullish()})).nullish(),usage:Ag.nullish()}),Sx="1.0.30";function qg(e={}){var t;const r=fx((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>Sg({Authorization:`Bearer ${G8({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${Sx}`);class o extends _x{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=a=>new o(a,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:kx}),i=a=>s(a);return i.languageModel=s,i.chat=s,i.textEmbeddingModel=a=>{throw new gg({modelId:a,modelType:"textEmbeddingModel"})},i.imageModel=a=>{throw new gg({modelId:a,modelType:"imageModel"})},i}qg();const Ix=(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})},xx=(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 Ex{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=xx("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=Nn.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];Ix("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 Na(e){return!!e._zod}function ln(e,t){return Na(e)?Xd(e,t):e.safeParse(t)}function Lg(e){if(!e)return;let t;if(Na(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function $x(e){if(Na(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 Ln(e){return e==="completed"||e==="failed"||e==="cancelled"}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function jg(e){const r=Lg(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=$x(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ug(e,t){const r=ln(e,t);if(!r.success)throw r.error;return r.data}const Rx=6e4;class Px{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(oc,r=>{this._oncancel(r)}),this.setNotificationHandler(ac,r=>{this._onprogress(r)}),this.setRequestHandler(sc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ic,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new be(xe.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(cc,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){const l=a.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),a.type==="response")u(l);else{const m=l,p=new be(m.error.code,m.error.message,m.error.data);u(p)}else{const m=a.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${c}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}const i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new be(xe.InvalidParams,`Task not found: ${s}`);if(!Ln(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Ln(i.status)){const a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Pn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(uc,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 be(xe.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(pc,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new be(xe.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ln(o.status))throw new be(xe.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 be(xe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof be?o:new be(xe.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),be.fromError(xe.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),Yo(s)||Y5(s)?this._onresponse(s):tc(s)?this._onrequest(s,i):K5(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=be.fromError(xe.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?.[Pn]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:xe.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):o?.send(u).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);const a=W5(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const m={relatedRequestId:t.id};s&&(m.relatedTask={taskId:s}),await this.notification(u,m)},sendRequest:async(u,m,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:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(i.signal.aborted)return;const m={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)},async u=>{if(i.signal.aborted)return;const m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:xe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},o?.sessionId):await o?.send(m)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Yo(t))n(t);else{const i=new be(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(Yo(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),Yo(t))o(t);else{const i=be.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 be?i:new be(xe.InternalError,String(i))}}return}let s;try{const i=await this.request(t,rs,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new be(xe.InternalError,"Task creation did not return a task");for(;;){const a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Ln(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new be(xe.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new be(xe.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 be?i:new be(xe.InternalError,String(i))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{const m=_=>{u(_)};if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(_){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}}),a&&(f.params={...f.params,task:a}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Pn]: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:i}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const h=_ instanceof be?_:new be(xe.RequestTimeout,String(_));u(h)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{const h=ln(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??Rx,y=()=>g(be.fromError(xe.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(p,v,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const _=h=>{const T=this._responseHandlers.get(p);T?T(h):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(h=>{this._cleanupTimeout(p),u(h)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),u(_)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},lc,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},dc,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},hT,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||{},[Pn]: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||{},[Pn]: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||{},[Pn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){const n=jg(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const i=Ug(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=jg(t);this._notificationHandlers.set(n,o=>{const s=Ug(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"&&tc(o.message)){const s=o.message.id,i=this._requestResolvers.get(s);i?(i(new be(xe.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 be(xe.InvalidRequest,"Request cancelled"));return}const i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new be(xe.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 be(xe.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=ma.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Ln(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 be(xe.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Ln(a.status))throw new be(xe.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=ma.parse({method:"notifications/tasks/status",params:l});await this.notification(c),Ln(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function Dg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Nx(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];Dg(i)&&Dg(s)?r[o]={...i,...s}:r[o]=s}return r}var Ma={exports:{}},au={},Dr={},jn={},iu={},lu={},cu={},zg;function Oa(){return zg||(zg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(_){if(super(),!e.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((h,T)=>`${h}${T}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((h,T)=>(T instanceof r&&(h[T.str]=(h[T.str]||0)+1),h),{})}}e._Code=n,e.nil=new n("");function o(w,..._){const h=[w[0]];let T=0;for(;T<_.length;)a(h,_[T]),h.push(w[++T]);return new n(h)}e._=o;const s=new n("+");function i(w,..._){const h=[f(w[0])];let T=0;for(;T<_.length;)h.push(s),a(h,_[T]),h.push(s,f(w[++T]));return l(h),new n(h)}e.str=i;function a(w,_){_ instanceof n?w.push(..._._items):_ instanceof r?w.push(_):w.push(m(_))}e.addCodeArg=a;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()?_:i`${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})(cu)),cu}var uu={},Fg;function Vg(){return Fg||(Fg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Oa();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,m;if(!((m=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||m===void 0)&&m.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:m}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${m}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?i:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var m;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const 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=a})(uu)),uu}var Zg;function Re(){return Zg||(Zg=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=Oa(),r=Vg();var n=Oa();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=Vg();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(E,N){return this}}class i extends s{constructor(E,N,L){super(),this.varKind=E,this.name=N,this.rhs=L}render({es5:E,_n:N}){const L=E?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${L} ${this.name}${G};`+N}optimizeNames(E,N){if(E[this.name.str])return this.rhs&&(this.rhs=O(this.rhs,E,N)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(E,N,L){super(),this.lhs=E,this.rhs=N,this.sideEffects=L}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,N){if(!(this.lhs instanceof t.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,E,N),this}get names(){const E=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(E,this.rhs)}}class l extends a{constructor(E,N,L,G){super(E,L,G),this.op=N}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends s{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class m extends s{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class p extends s{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,N){return this.code=O(this.code,E,N),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends s{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((N,L)=>N+L.render(E),"")}optimizeNodes(){const{nodes:E}=this;let N=E.length;for(;N--;){const L=E[N].optimizeNodes();Array.isArray(L)?E.splice(N,1,...L):L?E[N]=L:E.splice(N,1)}return E.length>0?this:void 0}optimizeNames(E,N){const{nodes:L}=this;let G=L.length;for(;G--;){const ee=L[G];ee.optimizeNames(E,N)||(H(E,ee.names),L.splice(G,1))}return L.length>0?this:void 0}get names(){return this.nodes.reduce((E,N)=>D(E,N.names),{})}}class g extends f{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class v extends f{}class y extends g{}y.kind="else";class w extends g{constructor(E,N){super(N),this.condition=E}render(E){let N=`if(${this.condition})`+super.render(E);return this.else&&(N+="else "+this.else.render(E)),N}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let N=this.else;if(N){const L=N.optimizeNodes();N=this.else=Array.isArray(L)?new y(L):L}if(N)return E===!1?N instanceof w?N:N.nodes:this.nodes.length?this:new w(Q(E),N instanceof w?[N]:N.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,N){var L;if(this.else=(L=this.else)===null||L===void 0?void 0:L.optimizeNames(E,N),!!(super.optimizeNames(E,N)||this.else))return this.condition=O(this.condition,E,N),this}get names(){const E=super.names;return A(E,this.condition),this.else&&D(E,this.else.names),E}}w.kind="if";class _ extends g{}_.kind="for";class h extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,N){if(super.optimizeNames(E,N))return this.iteration=O(this.iteration,E,N),this}get names(){return D(super.names,this.iteration.names)}}class T extends _{constructor(E,N,L,G){super(),this.varKind=E,this.name=N,this.from=L,this.to=G}render(E){const N=E.es5?r.varKinds.var:this.varKind,{name:L,from:G,to:ee}=this;return`for(${N} ${L}=${G}; ${L}<${ee}; ${L}++)`+super.render(E)}get names(){const E=A(super.names,this.from);return A(E,this.to)}}class b extends _{constructor(E,N,L,G){super(),this.loop=E,this.varKind=N,this.name=L,this.iterable=G}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,N){if(super.optimizeNames(E,N))return this.iterable=O(this.iterable,E,N),this}get names(){return D(super.names,this.iterable.names)}}class k extends g{constructor(E,N,L){super(),this.name=E,this.args=N,this.async=L}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}k.kind="func";class S extends f{render(E){return"return "+super.render(E)}}S.kind="return";class I extends g{render(E){let N="try"+super.render(E);return this.catch&&(N+=this.catch.render(E)),this.finally&&(N+=this.finally.render(E)),N}optimizeNodes(){var E,N;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(N=this.finally)===null||N===void 0||N.optimizeNodes(),this}optimizeNames(E,N){var L,G;return super.optimizeNames(E,N),(L=this.catch)===null||L===void 0||L.optimizeNames(E,N),(G=this.finally)===null||G===void 0||G.optimizeNames(E,N),this}get names(){const E=super.names;return this.catch&&D(E,this.catch.names),this.finally&&D(E,this.finally.names),E}}class x extends g{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}x.kind="catch";class j extends g{render(E){return"finally"+super.render(E)}}j.kind="finally";class M{constructor(E,N={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...N,_n:N.lines?`
|
|
82
|
+
`:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,N){const L=this._extScope.value(E,N);return(this._values[L.prefix]||(this._values[L.prefix]=new Set)).add(L),L}getScopeValue(E,N){return this._extScope.getValue(E,N)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,N,L,G){const ee=this._scope.toName(N);return L!==void 0&&G&&(this._constants[ee.str]=L),this._leafNode(new i(E,ee,L)),ee}const(E,N,L){return this._def(r.varKinds.const,E,N,L)}let(E,N,L){return this._def(r.varKinds.let,E,N,L)}var(E,N,L){return this._def(r.varKinds.var,E,N,L)}assign(E,N,L){return this._leafNode(new a(E,N,L))}add(E,N){return this._leafNode(new l(E,e.operators.ADD,N))}code(E){return typeof E=="function"?E():E!==t.nil&&this._leafNode(new p(E)),this}object(...E){const N=["{"];for(const[L,G]of E)N.length>1&&N.push(","),N.push(L),(L!==G||this.opts.es5)&&(N.push(":"),(0,t.addCodeArg)(N,G));return N.push("}"),new t._Code(N)}if(E,N,L){if(this._blockNode(new w(E)),N&&L)this.code(N).else().code(L).endIf();else if(N)this.code(N).endIf();else if(L)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new w(E))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(E,N){return this._blockNode(E),N&&this.code(N).endFor(),this}for(E,N){return this._for(new h(E),N)}forRange(E,N,L,G,ee=this.opts.es5?r.varKinds.var:r.varKinds.let){const se=this._scope.toName(E);return this._for(new T(ee,se,N,L),()=>G(se))}forOf(E,N,L,G=r.varKinds.const){const ee=this._scope.toName(E);if(this.opts.es5){const se=N instanceof t.Name?N:this.var("_arr",N);return this.forRange("_i",0,(0,t._)`${se}.length`,ke=>{this.var(ee,(0,t._)`${se}[${ke}]`),L(ee)})}return this._for(new b("of",G,ee,N),()=>L(ee))}forIn(E,N,L,G=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,t._)`Object.keys(${N})`,L);const ee=this._scope.toName(E);return this._for(new b("in",G,ee,N),()=>L(ee))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const N=new S;if(this._blockNode(N),this.code(E),N.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(S)}try(E,N,L){if(!N&&!L)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new I;if(this._blockNode(G),this.code(E),N){const ee=this.name("e");this._currNode=G.catch=new x(ee),N(ee)}return L&&(this._currNode=G.finally=new j,this.code(L)),this._endBlockNode(x,j)}throw(E){return this._leafNode(new m(E))}block(E,N){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(N),this}endBlock(E){const N=this._blockStarts.pop();if(N===void 0)throw new Error("CodeGen: not in self-balancing block");const L=this._nodes.length-N;if(L<0||E!==void 0&&L!==E)throw new Error(`CodeGen: wrong number of nodes: ${L} vs ${E} expected`);return this._nodes.length=N,this}func(E,N=t.nil,L,G){return this._blockNode(new k(E,N,L)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,N){const L=this._currNode;if(L instanceof E||N&&L instanceof N)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${N?`${E.kind}/${N.kind}`:E.kind}"`)}_elseNode(E){const N=this._currNode;if(!(N instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=N.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const N=this._nodes;N[N.length-1]=E}}e.CodeGen=M;function D(F,E){for(const N in E)F[N]=(F[N]||0)+(E[N]||0);return F}function A(F,E){return E instanceof t._CodeOrName?D(F,E.names):F}function O(F,E,N){if(F instanceof t.Name)return L(F);if(!G(F))return F;return new t._Code(F._items.reduce((ee,se)=>(se instanceof t.Name&&(se=L(se)),se instanceof t._Code?ee.push(...se._items):ee.push(se),ee),[]));function L(ee){const se=N[ee.str];return se===void 0||E[ee.str]!==1?ee:(delete E[ee.str],se)}function G(ee){return ee instanceof t._Code&&ee._items.some(se=>se instanceof t.Name&&E[se.str]===1&&N[se.str]!==void 0)}}function H(F,E){for(const N in E)F[N]=(F[N]||0)-(E[N]||0)}function Q(F){return typeof F=="boolean"||typeof F=="number"||F===null?!F:(0,t._)`!${B(F)}`}e.not=Q;const Y=P(e.operators.AND);function W(...F){return F.reduce(Y)}e.and=W;const pe=P(e.operators.OR);function Z(...F){return F.reduce(pe)}e.or=Z;function P(F){return(E,N)=>E===t.nil?N:N===t.nil?E:(0,t._)`${B(E)} ${F} ${B(N)}`}function B(F){return F instanceof t.Name?F:(0,t._)`(${F})`}})(lu)),lu}var Pe={},Bg;function Le(){if(Bg)return Pe;Bg=1,Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.checkStrictMode=Pe.getErrorPath=Pe.Type=Pe.useFunc=Pe.setEvaluated=Pe.evaluatedPropsToName=Pe.mergeEvaluated=Pe.eachItem=Pe.unescapeJsonPointer=Pe.escapeJsonPointer=Pe.escapeFragment=Pe.unescapeFragment=Pe.schemaRefOrVal=Pe.schemaHasRulesButRef=Pe.schemaHasRules=Pe.checkUnknownRules=Pe.alwaysValidSchema=Pe.toHash=void 0;const e=Re(),t=Oa();function r(b){const k={};for(const S of b)k[S]=!0;return k}Pe.toHash=r;function n(b,k){return typeof k=="boolean"?k:Object.keys(k).length===0?!0:(o(b,k),!s(k,b.self.RULES.all))}Pe.alwaysValidSchema=n;function o(b,k=b.schema){const{opts:S,self:I}=b;if(!S.strictSchema||typeof k=="boolean")return;const x=I.RULES.keywords;for(const j in k)x[j]||T(b,`unknown keyword: "${j}"`)}Pe.checkUnknownRules=o;function s(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(k[S])return!0;return!1}Pe.schemaHasRules=s;function i(b,k){if(typeof b=="boolean")return!b;for(const S in b)if(S!=="$ref"&&k.all[S])return!0;return!1}Pe.schemaHasRulesButRef=i;function a({topSchemaRef:b,schemaPath:k},S,I,x){if(!x){if(typeof S=="number"||typeof S=="boolean")return S;if(typeof S=="string")return(0,e._)`${S}`}return(0,e._)`${b}${k}${(0,e.getProperty)(I)}`}Pe.schemaRefOrVal=a;function l(b){return m(decodeURIComponent(b))}Pe.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}Pe.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}Pe.escapeJsonPointer=u;function m(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Pe.unescapeJsonPointer=m;function p(b,k){if(Array.isArray(b))for(const S of b)k(S);else k(b)}Pe.eachItem=p;function f({mergeNames:b,mergeToName:k,mergeValues:S,resultToName:I}){return(x,j,M,D)=>{const A=M===void 0?j:M instanceof e.Name?(j instanceof e.Name?b(x,j,M):k(x,j,M),M):j instanceof e.Name?(k(x,M,j),j):S(j,M);return D===e.Name&&!(A instanceof e.Name)?I(x,A):A}}Pe.mergeEvaluated={props:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>{b.if((0,e._)`${k} === true`,()=>b.assign(S,!0),()=>b.assign(S,(0,e._)`${S} || {}`).code((0,e._)`Object.assign(${S}, ${k})`))}),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>{k===!0?b.assign(S,!0):(b.assign(S,(0,e._)`${S} || {}`),v(b,S,k))}),mergeValues:(b,k)=>b===!0?!0:{...b,...k},resultToName:g}),items:f({mergeNames:(b,k,S)=>b.if((0,e._)`${S} !== true && ${k} !== undefined`,()=>b.assign(S,(0,e._)`${k} === true ? true : ${S} > ${k} ? ${S} : ${k}`)),mergeToName:(b,k,S)=>b.if((0,e._)`${S} !== true`,()=>b.assign(S,k===!0?!0:(0,e._)`${S} > ${k} ? ${S} : ${k}`)),mergeValues:(b,k)=>b===!0?!0:Math.max(b,k),resultToName:(b,k)=>b.var("items",k)})};function g(b,k){if(k===!0)return b.var("props",!0);const S=b.var("props",(0,e._)`{}`);return k!==void 0&&v(b,S,k),S}Pe.evaluatedPropsToName=g;function v(b,k,S){Object.keys(S).forEach(I=>b.assign((0,e._)`${k}${(0,e.getProperty)(I)}`,!0))}Pe.setEvaluated=v;const y={};function w(b,k){return b.scopeValue("func",{ref:k,code:y[k.code]||(y[k.code]=new t._Code(k.code))})}Pe.useFunc=w;var _;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(_||(Pe.Type=_={}));function h(b,k,S){if(b instanceof e.Name){const I=k===_.Num;return S?I?(0,e._)`"[" + ${b} + "]"`:(0,e._)`"['" + ${b} + "']"`:I?(0,e._)`"/" + ${b}`:(0,e._)`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return S?(0,e.getProperty)(b).toString():"/"+u(b)}Pe.getErrorPath=h;function T(b,k,S=b.opts.strictSchema){if(S){if(k=`strict mode: ${k}`,S===!0)throw new Error(k);b.self.logger.warn(k)}}return Pe.checkStrictMode=T,Pe}var Aa={},Hg;function cn(){if(Hg)return Aa;Hg=1,Object.defineProperty(Aa,"__esModule",{value:!0});const e=Re(),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 Aa.default=t,Aa}var Jg;function qa(){return Jg||(Jg=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=Re(),r=Le(),n=cn();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,t.str)`"${y}" keyword must be ${w} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,w=e.keywordError,_,h){const{it:T}=y,{gen:b,compositeRule:k,allErrors:S}=T,I=m(y,w,_);h??(k||S)?l(b,I):c(T,(0,t._)`[${I}]`)}e.reportError=o;function s(y,w=e.keywordError,_){const{it:h}=y,{gen:T,compositeRule:b,allErrors:k}=h,S=m(y,w,_);l(T,S),b||k||c(h,n.default.vErrors)}e.reportExtraError=s;function i(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=i;function a({gen:y,keyword:w,schemaValue:_,data:h,errsCount:T,it:b}){if(T===void 0)throw new Error("ajv implementation error");const k=y.name("err");y.forRange("i",T,n.default.errors,S=>{y.const(k,(0,t._)`${n.default.vErrors}[${S}]`),y.if((0,t._)`${k}.instancePath === undefined`,()=>y.assign((0,t._)`${k}.instancePath`,(0,t.strConcat)(n.default.instancePath,b.errorPath))),y.assign((0,t._)`${k}.schemaPath`,(0,t.str)`${b.errSchemaPath}/${w}`),b.opts.verbose&&(y.assign((0,t._)`${k}.schema`,_),y.assign((0,t._)`${k}.data`,h))})}e.extendErrors=a;function l(y,w){const _=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${_}]`),(0,t._)`${n.default.vErrors}.push(${_})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:_,validateName:h,schemaEnv:T}=y;T.$async?_.throw((0,t._)`new ${y.ValidationError}(${w})`):(_.assign((0,t._)`${h}.errors`,w),_.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function m(y,w,_){const{createErrors:h}=y.it;return h===!1?(0,t._)`{}`:p(y,w,_)}function p(y,w,_={}){const{gen:h,it:T}=y,b=[f(T,_),g(y,_)];return v(y,w,b),h.object(...b)}function f({errorPath:y},{instancePath:w}){const _=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,_)]}function g({keyword:y,it:{errSchemaPath:w}},{schemaPath:_,parentSchema:h}){let T=h?w:(0,t.str)`${w}/${y}`;return _&&(T=(0,t.str)`${T}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,T]}function v(y,{params:w,message:_},h){const{keyword:T,data:b,schemaValue:k,it:S}=y,{opts:I,propertyName:x,topSchemaRef:j,schemaPath:M}=S;h.push([u.keyword,T],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),I.messages&&h.push([u.message,typeof _=="function"?_(y):_]),I.verbose&&h.push([u.schema,k],[u.parentSchema,(0,t._)`${j}${M}`],[n.default.data,b]),x&&h.push([u.propertyName,x])}})(iu)),iu}var Gg;function Mx(){if(Gg)return jn;Gg=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.boolOrEmptySchema=jn.topBoolOrEmptySchema=void 0;const e=qa(),t=Re(),r=cn(),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))}jn.topBoolOrEmptySchema=o;function s(a,l){const{gen:c,schema:u}=a;u===!1?(c.var(l,!1),i(a)):c.var(l,!0)}jn.boolOrEmptySchema=s;function i(a,l){const{gen:c,data:u}=a,m={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:a};(0,e.reportError)(m,n,void 0,l)}return jn}var Pt={},Un={},Wg;function Kg(){if(Wg)return Un;Wg=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.getRules=Un.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)}Un.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 Un.getRules=n,Un}var zr={},Yg;function Qg(){if(Yg)return zr;Yg=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const i=o.RULES.types[s];return i&&i!==!0&&t(n,i)}zr.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}zr.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 zr.shouldUseRule=r,zr}var Xg;function La(){if(Xg)return Pt;Xg=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.reportTypeError=Pt.checkDataTypes=Pt.checkDataType=Pt.coerceAndCheckDataType=Pt.getJSONTypes=Pt.getSchemaTypes=Pt.DataType=void 0;const e=Kg(),t=Qg(),r=qa(),n=Re(),o=Le();var s;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(s||(Pt.DataType=s={}));function i(_){const h=a(_.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}Pt.getSchemaTypes=i;function a(_){const h=Array.isArray(_)?_:_?[_]:[];if(h.every(e.isJSONType))return h;throw new Error("type must be JSONType or JSONType[]: "+h.join(","))}Pt.getJSONTypes=a;function l(_,h){const{gen:T,data:b,opts:k}=_,S=u(h,k.coerceTypes),I=h.length>0&&!(S.length===0&&h.length===1&&(0,t.schemaHasRulesForType)(_,h[0]));if(I){const x=g(h,b,k.strictNumbers,s.Wrong);T.if(x,()=>{S.length?m(_,h,S):y(_)})}return I}Pt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,h){return h?_.filter(T=>c.has(T)||h==="array"&&T==="array"):[]}function m(_,h,T){const{gen:b,data:k,opts:S}=_,I=b.let("dataType",(0,n._)`typeof ${k}`),x=b.let("coerced",(0,n._)`undefined`);S.coerceTypes==="array"&&b.if((0,n._)`${I} == 'object' && Array.isArray(${k}) && ${k}.length == 1`,()=>b.assign(k,(0,n._)`${k}[0]`).assign(I,(0,n._)`typeof ${k}`).if(g(h,k,S.strictNumbers),()=>b.assign(x,k))),b.if((0,n._)`${x} !== undefined`);for(const M of T)(c.has(M)||M==="array"&&S.coerceTypes==="array")&&j(M);b.else(),y(_),b.endIf(),b.if((0,n._)`${x} !== undefined`,()=>{b.assign(k,x),p(_,x)});function j(M){switch(M){case"string":b.elseIf((0,n._)`${I} == "number" || ${I} == "boolean"`).assign(x,(0,n._)`"" + ${k}`).elseIf((0,n._)`${k} === null`).assign(x,(0,n._)`""`);return;case"number":b.elseIf((0,n._)`${I} == "boolean" || ${k} === null
|
|
83
83
|
|| (${I} == "string" && ${k} && ${k} == +${k})`).assign(x,(0,n._)`+${k}`);return;case"integer":b.elseIf((0,n._)`${I} === "boolean" || ${k} === null
|
|
84
84
|
|| (${I} === "string" && ${k} && ${k} == +${k} && !(${k} % 1))`).assign(x,(0,n._)`+${k}`);return;case"boolean":b.elseIf((0,n._)`${k} === "false" || ${k} === 0 || ${k} === null`).assign(x,!1).elseIf((0,n._)`${k} === "true" || ${k} === 1`).assign(x,!0);return;case"null":b.elseIf((0,n._)`${k} === "" || ${k} === 0 || ${k} === false`),b.assign(x,null);return;case"array":b.elseIf((0,n._)`${I} === "string" || ${I} === "number"
|
|
85
|
-
|| ${I} === "boolean" || ${k} === null`).assign(x,(0,n._)`[${k}]`)}}}function p({gen:_,parentData:h,parentDataProperty:T},b){_.if((0,n._)`${h} !== undefined`,()=>_.assign((0,n._)`${h}[${T}]`,b))}function f(_,h,T,b=s.Correct){const k=b===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(_){case"null":return(0,n._)`${h} ${k} null`;case"array":S=(0,n._)`Array.isArray(${h})`;break;case"object":S=(0,n._)`${h} && typeof ${h} == "object" && !Array.isArray(${h})`;break;case"integer":S=I((0,n._)`!(${h} % 1) && !isNaN(${h})`);break;case"number":S=I();break;default:return(0,n._)`typeof ${h} ${k} ${_}`}return b===s.Correct?S:(0,n.not)(S);function I(x=n.nil){return(0,n.and)((0,n._)`typeof ${h} == "number"`,x,T?(0,n._)`isFinite(${h})`:n.nil)}}Pt.checkDataType=f;function g(_,h,T,b){if(_.length===1)return f(_[0],h,T,b);let k;const S=(0,o.toHash)(_);if(S.array&&S.object){const I=(0,n._)`typeof ${h} != "object"`;k=S.null?I:(0,n._)`!${h} || ${I}`,delete S.null,delete S.array,delete S.object}else k=n.nil;S.number&&delete S.integer;for(const I in S)k=(0,n.and)(k,f(I,h,T,b));return k}Pt.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)}Pt.reportTypeError=y;function w(_){const{gen:h,data:T,schema:b}=_,k=(0,o.schemaRefOrVal)(_,b,"type");return{gen:h,keyword:"type",data:T,schema:b.type,schemaCode:k,schemaValue:k,parentSchema:b,params:{},it:_}}return Pt}var ls={},Kg;function Ex(){if(Kg)return ls;Kg=1,Object.defineProperty(ls,"__esModule",{value:!0}),ls.assignDefaults=void 0;const e=Re(),t=Le();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))}ls.assignDefaults=r;function n(o,s,i){const{gen:a,compositeRule:l,data:c,opts:u}=o;if(i===void 0)return;const m=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${m}`);return}let p=(0,e._)`${m} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${m} === null || ${m} === ""`),a.if(p,(0,e._)`${m} = ${(0,e.stringify)(i)}`)}return ls}var hr={},Ze={},Yg;function mr(){if(Yg)return Ze;Yg=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=Re(),t=Le(),r=ln(),n=Le();function o(_,h){const{gen:T,data:b,it:k}=_;T.if(u(T,b,h,k.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${h}`},!0),_.error()})}Ze.checkReportMissingProp=o;function s({gen:_,data:h,it:{opts:T}},b,k){return(0,e.or)(...b.map(S=>(0,e.and)(u(_,h,S,T.ownProperties),(0,e._)`${k} = ${S}`)))}Ze.checkMissingProp=s;function i(_,h){_.setParams({missingProperty:h},!0),_.error()}Ze.reportMissingProp=i;function a(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ze.hasPropFunc=a;function l(_,h,T){return(0,e._)`${a(_)}.call(${h}, ${T})`}Ze.isOwnProperty=l;function c(_,h,T,b){const k=(0,e._)`${h}${(0,e.getProperty)(T)} !== undefined`;return b?(0,e._)`${k} && ${l(_,h,T)}`:k}Ze.propertyInData=c;function u(_,h,T,b){const k=(0,e._)`${h}${(0,e.getProperty)(T)} === undefined`;return b?(0,e.or)(k,(0,e.not)(l(_,h,T))):k}Ze.noPropertyInData=u;function m(_){return _?Object.keys(_).filter(h=>h!=="__proto__"):[]}Ze.allSchemaProperties=m;function p(_,h){return m(h).filter(T=>!(0,t.alwaysValidSchema)(_,h[T]))}Ze.schemaProperties=p;function f({schemaCode:_,data:h,it:{gen:T,topSchemaRef:b,schemaPath:k,errorPath:S},it:I},x,j,M){const D=M?(0,e._)`${_}, ${h}, ${b}${k}`:h,A=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,I.parentData],[r.default.parentDataProperty,I.parentDataProperty],[r.default.rootData,r.default.rootData]];I.opts.dynamicRef&&A.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const O=(0,e._)`${D}, ${T.object(...A)}`;return j!==e.nil?(0,e._)`${x}.call(${j}, ${O})`:(0,e._)`${x}(${O})`}Ze.callValidateCode=f;const g=(0,e._)`new RegExp`;function v({gen:_,it:{opts:h}},T){const b=h.unicodeRegExp?"u":"",{regExp:k}=h.code,S=k(T,b);return _.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${k.code==="new RegExp"?g:(0,n.useFunc)(_,k)}(${T}, ${b})`})}Ze.usePattern=v;function y(_){const{gen:h,data:T,keyword:b,it:k}=_,S=h.name("valid");if(k.allErrors){const x=h.let("valid",!0);return I(()=>h.assign(x,!1)),x}return h.var(S,!0),I(()=>h.break()),S;function I(x){const j=h.const("len",(0,e._)`${T}.length`);h.forRange("i",0,j,M=>{_.subschema({keyword:b,dataProp:M,dataPropType:t.Type.Num},S),h.if((0,e.not)(S),x)})}}Ze.validateArray=y;function w(_){const{gen:h,schema:T,keyword:b,it:k}=_;if(!Array.isArray(T))throw new Error("ajv implementation error");if(T.some(j=>(0,t.alwaysValidSchema)(k,j))&&!k.opts.unevaluated)return;const I=h.let("valid",!1),x=h.name("_valid");h.block(()=>T.forEach((j,M)=>{const D=_.subschema({keyword:b,schemaProp:M,compositeRule:!0},x);h.assign(I,(0,e._)`${I} || ${x}`),_.mergeValidEvaluated(D,x)||h.if((0,e.not)(I))})),_.result(I,()=>_.reset(),()=>_.error(!0))}return Ze.validateUnion=w,Ze}var Qg;function $x(){if(Qg)return hr;Qg=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.validateKeywordUsage=hr.validSchemaType=hr.funcKeywordCode=hr.macroKeywordCode=void 0;const e=Re(),t=ln(),r=mr(),n=Na();function o(p,f){const{gen:g,keyword:v,schema:y,parentSchema:w,it:_}=p,h=f.macro.call(_.self,y,w,_),T=c(g,v,h);_.opts.validateSchema!==!1&&_.self.validateSchema(h,!0);const b=g.name("valid");p.subschema({schema:h,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${v}`,topSchemaRef:T,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}hr.macroKeywordCode=o;function s(p,f){var g;const{gen:v,keyword:y,schema:w,parentSchema:_,$data:h,it:T}=p;l(T,f);const b=!h&&f.compile?f.compile.call(T.self,w,_,T):f.validate,k=c(v,y,b),S=v.let("valid");p.block$data(S,I),p.ok((g=f.valid)!==null&&g!==void 0?g:S);function I(){if(f.errors===!1)M(),f.modifying&&i(p),D(()=>p.error());else{const A=f.async?x():j();f.modifying&&i(p),D(()=>a(p,A))}}function x(){const A=v.let("ruleErrs",null);return v.try(()=>M((0,e._)`await `),O=>v.assign(S,!1).if((0,e._)`${O} instanceof ${T.ValidationError}`,()=>v.assign(A,(0,e._)`${O}.errors`),()=>v.throw(O))),A}function j(){const A=(0,e._)`${k}.errors`;return v.assign(A,null),M(e.nil),A}function M(A=f.async?(0,e._)`await `:e.nil){const O=T.opts.passContext?t.default.this:t.default.self,H=!("compile"in f&&!h||f.schema===!1);v.assign(S,(0,e._)`${A}${(0,r.callValidateCode)(p,k,O,H)}`,f.modifying)}function D(A){var O;v.if((0,e.not)((O=f.valid)!==null&&O!==void 0?O:S),A)}}hr.funcKeywordCode=s;function i(p){const{gen:f,data:g,it:v}=p;f.if(v.parentData,()=>f.assign(g,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function a(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")}hr.validSchemaType=u;function m({schema:p,opts:f,self:g,errSchemaPath:v},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const _=y.dependencies;if(_?.some(h=>!Object.prototype.hasOwnProperty.call(p,h)))throw new Error(`parent schema must have dependencies of ${w}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const T=`keyword "${w}" value is invalid at path "${v}": `+g.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")g.logger.error(T);else throw new Error(T)}}return hr.validateKeywordUsage=m,hr}var zr={},Xg;function Rx(){if(Xg)return zr;Xg=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.extendSubschemaMode=zr.extendSubschemaData=zr.getSubschema=void 0;const e=Re(),t=Le();function r(s,{keyword:i,schemaProp:a,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:m}){if(i!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const p=s.schema[i];return a===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${i}`}:{schema:p[a],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${i}/${(0,t.escapeFragment)(a)}`}}if(l!==void 0){if(c===void 0||u===void 0||m===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:m,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}zr.getSubschema=r;function n(s,i,{dataProp:a,dataPropType:l,data:c,dataTypes:u,propertyName:m}){if(c!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(a!==void 0){const{errorPath:g,dataPathArr:v,opts:y}=i,w=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);f(w),s.errorPath=(0,e.str)`${g}${(0,t.getErrorPath)(a,l,y.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,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=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,g]}}zr.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 zr.extendSubschemaMode=o,zr}var Ut={},tu,ey;function ty(){return ey||(ey=1,tu=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}),tu}var ru={exports:{}},ry;function Px(){if(ry)return ru.exports;ry=1;var e=ru.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var i=typeof s=="function"?s:s.pre||function(){},a=s.post||function(){};t(o,i,a,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,i,a,l,c,u,m,p){if(i&&typeof i=="object"&&!Array.isArray(i)){o(i,a,l,c,u,m,p);for(var f in i){var g=i[f];if(Array.isArray(g)){if(f in e.arrayKeywords)for(var v=0;v<g.length;v++)t(n,o,s,g[v],a+"/"+f+"/"+v,l,a,f,i,v)}else if(f in e.propsKeywords){if(g&&typeof g=="object")for(var y in g)t(n,o,s,g[y],a+"/"+f+"/"+r(y),l,a,f,i,y)}else(f in e.keywords||n.allKeys&&!(f in e.skipKeywords))&&t(n,o,s,g,a+"/"+f,l,a,f,i)}s(i,a,l,c,u,m,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return ru.exports}var ny;function Oa(){if(ny)return Ut;ny=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.getSchemaRefs=Ut.resolveUrl=Ut.normalizeId=Ut._getFullPath=Ut.getFullPath=Ut.inlineRef=void 0;const e=Le(),t=ty(),r=Px(),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?!i(v):y?a(v)<=y:!1}Ut.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(v){for(const y in v){if(s.has(y))return!0;const w=v[y];if(Array.isArray(w)&&w.some(i)||typeof w=="object"&&i(w))return!0}return!1}function a(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+=a(_)),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,_)}Ut.getFullPath=l;function c(v,y){return v.serialize(y).split("#")[0]+"#"}Ut._getFullPath=c;const u=/#\/?$/;function m(v){return v?v.replace(u,""):""}Ut.normalizeId=m;function p(v,y,w){return w=m(w),v.resolve(y,w)}Ut.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function g(v,y){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:_}=this.opts,h=m(v[w]||y),T={"":h},b=l(_,h,!1),k={},S=new Set;return r(v,{allKeys:!0},(j,M,D,A)=>{if(A===void 0)return;const O=b+M;let H=T[A];typeof j[w]=="string"&&(H=Q.call(this,j[w])),Y.call(this,j.$anchor),Y.call(this,j.$dynamicAnchor),T[M]=H;function Q(W){const pe=this.opts.uriResolver.resolve;if(W=m(H?pe(H,W):W),S.has(W))throw x(W);S.add(W);let Z=this.refs[W];return typeof Z=="string"&&(Z=this.refs[Z]),typeof Z=="object"?I(j,Z.schema,W):W!==m(O)&&(W[0]==="#"?(I(j,k[W],W),k[W]=j):this.refs[W]=O),W}function Y(W){if(typeof W=="string"){if(!f.test(W))throw new Error(`invalid anchor "${W}"`);Q.call(this,`#${W}`)}}}),k;function I(j,M,D){if(M!==void 0&&!t(j,M))throw x(D)}function x(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return Ut.getSchemaRefs=g,Ut}var oy;function Aa(){if(oy)return Ur;oy=1,Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.getData=Ur.KeywordCxt=Ur.validateFunctionCode=void 0;const e=xx(),t=Ma(),r=Gg(),n=Ma(),o=Ex(),s=$x(),i=Rx(),a=Re(),l=ln(),c=Oa(),u=Le(),m=Na();function p(z){if(b(z)&&(S(z),T(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Ur.validateFunctionCode=p;function f({gen:z,validateName:V,schema:K,schemaEnv:X,opts:le},Te){le.code.es5?z.func(V,(0,a._)`${l.default.data}, ${l.default.valCxt}`,X.$async,()=>{z.code((0,a._)`"use strict"; ${_(K,le)}`),v(z,le),z.code(Te)}):z.func(V,(0,a._)`${l.default.data}, ${g(le)}`,X.$async,()=>z.code(_(K,le)).code(Te))}function g(z){return(0,a._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${z.dynamicRef?(0,a._)`, ${l.default.dynamicAnchors}={}`:a.nil}}={}`}function v(z,V){z.if(l.default.valCxt,()=>{z.var(l.default.instancePath,(0,a._)`${l.default.valCxt}.${l.default.instancePath}`),z.var(l.default.parentData,(0,a._)`${l.default.valCxt}.${l.default.parentData}`),z.var(l.default.parentDataProperty,(0,a._)`${l.default.valCxt}.${l.default.parentDataProperty}`),z.var(l.default.rootData,(0,a._)`${l.default.valCxt}.${l.default.rootData}`),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,a._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{z.var(l.default.instancePath,(0,a._)`""`),z.var(l.default.parentData,(0,a._)`undefined`),z.var(l.default.parentDataProperty,(0,a._)`undefined`),z.var(l.default.rootData,l.default.data),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,a._)`{}`)})}function y(z){const{schema:V,opts:K,gen:X}=z;f(z,()=>{K.$comment&&V.$comment&&A(z),j(z),X.let(l.default.vErrors,null),X.let(l.default.errors,0),K.unevaluated&&w(z),I(z),O(z)})}function w(z){const{gen:V,validateName:K}=z;z.evaluated=V.const("evaluated",(0,a._)`${K}.evaluated`),V.if((0,a._)`${z.evaluated}.dynamicProps`,()=>V.assign((0,a._)`${z.evaluated}.props`,(0,a._)`undefined`)),V.if((0,a._)`${z.evaluated}.dynamicItems`,()=>V.assign((0,a._)`${z.evaluated}.items`,(0,a._)`undefined`))}function _(z,V){const K=typeof z=="object"&&z[V.schemaId];return K&&(V.code.source||V.code.process)?(0,a._)`/*# sourceURL=${K} */`:a.nil}function h(z,V){if(b(z)&&(S(z),T(z))){k(z,V);return}(0,e.boolOrEmptySchema)(z,V)}function T({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 b(z){return typeof z.schema!="boolean"}function k(z,V){const{schema:K,gen:X,opts:le}=z;le.$comment&&K.$comment&&A(z),M(z),D(z);const Te=X.const("_errs",l.default.errors);I(z,Te),X.var(V,(0,a._)`${Te} === ${l.default.errors}`)}function S(z){(0,u.checkUnknownRules)(z),x(z)}function I(z,V){if(z.opts.jtd)return Q(z,[],!1,V);const K=(0,t.getSchemaTypes)(z.schema),X=(0,t.coerceAndCheckDataType)(z,K);Q(z,K,!X,V)}function x(z){const{schema:V,errSchemaPath:K,opts:X,self:le}=z;V.$ref&&X.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(V,le.RULES)&&le.logger.warn(`$ref: keywords ignored in schema at path "${K}"`)}function j(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 D(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function A({gen:z,schemaEnv:V,schema:K,errSchemaPath:X,opts:le}){const Te=K.$comment;if(le.$comment===!0)z.code((0,a._)`${l.default.self}.logger.log(${Te})`);else if(typeof le.$comment=="function"){const Fe=(0,a.str)`${X}/$comment`,tt=z.scopeValue("root",{ref:V.root});z.code((0,a._)`${l.default.self}.opts.$comment(${Te}, ${Fe}, ${tt}.schema)`)}}function O(z){const{gen:V,schemaEnv:K,validateName:X,ValidationError:le,opts:Te}=z;K.$async?V.if((0,a._)`${l.default.errors} === 0`,()=>V.return(l.default.data),()=>V.throw((0,a._)`new ${le}(${l.default.vErrors})`)):(V.assign((0,a._)`${X}.errors`,l.default.vErrors),Te.unevaluated&&H(z),V.return((0,a._)`${l.default.errors} === 0`))}function H({gen:z,evaluated:V,props:K,items:X}){K instanceof a.Name&&z.assign((0,a._)`${V}.props`,K),X instanceof a.Name&&z.assign((0,a._)`${V}.items`,X)}function Q(z,V,K,X){const{gen:le,schema:Te,data:Fe,allErrors:tt,opts:ut,self:Ye}=z,{RULES:$}=Ye;if(Te.$ref&&(ut.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(Te,$))){le.block(()=>G(z,"$ref",$.all.$ref.definition));return}ut.jtd||W(z,V),le.block(()=>{for(const Ae of $.rules)re(Ae);re($.post)});function re(Ae){(0,r.shouldUseGroup)(Te,Ae)&&(Ae.type?(le.if((0,n.checkDataType)(Ae.type,Fe,ut.strictNumbers)),Y(z,Ae),V.length===1&&V[0]===Ae.type&&K&&(le.else(),(0,n.reportTypeError)(z)),le.endIf()):Y(z,Ae),tt||le.if((0,a._)`${l.default.errors} === ${X||0}`))}}function Y(z,V){const{gen:K,schema:X,opts:{useDefaults:le}}=z;le&&(0,o.assignDefaults)(z,V.type),K.block(()=>{for(const Te of V.rules)(0,r.shouldUseRule)(X,Te)&&G(z,Te.keyword,Te.definition,V.type)})}function W(z,V){z.schemaEnv.meta||!z.opts.strictTypes||(pe(z,V),z.opts.allowUnionTypes||Z(z,V),P(z,z.dataTypes))}function pe(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(",")}"`)}),E(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 P(z,V){const K=z.self.RULES.all;for(const X in K){const le=K[X];if(typeof le=="object"&&(0,r.shouldUseRule)(z.schema,le)){const{type:Te}=le.definition;Te.length&&!Te.some(Fe=>B(V,Fe))&&N(z,`missing type "${Te.join(",")}" for keyword "${X}"`)}}}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 E(z,V){const K=[];for(const X of z.dataTypes)F(V,X)?K.push(X):V.includes("integer")&&X==="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 L{constructor(V,K,X){if((0,s.validateKeywordUsage)(V,K,X),this.gen=V.gen,this.allErrors=V.allErrors,this.keyword=X,this.data=V.data,this.schema=V.schema[X],this.$data=K.$data&&V.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(V,this.schema,X,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",ke(this.$data,V));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,K.schemaType,K.allowUndefined))throw new Error(`${X} 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,X){this.failResult((0,a.not)(V),K,X)}failResult(V,K,X){this.gen.if(V),X?X():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,a.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,a._)`${K} !== undefined && (${(0,a.or)(this.invalid$data(),V)})`)}error(V,K,X){if(K){this.setParams(K),this._error(V,X),this.setParams({});return}this._error(V,X)}_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,X=a.nil){this.gen.block(()=>{this.check$data(V,X),K()})}check$data(V=a.nil,K=a.nil){if(!this.$data)return;const{gen:X,schemaCode:le,schemaType:Te,def:Fe}=this;X.if((0,a.or)((0,a._)`${le} === undefined`,K)),V!==a.nil&&X.assign(V,!0),(Te.length||Fe.validateSchema)&&(X.elseIf(this.invalid$data()),this.$dataError(),V!==a.nil&&X.assign(V,!1)),X.else()}invalid$data(){const{gen:V,schemaCode:K,schemaType:X,def:le,it:Te}=this;return(0,a.or)(Fe(),tt());function Fe(){if(X.length){if(!(K instanceof a.Name))throw new Error("ajv implementation error");const ut=Array.isArray(X)?X:[X];return(0,a._)`${(0,n.checkDataTypes)(ut,K,Te.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}function tt(){if(le.validateSchema){const ut=V.scopeValue("validate$data",{ref:le.validateSchema});return(0,a._)`!${ut}(${K})`}return a.nil}}subschema(V,K){const X=(0,i.getSubschema)(this.it,V);(0,i.extendSubschemaData)(X,this.it,V),(0,i.extendSubschemaMode)(X,V);const le={...this.it,...X,items:void 0,props:void 0};return h(le,K),le}mergeEvaluated(V,K){const{it:X,gen:le}=this;X.opts.unevaluated&&(X.props!==!0&&V.props!==void 0&&(X.props=u.mergeEvaluated.props(le,V.props,X.props,K)),X.items!==!0&&V.items!==void 0&&(X.items=u.mergeEvaluated.items(le,V.items,X.items,K)))}mergeValidEvaluated(V,K){const{it:X,gen:le}=this;if(X.opts.unevaluated&&(X.props!==!0||X.items!==!0))return le.if(K,()=>this.mergeEvaluated(V,a.Name)),!0}}Ur.KeywordCxt=L;function G(z,V,K,X){const le=new L(z,K,V);"code"in K?K.code(le,X):le.$data&&K.validate?(0,s.funcKeywordCode)(le,K):"macro"in K?(0,s.macroKeywordCode)(le,K):(K.compile||K.validate)&&(0,s.funcKeywordCode)(le,K)}const ee=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ke(z,{dataLevel:V,dataNames:K,dataPathArr:X}){let le,Te;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!ee.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);le=z,Te=l.default.rootData}else{const Ye=se.exec(z);if(!Ye)throw new Error(`Invalid JSON-pointer: ${z}`);const $=+Ye[1];if(le=Ye[2],le==="#"){if($>=V)throw new Error(ut("property/index",$));return X[V-$]}if($>V)throw new Error(ut("data",$));if(Te=K[V-$],!le)return Te}let Fe=Te;const tt=le.split("/");for(const Ye of tt)Ye&&(Te=(0,a._)`${Te}${(0,a.getProperty)((0,u.unescapeJsonPointer)(Ye))}`,Fe=(0,a._)`${Fe} && ${Te}`);return Fe;function ut(Ye,$){return`Cannot access ${Ye} ${$} levels up, current level is ${V}`}}return Ur.getData=ke,Ur}var qa={},sy;function nu(){if(sy)return qa;sy=1,Object.defineProperty(qa,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return qa.default=e,qa}var La={},ay;function ja(){if(ay)return La;ay=1,Object.defineProperty(La,"__esModule",{value:!0});const e=Oa();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 La.default=t,La}var Yt={},iy;function ou(){if(iy)return Yt;iy=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;const e=Re(),t=nu(),r=ln(),n=Oa(),o=Le(),s=Aa();class i{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={}}}Yt.SchemaEnv=i;function a(y){const w=u.call(this,y);if(w)return w;const _=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:h,lines:T}=this.opts.code,{ownProperties:b}=this.opts,k=new e.CodeGen(this.scope,{es5:h,lines:T,ownProperties:b});let S;y.$async&&(S=k.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=k.scopeName("validate");y.validateName=I;const x={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:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:I,ValidationError:S,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(y),(0,s.validateFunctionCode)(x),k.optimize(this.opts.code.optimize);const M=k.toString();j=`${k.scopeRefs(r.default.scope)}return ${M}`,this.opts.code.process&&(j=this.opts.code.process(j,y));const A=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(I,{ref:A}),A.errors=null,A.schema=y.schema,A.schemaEnv=y,y.$async&&(A.$async=!0),this.opts.code.source===!0&&(A.source={validateName:I,validateCode:M,scopeValues:k._values}),this.opts.unevaluated){const{props:O,items:H}=x;A.evaluated={props:O instanceof e.Name?void 0:O,items:H instanceof e.Name?void 0:H,dynamicProps:O instanceof e.Name,dynamicItems:H instanceof e.Name},A.source&&(A.source.evaluated=(0,e.stringify)(A.evaluated))}return y.validate=A,y}catch(M){throw delete y.validate,delete y.validateName,j&&this.logger.error("Error compiling schema, function code:",j),M}finally{this._compilations.delete(y)}}Yt.compileSchema=a;function l(y,w,_){var h;_=(0,n.resolveUrl)(this.opts.uriResolver,w,_);const T=y.refs[_];if(T)return T;let b=p.call(this,y,_);if(b===void 0){const k=(h=y.localRefs)===null||h===void 0?void 0:h[_],{schemaId:S}=this.opts;k&&(b=new i({schema:k,schemaId:S,root:y,baseId:w}))}if(b!==void 0)return y.refs[_]=c.call(this,b)}Yt.resolveRef=l;function c(y){return(0,n.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:a.call(this,y)}function u(y){for(const w of this._compilations)if(m(w,y))return w}Yt.getCompilingSchema=u;function m(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let _;for(;typeof(_=this.refs[w])=="string";)w=_;return _||this.schemas[w]||f.call(this,y,w)}function f(y,w){const _=this.opts.uriResolver.parse(w),h=(0,n._getFullPath)(this.opts.uriResolver,_);let T=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&h===T)return v.call(this,_,y);const b=(0,n.normalizeId)(h),k=this.refs[b]||this.schemas[b];if(typeof k=="string"){const S=f.call(this,y,k);return typeof S?.schema!="object"?void 0:v.call(this,_,S)}if(typeof k?.schema=="object"){if(k.validate||a.call(this,k),b===(0,n.normalizeId)(w)){const{schema:S}=k,{schemaId:I}=this.opts,x=S[I];return x&&(T=(0,n.resolveUrl)(this.opts.uriResolver,T,x)),new i({schema:S,schemaId:I,root:y,baseId:T})}return v.call(this,_,k)}}Yt.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(y,{baseId:w,schema:_,root:h}){var T;if(((T=y.fragment)===null||T===void 0?void 0:T[0])!=="/")return;for(const S of y.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const I=_[(0,o.unescapeFragment)(S)];if(I===void 0)return;_=I;const x=typeof _=="object"&&_[this.opts.schemaId];!g.has(S)&&x&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,x))}let b;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const S=(0,n.resolveUrl)(this.opts.uriResolver,w,_.$ref);b=f.call(this,h,S)}const{schemaId:k}=this.opts;if(b=b||new i({schema:_,schemaId:k,root:h,baseId:w}),b.schema!==b.root.schema)return b}return Yt}const Nx={$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 Ua={},cs={exports:{}},su,ly;function cy(){if(ly)return su;ly=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 i(p){let f=0;const g={error:!1,address:"",zone:""},v=[],y=[];let w=!1,_=!1,h=s;for(let T=0;T<p.length;T++){const b=p[T];if(!(b==="["||b==="]"))if(b===":"){if(w===!0&&(_=!0),!h(y,v,g))break;if(++f>7){g.error=!0;break}T>0&&p[T-1]===":"&&(w=!0),v.push(":");continue}else if(b==="%"){if(!h(y,v,g))break;h=o}else{y.push(b);continue}}return y.length&&(h===o?g.zone=y.join(""):_?v.push(y.join("")):v.push(r(y))),g.address=v.join(""),g}function a(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const f=i(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=a(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 su={nonSimpleDomain:n,recomposeAuthority:m,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:r},su}var au,uy;function Mx(){if(uy)return au;uy=1;const{isUUID:e}=cy(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(b){return r.indexOf(b)!==-1}function o(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function i(b){const k=String(b.scheme).toLowerCase()==="https";return(b.port===(k?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function a(b){return b.secure=o(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(o(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){const[k,S]=b.resourceName.split("?");b.path=k&&k!=="/"?k:void 0,b.query=S,b.resourceName=void 0}return b.fragment=void 0,b}function c(b,k){if(!b.path)return b.error="URN can not be parsed",b;const S=b.path.match(t);if(S){const I=k.scheme||b.scheme||"urn";b.nid=S[1].toLowerCase(),b.nss=S[2];const x=`${I}:${k.nid||b.nid}`,j=T(x);b.path=void 0,j&&(b=j.parse(b,k))}else b.error=b.error||"URN can not be parsed.";return b}function u(b,k){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=k.scheme||b.scheme||"urn",I=b.nid.toLowerCase(),x=`${S}:${k.nid||I}`,j=T(x);j&&(b=j.serialize(b,k));const M=b,D=b.nss;return M.path=`${I||k.nid}:${D}`,k.skipEscape=!0,M}function m(b,k){const S=b;return S.uuid=S.nss,S.nss=void 0,!k.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(b){const k=b;return k.nss=(b.uuid||"").toLowerCase(),k}const f={scheme:"http",domainHost:!0,parse:s,serialize:i},g={scheme:"https",domainHost:f.domainHost,parse:s,serialize:i},v={scheme:"ws",domainHost:!0,parse:a,serialize:l},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},h={http:f,https:g,ws:v,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:m,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(h,null);function T(b){return b&&(h[b]||h[b.toLowerCase()])||void 0}return au={wsIsSecure:o,SCHEMES:h,isValidSchemeName:n,getSchemeHandler:T},au}var dy;function Ox(){if(dy)return cs.exports;dy=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=cy(),{SCHEMES:i,getSchemeHandler:a}=Mx();function l(y,w){return typeof y=="string"?y=p(g(y,w),w):typeof y=="object"&&(y=g(p(y,w),w)),y}function c(y,w,_){const h=_?Object.assign({scheme:"null"},_):{scheme:"null"},T=u(g(y,h),g(w,h),h,!0);return h.skipEscape=!0,p(T,h)}function u(y,w,_,h){const T={};return h||(y=g(p(y,_),_),w=g(p(w,_),_)),_=_||{},!_.tolerant&&w.scheme?(T.scheme=w.scheme,T.userinfo=w.userinfo,T.host=w.host,T.port=w.port,T.path=t(w.path||""),T.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(T.userinfo=w.userinfo,T.host=w.host,T.port=w.port,T.path=t(w.path||""),T.query=w.query):(w.path?(w.path[0]==="/"?T.path=t(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?T.path="/"+w.path:y.path?T.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:T.path=w.path,T.path=t(T.path)),T.query=w.query):(T.path=y.path,w.query!==void 0?T.query=w.query:T.query=y.query),T.userinfo=y.userinfo,T.host=y.host,T.port=y.port),T.scheme=y.scheme),T.fragment=w.fragment,T}function m(y,w,_){return typeof y=="string"?(y=unescape(y),y=p(n(g(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{..._,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(g(w,_),!0),{..._,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{..._,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const _={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},h=Object.assign({},w),T=[],b=a(h.scheme||_.scheme);b&&b.serialize&&b.serialize(_,h),_.path!==void 0&&(h.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),h.reference!=="suffix"&&_.scheme&&T.push(_.scheme,":");const k=r(_);if(k!==void 0&&(h.reference!=="suffix"&&T.push("//"),T.push(k),_.path&&_.path[0]!=="/"&&T.push("/")),_.path!==void 0){let S=_.path;!h.absolutePath&&(!b||!b.absolutePath)&&(S=t(S)),k===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),T.push(S)}return _.query!==void 0&&T.push("?",_.query),_.fragment!==void 0&&T.push("#",_.fragment),T.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(y,w){const _=Object.assign({},w),h={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let T=!1;_.reference==="suffix"&&(_.scheme?y=_.scheme+":"+y:y="//"+y);const b=y.match(f);if(b){if(h.scheme=b[1],h.userinfo=b[3],h.host=b[4],h.port=parseInt(b[5],10),h.path=b[6]||"",h.query=b[7],h.fragment=b[8],isNaN(h.port)&&(h.port=b[5]),h.host)if(o(h.host)===!1){const I=e(h.host);h.host=I.host.toLowerCase(),T=I.isIPV6}else T=!0;h.scheme===void 0&&h.userinfo===void 0&&h.host===void 0&&h.port===void 0&&h.query===void 0&&!h.path?h.reference="same-document":h.scheme===void 0?h.reference="relative":h.fragment===void 0?h.reference="absolute":h.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==h.reference&&(h.error=h.error||"URI is not a "+_.reference+" reference.");const k=a(_.scheme||h.scheme);if(!_.unicodeSupport&&(!k||!k.unicodeSupport)&&h.host&&(_.domainHost||k&&k.domainHost)&&T===!1&&s(h.host))try{h.host=URL.domainToASCII(h.host.toLowerCase())}catch(S){h.error=h.error||"Host's domain name can not be converted to ASCII: "+S}(!k||k&&!k.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)))),k&&k.parse&&k.parse(h,_)}else h.error=h.error||"URI can not be parsed.";return h}const v={SCHEMES:i,normalize:l,resolve:c,resolveComponent:u,equal:m,serialize:p,parse:g};return cs.exports=v,cs.exports.default=v,cs.exports.fastUri=v,cs.exports}var py;function Ax(){if(py)return Ua;py=1,Object.defineProperty(Ua,"__esModule",{value:!0});const e=Ox();return e.code='require("ajv/dist/runtime/uri").default',Ua.default=e,Ua}var fy;function qx(){return fy||(fy=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=Aa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Re();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=nu(),o=ja(),s=Hg(),i=ou(),a=Re(),l=Oa(),c=Ma(),u=Le(),m=Nx,p=Ax(),f=(Z,P)=>new RegExp(Z,P);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 P,B,F,E,N,L,G,ee,se,ke,z,V,K,X,le,Te,Fe,tt,ut,Ye,$,re,Ae,yt,Dt;const Be=Z.strict,Br=(P=Z.code)===null||P===void 0?void 0:P.optimize,dt=Br===!0||Br===void 0?1:Br||0,sr=(F=(B=Z.code)===null||B===void 0?void 0:B.regExp)!==null&&F!==void 0?F:f,hn=(E=Z.uriResolver)!==null&&E!==void 0?E:p.default;return{strictSchema:(L=(N=Z.strictSchema)!==null&&N!==void 0?N:Be)!==null&&L!==void 0?L:!0,strictNumbers:(ee=(G=Z.strictNumbers)!==null&&G!==void 0?G:Be)!==null&&ee!==void 0?ee:!0,strictTypes:(ke=(se=Z.strictTypes)!==null&&se!==void 0?se:Be)!==null&&ke!==void 0?ke:"log",strictTuples:(V=(z=Z.strictTuples)!==null&&z!==void 0?z:Be)!==null&&V!==void 0?V:"log",strictRequired:(X=(K=Z.strictRequired)!==null&&K!==void 0?K:Be)!==null&&X!==void 0?X:!1,code:Z.code?{...Z.code,optimize:dt,regExp:sr}:{optimize:dt,regExp:sr},loopRequired:(le=Z.loopRequired)!==null&&le!==void 0?le:_,loopEnum:(Te=Z.loopEnum)!==null&&Te!==void 0?Te:_,meta:(Fe=Z.meta)!==null&&Fe!==void 0?Fe:!0,messages:(tt=Z.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(ut=Z.inlineRefs)!==null&&ut!==void 0?ut:!0,schemaId:(Ye=Z.schemaId)!==null&&Ye!==void 0?Ye:"$id",addUsedSchema:($=Z.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(re=Z.validateSchema)!==null&&re!==void 0?re:!0,validateFormats:(Ae=Z.validateFormats)!==null&&Ae!==void 0?Ae:!0,unicodeRegExp:(yt=Z.unicodeRegExp)!==null&&yt!==void 0?yt:!0,int32range:(Dt=Z.int32range)!==null&&Dt!==void 0?Dt:!0,uriResolver:hn}}class T{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,...h(P)};const{es5:B,lines:F}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:B,lines:F}),this.logger=D(P.logger);const E=P.validateFormats;P.validateFormats=!1,this.RULES=(0,s.getRules)(),b.call(this,y,P,"NOT SUPPORTED"),b.call(this,w,P,"DEPRECATED","warn"),this._metaOpts=j.call(this),P.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&x.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),S.call(this),P.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:P,meta:B,schemaId:F}=this.opts;let E=m;F==="id"&&(E={...m},E.id=E.$id,delete E.$id),B&&P&&this.addMetaSchema(E,E[F],!1)}defaultMeta(){const{meta:P,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[B]||P:void 0}validate(P,B){let F;if(typeof P=="string"){if(F=this.getSchema(P),!F)throw new Error(`no schema with key or ref "${P}"`)}else F=this.compile(P);const E=F(B);return"$async"in F||(this.errors=F.errors),E}compile(P,B){const F=this._addSchema(P,B);return F.validate||this._compileSchemaEnv(F)}compileAsync(P,B){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:F}=this.opts;return E.call(this,P,B);async function E(ke,z){await N.call(this,ke.$schema);const V=this._addSchema(ke,z);return V.validate||L.call(this,V)}async function N(ke){ke&&!this.getSchema(ke)&&await E.call(this,{$ref:ke},!0)}async function L(ke){try{return this._compileSchemaEnv(ke)}catch(z){if(!(z instanceof o.default))throw z;return G.call(this,z),await ee.call(this,z.missingSchema),L.call(this,ke)}}function G({missingSchema:ke,missingRef:z}){if(this.refs[ke])throw new Error(`AnySchema ${ke} is loaded but ${z} cannot be resolved`)}async function ee(ke){const z=await se.call(this,ke);this.refs[ke]||await N.call(this,z.$schema),this.refs[ke]||this.addSchema(z,ke,B)}async function se(ke){const z=this._loading[ke];if(z)return z;try{return await(this._loading[ke]=F(ke))}finally{delete this._loading[ke]}}}addSchema(P,B,F,E=this.opts.validateSchema){if(Array.isArray(P)){for(const L of P)this.addSchema(L,void 0,F,E);return this}let N;if(typeof P=="object"){const{schemaId:L}=this.opts;if(N=P[L],N!==void 0&&typeof N!="string")throw new Error(`schema ${L} must be string`)}return B=(0,l.normalizeId)(B||N),this._checkUnique(B),this.schemas[B]=this._addSchema(P,F,B,E,!0),this}addMetaSchema(P,B,F=this.opts.validateSchema){return this.addSchema(P,B,!0,F),this}validateSchema(P,B){if(typeof P=="boolean")return!0;let F;if(F=P.$schema,F!==void 0&&typeof F!="string")throw new Error("$schema must be a string");if(F=F||this.opts.defaultMeta||this.defaultMeta(),!F)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(F,P);if(!E&&B){const N="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(N);else throw new Error(N)}return E}getSchema(P){let B;for(;typeof(B=k.call(this,P))=="string";)P=B;if(B===void 0){const{schemaId:F}=this.opts,E=new i.SchemaEnv({schema:{},schemaId:F});if(B=i.resolveSchema.call(this,E,P),!B)return;this.refs[P]=B}return B.validate||this._compileSchemaEnv(B)}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 B=k.call(this,P);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{const B=P;this._cache.delete(B);let F=P[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(P){for(const B of P)this.addKeyword(B);return this}addKeyword(P,B){let F;if(typeof P=="string")F=P,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=F);else if(typeof P=="object"&&B===void 0){if(B=P,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(O.call(this,F,B),!B)return(0,u.eachItem)(F,N=>H.call(this,N)),this;Y.call(this,B);const E={...B,type:(0,c.getJSONTypes)(B.type),schemaType:(0,c.getJSONTypes)(B.schemaType)};return(0,u.eachItem)(F,E.type.length===0?N=>H.call(this,N,E):N=>E.type.forEach(L=>H.call(this,N,E,L))),this}getKeyword(P){const B=this.RULES.all[P];return typeof B=="object"?B.definition:!!B}removeKeyword(P){const{RULES:B}=this;delete B.keywords[P],delete B.all[P];for(const F of B.rules){const E=F.rules.findIndex(N=>N.keyword===P);E>=0&&F.rules.splice(E,1)}return this}addFormat(P,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[P]=B,this}errorsText(P=this.errors,{separator:B=", ",dataVar:F="data"}={}){return!P||P.length===0?"No errors":P.map(E=>`${F}${E.instancePath} ${E.message}`).reduce((E,N)=>E+B+N)}$dataMetaSchema(P,B){const F=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(const E of B){const N=E.split("/").slice(1);let L=P;for(const G of N)L=L[G];for(const G in F){const ee=F[G];if(typeof ee!="object")continue;const{$data:se}=ee.definition,ke=L[G];se&&ke&&(L[G]=pe(ke))}}return P}_removeAllSchemas(P,B){for(const F in P){const E=P[F];(!B||B.test(F))&&(typeof E=="string"?delete P[F]:E&&!E.meta&&(this._cache.delete(E.schema),delete P[F]))}}_addSchema(P,B,F,E=this.opts.validateSchema,N=this.opts.addUsedSchema){let L;const{schemaId:G}=this.opts;if(typeof P=="object")L=P[G];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 ee=this._cache.get(P);if(ee!==void 0)return ee;F=(0,l.normalizeId)(L||F);const se=l.getSchemaRefs.call(this,P,F);return ee=new i.SchemaEnv({schema:P,schemaId:G,meta:B,baseId:F,localRefs:se}),this._cache.set(ee.schema,ee),N&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=ee),E&&this.validateSchema(P,!0),ee}_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 B=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,P)}finally{this.opts=B}}}T.ValidationError=n.default,T.MissingRefError=o.default,e.default=T;function b(Z,P,B,F="error"){for(const E in Z){const N=E;N in P&&this.logger[F](`${B}: option ${E}. ${Z[N]}`)}}function k(Z){return Z=(0,l.normalizeId)(Z),this.schemas[Z]||this.refs[Z]}function S(){const Z=this.opts.schemas;if(Z)if(Array.isArray(Z))this.addSchema(Z);else for(const P in Z)this.addSchema(Z[P],P)}function I(){for(const Z in this.opts.formats){const P=this.opts.formats[Z];P&&this.addFormat(Z,P)}}function x(Z){if(Array.isArray(Z)){this.addVocabulary(Z);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const P in Z){const B=Z[P];B.keyword||(B.keyword=P),this.addKeyword(B)}}function j(){const Z={...this.opts};for(const P of g)delete Z[P];return Z}const M={log(){},warn(){},error(){}};function D(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 A=/^[a-z_$][a-z0-9_$:-]*$/i;function O(Z,P){const{RULES:B}=this;if((0,u.eachItem)(Z,F=>{if(B.keywords[F])throw new Error(`Keyword ${F} is already defined`);if(!A.test(F))throw new Error(`Keyword ${F} has invalid name`)}),!!P&&P.$data&&!("code"in P||"validate"in P))throw new Error('$data keyword must have "code" or "validate" function')}function H(Z,P,B){var F;const E=P?.post;if(B&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:N}=this;let L=E?N.post:N.rules.find(({type:ee})=>ee===B);if(L||(L={type:B,rules:[]},N.rules.push(L)),N.keywords[Z]=!0,!P)return;const G={keyword:Z,definition:{...P,type:(0,c.getJSONTypes)(P.type),schemaType:(0,c.getJSONTypes)(P.schemaType)}};P.before?Q.call(this,L,G,P.before):L.rules.push(G),N.all[Z]=G,(F=P.implements)===null||F===void 0||F.forEach(ee=>this.addKeyword(ee))}function Q(Z,P,B){const F=Z.rules.findIndex(E=>E.keyword===B);F>=0?Z.rules.splice(F,0,P):(Z.rules.push(P),this.logger.warn(`rule ${B} is not defined`))}function Y(Z){let{metaSchema:P}=Z;P!==void 0&&(Z.$data&&this.opts.$data&&(P=pe(P)),Z.validateSchema=this.compile(P,!0))}const W={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pe(Z){return{anyOf:[Z,W]}}})(Kc)),Kc}var Da={},za={},Fa={},hy;function Lx(){if(hy)return Fa;hy=1,Object.defineProperty(Fa,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Fa.default=e,Fa}var cn={},my;function jx(){if(my)return cn;my=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.callRef=cn.getValidate=void 0;const e=ja(),t=mr(),r=Re(),n=ln(),o=ou(),s=Le(),i={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:m,it:p}=c,{baseId:f,schemaEnv:g,validateName:v,opts:y,self:w}=p,{root:_}=g;if((m==="#"||m==="#/")&&f===_.baseId)return T();const h=o.resolveRef.call(w,_,f,m);if(h===void 0)throw new e.default(p.opts.uriResolver,f,m);if(h instanceof o.SchemaEnv)return b(h);return k(h);function T(){if(g===_)return l(c,v,g,g.$async);const S=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${S}.validate`,_,_.$async)}function b(S){const I=a(c,S);l(c,I,S,S.$async)}function k(S){const I=u.scopeValue("schema",y.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),x=u.name("valid"),j=c.subschema({schema:S,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:m},x);c.mergeEvaluated(j),c.ok(x)}}};function a(c,u){const{gen:m}=c;return u.validate?m.scopeValue("validate",{ref:u.validate}):(0,r._)`${m.scopeValue("wrapper",{ref:u})}.validate`}cn.getValidate=a;function l(c,u,m,p){const{gen:f,it:g}=c,{allErrors:v,schemaEnv:y,opts:w}=g,_=w.passContext?n.default.this:r.nil;p?h():T();function h(){if(!y.$async)throw new Error("async schema referenced by sync schema");const S=f.let("valid");f.try(()=>{f.code((0,r._)`await ${(0,t.callValidateCode)(c,u,_)}`),k(u),v||f.assign(S,!0)},I=>{f.if((0,r._)`!(${I} instanceof ${g.ValidationError})`,()=>f.throw(I)),b(I),v||f.assign(S,!1)}),c.ok(S)}function T(){c.result((0,t.callValidateCode)(c,u,_),()=>k(u),()=>b(u))}function b(S){const I=(0,r._)`${S}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${I} : ${n.default.vErrors}.concat(${I})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function k(S){var I;if(!g.opts.unevaluated)return;const x=(I=m?.validate)===null||I===void 0?void 0:I.evaluated;if(g.props!==!0)if(x&&!x.dynamicProps)x.props!==void 0&&(g.props=s.mergeEvaluated.props(f,x.props,g.props));else{const j=f.var("props",(0,r._)`${S}.evaluated.props`);g.props=s.mergeEvaluated.props(f,j,g.props,r.Name)}if(g.items!==!0)if(x&&!x.dynamicItems)x.items!==void 0&&(g.items=s.mergeEvaluated.items(f,x.items,g.items));else{const j=f.var("items",(0,r._)`${S}.evaluated.items`);g.items=s.mergeEvaluated.items(f,j,g.items,r.Name)}}}return cn.callRef=l,cn.default=i,cn}var gy;function Ux(){if(gy)return za;gy=1,Object.defineProperty(za,"__esModule",{value:!0});const e=Lx(),t=jx(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return za.default=r,za}var Va={},Za={},yy;function Dx(){if(yy)return Za;yy=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=Re(),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 Za.default=o,Za}var Ba={},_y;function zx(){if(_y)return Ba;_y=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=Re(),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 Ba.default=r,Ba}var Ha={},Ja={},vy;function Fx(){if(vy)return Ja;vy=1,Object.defineProperty(Ja,"__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 Ja.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Ja}var wy;function Vx(){if(wy)return Ha;wy=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e=Re(),t=Le(),r=Fx(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:i}){const a=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${i} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:i,data:a,schemaCode:l,it:c}=s,u=i==="maxLength"?e.operators.GT:e.operators.LT,m=c.opts.unicode===!1?(0,e._)`${a}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${a})`;s.fail$data((0,e._)`${m} ${u} ${l}`)}};return Ha.default=o,Ha}var Ga={},by;function Zx(){if(by)return Ga;by=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=mr(),t=Le(),r=Re(),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:i,data:a,$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)(i,f),v=i.let("valid");i.try(()=>i.assign(v,(0,r._)`${g}(${u}, ${p}).test(${a})`),()=>i.assign(v,!1)),s.fail$data((0,r._)`!${v}`)}else{const f=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${f}.test(${a})`)}}};return Ga.default=o,Ga}var Wa={},ky;function Bx(){if(ky)return Wa;ky=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=Re(),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 Wa.default=r,Wa}var Ka={},Cy;function Hx(){if(Cy)return Ka;Cy=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=mr(),t=Re(),r=Le(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:i,schema:a,schemaCode:l,data:c,$data:u,it:m}=s,{opts:p}=m;if(!u&&a.length===0)return;const f=a.length>=p.loopRequired;if(m.allErrors?g():v(),p.strictRequired){const _=s.parentSchema.properties,{definedProperties:h}=s.it;for(const T of a)if(_?.[T]===void 0&&!h.has(T)){const b=m.schemaEnv.baseId+m.errSchemaPath,k=`required property "${T}" is not defined at "${b}" (strictRequired)`;(0,r.checkStrictMode)(m,k,m.opts.strictRequired)}}function g(){if(f||u)s.block$data(t.nil,y);else for(const _ of a)(0,e.checkReportMissingProp)(s,_)}function v(){const _=i.let("missing");if(f||u){const h=i.let("valid",!0);s.block$data(h,()=>w(_,h)),s.ok(h)}else i.if((0,e.checkMissingProp)(s,a,_)),(0,e.reportMissingProp)(s,_),i.else()}function y(){i.forOf("prop",l,_=>{s.setParams({missingProperty:_}),i.if((0,e.noPropertyInData)(i,c,_,p.ownProperties),()=>s.error())})}function w(_,h){s.setParams({missingProperty:_}),i.forOf(_,l,()=>{i.assign(h,(0,e.propertyInData)(i,c,_,p.ownProperties)),i.if((0,t.not)(h),()=>{s.error(),i.break()})},t.nil)}}};return Ka.default=o,Ka}var Ya={},Ty;function Jx(){if(Ty)return Ya;Ty=1,Object.defineProperty(Ya,"__esModule",{value:!0});const e=Re(),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 Ya.default=r,Ya}var Qa={},Xa={},Sy;function iu(){if(Sy)return Xa;Sy=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=ty();return e.code='require("ajv/dist/runtime/equal").default',Xa.default=e,Xa}var Iy;function Gx(){if(Iy)return Qa;Iy=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=Ma(),t=Re(),r=Le(),n=iu(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:a}})=>(0,t.str)`must NOT have duplicate items (items ## ${a} and ${i} are identical)`,params:({params:{i,j:a}})=>(0,t._)`{i: ${i}, j: ${a}}`},code(i){const{gen:a,data:l,$data:c,schema:u,parentSchema:m,schemaCode:p,it:f}=i;if(!c&&!u)return;const g=a.let("valid"),v=m.items?(0,e.getSchemaTypes)(m.items):[];i.block$data(g,y,(0,t._)`${p} === false`),i.ok(g);function y(){const T=a.let("i",(0,t._)`${l}.length`),b=a.let("j");i.setParams({i:T,j:b}),a.assign(g,!0),a.if((0,t._)`${T} > 1`,()=>(w()?_:h)(T,b))}function w(){return v.length>0&&!v.some(T=>T==="object"||T==="array")}function _(T,b){const k=a.name("item"),S=(0,e.checkDataTypes)(v,k,f.opts.strictNumbers,e.DataType.Wrong),I=a.const("indices",(0,t._)`{}`);a.for((0,t._)`;${T}--;`,()=>{a.let(k,(0,t._)`${l}[${T}]`),a.if(S,(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(b,(0,t._)`${I}[${k}]`),i.error(),a.assign(g,!1).break()}).code((0,t._)`${I}[${k}] = ${T}`)})}function h(T,b){const k=(0,r.useFunc)(a,n.default),S=a.name("outer");a.label(S).for((0,t._)`;${T}--;`,()=>a.for((0,t._)`${b} = ${T}; ${b}--;`,()=>a.if((0,t._)`${k}(${l}[${T}], ${l}[${b}])`,()=>{i.error(),a.assign(g,!1).break(S)})))}}};return Qa.default=s,Qa}var ei={},xy;function Wx(){if(xy)return ei;xy=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Re(),t=Le(),r=iu(),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 ei.default=o,ei}var ti={},Ey;function Kx(){if(Ey)return ti;Ey=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Re(),t=Le(),r=iu(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:i,data:a,$data:l,schema:c,schemaCode:u,it:m}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=m.opts.loopEnum;let f;const g=()=>f??(f=(0,t.useFunc)(i,r.default));let v;if(p||l)v=i.let("valid"),s.block$data(v,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=i.const("vSchema",u);v=(0,e.or)(...c.map((h,T)=>w(_,T)))}s.pass(v);function y(){i.assign(v,!1),i.forOf("v",u,_=>i.if((0,e._)`${g()}(${a}, ${_})`,()=>i.assign(v,!0).break()))}function w(_,h){const T=c[h];return typeof T=="object"&&T!==null?(0,e._)`${g()}(${a}, ${_}[${h}])`:(0,e._)`${a} === ${T}`}}};return ti.default=o,ti}var $y;function Yx(){if($y)return Va;$y=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Dx(),t=zx(),r=Vx(),n=Zx(),o=Bx(),s=Hx(),i=Jx(),a=Gx(),l=Wx(),c=Kx(),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 Va.default=u,Va}var ri={},uo={},Ry;function Py(){if(Ry)return uo;Ry=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.validateAdditionalItems=void 0;const e=Re(),t=Le(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:i,it:a}=s,{items:l}=i;if(!Array.isArray(l)){(0,t.checkStrictMode)(a,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,i){const{gen:a,schema:l,data:c,keyword:u,it:m}=s;m.items=!0;const p=a.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:i.length}),s.pass((0,e._)`${p} <= ${i.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(m,l)){const g=a.var("valid",(0,e._)`${p} <= ${i.length}`);a.if((0,e.not)(g),()=>f(g)),s.ok(g)}function f(g){a.forRange("i",i.length,p,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},g),m.allErrors||a.if((0,e.not)(g),()=>a.break())})}}return uo.validateAdditionalItems=o,uo.default=n,uo}var ni={},po={},Ny;function My(){if(Ny)return po;Ny=1,Object.defineProperty(po,"__esModule",{value:!0}),po.validateTuple=void 0;const e=Re(),t=Le(),r=mr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:i,it:a}=s;if(Array.isArray(i))return o(s,"additionalItems",i);a.items=!0,!(0,t.alwaysValidSchema)(a,i)&&s.ok((0,r.validateArray)(s))}};function o(s,i,a=s.schema){const{gen:l,parentSchema:c,data:u,keyword:m,it:p}=s;v(c),p.opts.unevaluated&&a.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,a.length,p.items));const f=l.name("valid"),g=l.const("len",(0,e._)`${u}.length`);a.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=a.length,T=h===y.minItems&&(h===y.maxItems||y[i]===!1);if(w.strictTuples&&!T){const b=`"${m}" is ${h}-tuple, but minItems or maxItems/${i} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(p,b,w.strictTuples)}}}return po.validateTuple=o,po.default=n,po}var Oy;function Qx(){if(Oy)return ni;Oy=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=My(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return ni.default=t,ni}var oi={},Ay;function Xx(){if(Ay)return oi;Ay=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=Re(),t=Le(),r=mr(),n=Py(),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 oi.default=s,oi}var si={},qy;function e7(){if(qy)return si;qy=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Re(),t=Le(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:i,parentSchema:a,data:l,it:c}=o;let u,m;const{minContains:p,maxContains:f}=a;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,i)){let h=(0,e._)`${g} >= ${u}`;m!==void 0&&(h=(0,e._)`${h} && ${g} <= ${m}`),o.pass(h);return}c.items=!0;const v=s.name("valid");m===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),m!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(v,!1),y()),o.result(v,()=>o.reset());function y(){const h=s.name("_valid"),T=s.let("count",0);w(h,()=>s.if(h,()=>_(T)))}function w(h,T){s.forRange("i",0,g,b=>{o.subschema({keyword:"contains",dataProp:b,dataPropType:t.Type.Num,compositeRule:!0},h),T()})}function _(h){s.code((0,e._)`${h}++`),m===void 0?s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${h} > ${m}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0)))}}};return si.default=n,si}var lu={},Ly;function t7(){return Ly||(Ly=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Re(),r=Le(),n=mr();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},
|
|
85
|
+
|| ${I} === "boolean" || ${k} === null`).assign(x,(0,n._)`[${k}]`)}}}function p({gen:_,parentData:h,parentDataProperty:T},b){_.if((0,n._)`${h} !== undefined`,()=>_.assign((0,n._)`${h}[${T}]`,b))}function f(_,h,T,b=s.Correct){const k=b===s.Correct?n.operators.EQ:n.operators.NEQ;let S;switch(_){case"null":return(0,n._)`${h} ${k} null`;case"array":S=(0,n._)`Array.isArray(${h})`;break;case"object":S=(0,n._)`${h} && typeof ${h} == "object" && !Array.isArray(${h})`;break;case"integer":S=I((0,n._)`!(${h} % 1) && !isNaN(${h})`);break;case"number":S=I();break;default:return(0,n._)`typeof ${h} ${k} ${_}`}return b===s.Correct?S:(0,n.not)(S);function I(x=n.nil){return(0,n.and)((0,n._)`typeof ${h} == "number"`,x,T?(0,n._)`isFinite(${h})`:n.nil)}}Pt.checkDataType=f;function g(_,h,T,b){if(_.length===1)return f(_[0],h,T,b);let k;const S=(0,o.toHash)(_);if(S.array&&S.object){const I=(0,n._)`typeof ${h} != "object"`;k=S.null?I:(0,n._)`!${h} || ${I}`,delete S.null,delete S.array,delete S.object}else k=n.nil;S.number&&delete S.integer;for(const I in S)k=(0,n.and)(k,f(I,h,T,b));return k}Pt.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)}Pt.reportTypeError=y;function w(_){const{gen:h,data:T,schema:b}=_,k=(0,o.schemaRefOrVal)(_,b,"type");return{gen:h,keyword:"type",data:T,schema:b.type,schemaCode:k,schemaValue:k,parentSchema:b,params:{},it:_}}return Pt}var ps={},ey;function Ox(){if(ey)return ps;ey=1,Object.defineProperty(ps,"__esModule",{value:!0}),ps.assignDefaults=void 0;const e=Re(),t=Le();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))}ps.assignDefaults=r;function n(o,s,i){const{gen:a,compositeRule:l,data:c,opts:u}=o;if(i===void 0)return;const m=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${m}`);return}let p=(0,e._)`${m} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${m} === null || ${m} === ""`),a.if(p,(0,e._)`${m} = ${(0,e.stringify)(i)}`)}return ps}var mr={},Ze={},ty;function gr(){if(ty)return Ze;ty=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=Re(),t=Le(),r=cn(),n=Le();function o(_,h){const{gen:T,data:b,it:k}=_;T.if(u(T,b,h,k.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${h}`},!0),_.error()})}Ze.checkReportMissingProp=o;function s({gen:_,data:h,it:{opts:T}},b,k){return(0,e.or)(...b.map(S=>(0,e.and)(u(_,h,S,T.ownProperties),(0,e._)`${k} = ${S}`)))}Ze.checkMissingProp=s;function i(_,h){_.setParams({missingProperty:h},!0),_.error()}Ze.reportMissingProp=i;function a(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ze.hasPropFunc=a;function l(_,h,T){return(0,e._)`${a(_)}.call(${h}, ${T})`}Ze.isOwnProperty=l;function c(_,h,T,b){const k=(0,e._)`${h}${(0,e.getProperty)(T)} !== undefined`;return b?(0,e._)`${k} && ${l(_,h,T)}`:k}Ze.propertyInData=c;function u(_,h,T,b){const k=(0,e._)`${h}${(0,e.getProperty)(T)} === undefined`;return b?(0,e.or)(k,(0,e.not)(l(_,h,T))):k}Ze.noPropertyInData=u;function m(_){return _?Object.keys(_).filter(h=>h!=="__proto__"):[]}Ze.allSchemaProperties=m;function p(_,h){return m(h).filter(T=>!(0,t.alwaysValidSchema)(_,h[T]))}Ze.schemaProperties=p;function f({schemaCode:_,data:h,it:{gen:T,topSchemaRef:b,schemaPath:k,errorPath:S},it:I},x,j,M){const D=M?(0,e._)`${_}, ${h}, ${b}${k}`:h,A=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,S)],[r.default.parentData,I.parentData],[r.default.parentDataProperty,I.parentDataProperty],[r.default.rootData,r.default.rootData]];I.opts.dynamicRef&&A.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const O=(0,e._)`${D}, ${T.object(...A)}`;return j!==e.nil?(0,e._)`${x}.call(${j}, ${O})`:(0,e._)`${x}(${O})`}Ze.callValidateCode=f;const g=(0,e._)`new RegExp`;function v({gen:_,it:{opts:h}},T){const b=h.unicodeRegExp?"u":"",{regExp:k}=h.code,S=k(T,b);return _.scopeValue("pattern",{key:S.toString(),ref:S,code:(0,e._)`${k.code==="new RegExp"?g:(0,n.useFunc)(_,k)}(${T}, ${b})`})}Ze.usePattern=v;function y(_){const{gen:h,data:T,keyword:b,it:k}=_,S=h.name("valid");if(k.allErrors){const x=h.let("valid",!0);return I(()=>h.assign(x,!1)),x}return h.var(S,!0),I(()=>h.break()),S;function I(x){const j=h.const("len",(0,e._)`${T}.length`);h.forRange("i",0,j,M=>{_.subschema({keyword:b,dataProp:M,dataPropType:t.Type.Num},S),h.if((0,e.not)(S),x)})}}Ze.validateArray=y;function w(_){const{gen:h,schema:T,keyword:b,it:k}=_;if(!Array.isArray(T))throw new Error("ajv implementation error");if(T.some(j=>(0,t.alwaysValidSchema)(k,j))&&!k.opts.unevaluated)return;const I=h.let("valid",!1),x=h.name("_valid");h.block(()=>T.forEach((j,M)=>{const D=_.subschema({keyword:b,schemaProp:M,compositeRule:!0},x);h.assign(I,(0,e._)`${I} || ${x}`),_.mergeValidEvaluated(D,x)||h.if((0,e.not)(I))})),_.result(I,()=>_.reset(),()=>_.error(!0))}return Ze.validateUnion=w,Ze}var ry;function Ax(){if(ry)return mr;ry=1,Object.defineProperty(mr,"__esModule",{value:!0}),mr.validateKeywordUsage=mr.validSchemaType=mr.funcKeywordCode=mr.macroKeywordCode=void 0;const e=Re(),t=cn(),r=gr(),n=qa();function o(p,f){const{gen:g,keyword:v,schema:y,parentSchema:w,it:_}=p,h=f.macro.call(_.self,y,w,_),T=c(g,v,h);_.opts.validateSchema!==!1&&_.self.validateSchema(h,!0);const b=g.name("valid");p.subschema({schema:h,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${v}`,topSchemaRef:T,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}mr.macroKeywordCode=o;function s(p,f){var g;const{gen:v,keyword:y,schema:w,parentSchema:_,$data:h,it:T}=p;l(T,f);const b=!h&&f.compile?f.compile.call(T.self,w,_,T):f.validate,k=c(v,y,b),S=v.let("valid");p.block$data(S,I),p.ok((g=f.valid)!==null&&g!==void 0?g:S);function I(){if(f.errors===!1)M(),f.modifying&&i(p),D(()=>p.error());else{const A=f.async?x():j();f.modifying&&i(p),D(()=>a(p,A))}}function x(){const A=v.let("ruleErrs",null);return v.try(()=>M((0,e._)`await `),O=>v.assign(S,!1).if((0,e._)`${O} instanceof ${T.ValidationError}`,()=>v.assign(A,(0,e._)`${O}.errors`),()=>v.throw(O))),A}function j(){const A=(0,e._)`${k}.errors`;return v.assign(A,null),M(e.nil),A}function M(A=f.async?(0,e._)`await `:e.nil){const O=T.opts.passContext?t.default.this:t.default.self,H=!("compile"in f&&!h||f.schema===!1);v.assign(S,(0,e._)`${A}${(0,r.callValidateCode)(p,k,O,H)}`,f.modifying)}function D(A){var O;v.if((0,e.not)((O=f.valid)!==null&&O!==void 0?O:S),A)}}mr.funcKeywordCode=s;function i(p){const{gen:f,data:g,it:v}=p;f.if(v.parentData,()=>f.assign(g,(0,e._)`${v.parentData}[${v.parentDataProperty}]`))}function a(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")}mr.validSchemaType=u;function m({schema:p,opts:f,self:g,errSchemaPath:v},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const _=y.dependencies;if(_?.some(h=>!Object.prototype.hasOwnProperty.call(p,h)))throw new Error(`parent schema must have dependencies of ${w}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const T=`keyword "${w}" value is invalid at path "${v}": `+g.errorsText(y.validateSchema.errors);if(f.validateSchema==="log")g.logger.error(T);else throw new Error(T)}}return mr.validateKeywordUsage=m,mr}var Fr={},ny;function qx(){if(ny)return Fr;ny=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.extendSubschemaMode=Fr.extendSubschemaData=Fr.getSubschema=void 0;const e=Re(),t=Le();function r(s,{keyword:i,schemaProp:a,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:m}){if(i!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(i!==void 0){const p=s.schema[i];return a===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${i}`}:{schema:p[a],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(i)}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${i}/${(0,t.escapeFragment)(a)}`}}if(l!==void 0){if(c===void 0||u===void 0||m===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:m,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}Fr.getSubschema=r;function n(s,i,{dataProp:a,dataPropType:l,data:c,dataTypes:u,propertyName:m}){if(c!==void 0&&a!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=i;if(a!==void 0){const{errorPath:g,dataPathArr:v,opts:y}=i,w=p.let("data",(0,e._)`${i.data}${(0,e.getProperty)(a)}`,!0);f(w),s.errorPath=(0,e.str)`${g}${(0,t.getErrorPath)(a,l,y.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${a}`,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=i.dataLevel+1,s.dataTypes=[],i.definedProperties=new Set,s.parentData=i.data,s.dataNames=[...i.dataNames,g]}}Fr.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 Fr.extendSubschemaMode=o,Fr}var Ut={},du,oy;function sy(){return oy||(oy=1,du=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}),du}var pu={exports:{}},ay;function Lx(){if(ay)return pu.exports;ay=1;var e=pu.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var i=typeof s=="function"?s:s.pre||function(){},a=s.post||function(){};t(o,i,a,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,i,a,l,c,u,m,p){if(i&&typeof i=="object"&&!Array.isArray(i)){o(i,a,l,c,u,m,p);for(var f in i){var g=i[f];if(Array.isArray(g)){if(f in e.arrayKeywords)for(var v=0;v<g.length;v++)t(n,o,s,g[v],a+"/"+f+"/"+v,l,a,f,i,v)}else if(f in e.propsKeywords){if(g&&typeof g=="object")for(var y in g)t(n,o,s,g[y],a+"/"+f+"/"+r(y),l,a,f,i,y)}else(f in e.keywords||n.allKeys&&!(f in e.skipKeywords))&&t(n,o,s,g,a+"/"+f,l,a,f,i)}s(i,a,l,c,u,m,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return pu.exports}var iy;function ja(){if(iy)return Ut;iy=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.getSchemaRefs=Ut.resolveUrl=Ut.normalizeId=Ut._getFullPath=Ut.getFullPath=Ut.inlineRef=void 0;const e=Le(),t=sy(),r=Lx(),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?!i(v):y?a(v)<=y:!1}Ut.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(v){for(const y in v){if(s.has(y))return!0;const w=v[y];if(Array.isArray(w)&&w.some(i)||typeof w=="object"&&i(w))return!0}return!1}function a(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+=a(_)),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,_)}Ut.getFullPath=l;function c(v,y){return v.serialize(y).split("#")[0]+"#"}Ut._getFullPath=c;const u=/#\/?$/;function m(v){return v?v.replace(u,""):""}Ut.normalizeId=m;function p(v,y,w){return w=m(w),v.resolve(y,w)}Ut.resolveUrl=p;const f=/^[a-z_][-a-z0-9._]*$/i;function g(v,y){if(typeof v=="boolean")return{};const{schemaId:w,uriResolver:_}=this.opts,h=m(v[w]||y),T={"":h},b=l(_,h,!1),k={},S=new Set;return r(v,{allKeys:!0},(j,M,D,A)=>{if(A===void 0)return;const O=b+M;let H=T[A];typeof j[w]=="string"&&(H=Q.call(this,j[w])),Y.call(this,j.$anchor),Y.call(this,j.$dynamicAnchor),T[M]=H;function Q(W){const pe=this.opts.uriResolver.resolve;if(W=m(H?pe(H,W):W),S.has(W))throw x(W);S.add(W);let Z=this.refs[W];return typeof Z=="string"&&(Z=this.refs[Z]),typeof Z=="object"?I(j,Z.schema,W):W!==m(O)&&(W[0]==="#"?(I(j,k[W],W),k[W]=j):this.refs[W]=O),W}function Y(W){if(typeof W=="string"){if(!f.test(W))throw new Error(`invalid anchor "${W}"`);Q.call(this,`#${W}`)}}}),k;function I(j,M,D){if(M!==void 0&&!t(j,M))throw x(D)}function x(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return Ut.getSchemaRefs=g,Ut}var ly;function Ua(){if(ly)return Dr;ly=1,Object.defineProperty(Dr,"__esModule",{value:!0}),Dr.getData=Dr.KeywordCxt=Dr.validateFunctionCode=void 0;const e=Mx(),t=La(),r=Qg(),n=La(),o=Ox(),s=Ax(),i=qx(),a=Re(),l=cn(),c=ja(),u=Le(),m=qa();function p(z){if(b(z)&&(S(z),T(z))){y(z);return}f(z,()=>(0,e.topBoolOrEmptySchema)(z))}Dr.validateFunctionCode=p;function f({gen:z,validateName:V,schema:K,schemaEnv:X,opts:le},Te){le.code.es5?z.func(V,(0,a._)`${l.default.data}, ${l.default.valCxt}`,X.$async,()=>{z.code((0,a._)`"use strict"; ${_(K,le)}`),v(z,le),z.code(Te)}):z.func(V,(0,a._)`${l.default.data}, ${g(le)}`,X.$async,()=>z.code(_(K,le)).code(Te))}function g(z){return(0,a._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${z.dynamicRef?(0,a._)`, ${l.default.dynamicAnchors}={}`:a.nil}}={}`}function v(z,V){z.if(l.default.valCxt,()=>{z.var(l.default.instancePath,(0,a._)`${l.default.valCxt}.${l.default.instancePath}`),z.var(l.default.parentData,(0,a._)`${l.default.valCxt}.${l.default.parentData}`),z.var(l.default.parentDataProperty,(0,a._)`${l.default.valCxt}.${l.default.parentDataProperty}`),z.var(l.default.rootData,(0,a._)`${l.default.valCxt}.${l.default.rootData}`),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,a._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{z.var(l.default.instancePath,(0,a._)`""`),z.var(l.default.parentData,(0,a._)`undefined`),z.var(l.default.parentDataProperty,(0,a._)`undefined`),z.var(l.default.rootData,l.default.data),V.dynamicRef&&z.var(l.default.dynamicAnchors,(0,a._)`{}`)})}function y(z){const{schema:V,opts:K,gen:X}=z;f(z,()=>{K.$comment&&V.$comment&&A(z),j(z),X.let(l.default.vErrors,null),X.let(l.default.errors,0),K.unevaluated&&w(z),I(z),O(z)})}function w(z){const{gen:V,validateName:K}=z;z.evaluated=V.const("evaluated",(0,a._)`${K}.evaluated`),V.if((0,a._)`${z.evaluated}.dynamicProps`,()=>V.assign((0,a._)`${z.evaluated}.props`,(0,a._)`undefined`)),V.if((0,a._)`${z.evaluated}.dynamicItems`,()=>V.assign((0,a._)`${z.evaluated}.items`,(0,a._)`undefined`))}function _(z,V){const K=typeof z=="object"&&z[V.schemaId];return K&&(V.code.source||V.code.process)?(0,a._)`/*# sourceURL=${K} */`:a.nil}function h(z,V){if(b(z)&&(S(z),T(z))){k(z,V);return}(0,e.boolOrEmptySchema)(z,V)}function T({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 b(z){return typeof z.schema!="boolean"}function k(z,V){const{schema:K,gen:X,opts:le}=z;le.$comment&&K.$comment&&A(z),M(z),D(z);const Te=X.const("_errs",l.default.errors);I(z,Te),X.var(V,(0,a._)`${Te} === ${l.default.errors}`)}function S(z){(0,u.checkUnknownRules)(z),x(z)}function I(z,V){if(z.opts.jtd)return Q(z,[],!1,V);const K=(0,t.getSchemaTypes)(z.schema),X=(0,t.coerceAndCheckDataType)(z,K);Q(z,K,!X,V)}function x(z){const{schema:V,errSchemaPath:K,opts:X,self:le}=z;V.$ref&&X.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(V,le.RULES)&&le.logger.warn(`$ref: keywords ignored in schema at path "${K}"`)}function j(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 D(z){if(z.schema.$async&&!z.schemaEnv.$async)throw new Error("async schema in sync schema")}function A({gen:z,schemaEnv:V,schema:K,errSchemaPath:X,opts:le}){const Te=K.$comment;if(le.$comment===!0)z.code((0,a._)`${l.default.self}.logger.log(${Te})`);else if(typeof le.$comment=="function"){const Fe=(0,a.str)`${X}/$comment`,tt=z.scopeValue("root",{ref:V.root});z.code((0,a._)`${l.default.self}.opts.$comment(${Te}, ${Fe}, ${tt}.schema)`)}}function O(z){const{gen:V,schemaEnv:K,validateName:X,ValidationError:le,opts:Te}=z;K.$async?V.if((0,a._)`${l.default.errors} === 0`,()=>V.return(l.default.data),()=>V.throw((0,a._)`new ${le}(${l.default.vErrors})`)):(V.assign((0,a._)`${X}.errors`,l.default.vErrors),Te.unevaluated&&H(z),V.return((0,a._)`${l.default.errors} === 0`))}function H({gen:z,evaluated:V,props:K,items:X}){K instanceof a.Name&&z.assign((0,a._)`${V}.props`,K),X instanceof a.Name&&z.assign((0,a._)`${V}.items`,X)}function Q(z,V,K,X){const{gen:le,schema:Te,data:Fe,allErrors:tt,opts:ut,self:Ye}=z,{RULES:$}=Ye;if(Te.$ref&&(ut.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(Te,$))){le.block(()=>G(z,"$ref",$.all.$ref.definition));return}ut.jtd||W(z,V),le.block(()=>{for(const Ae of $.rules)re(Ae);re($.post)});function re(Ae){(0,r.shouldUseGroup)(Te,Ae)&&(Ae.type?(le.if((0,n.checkDataType)(Ae.type,Fe,ut.strictNumbers)),Y(z,Ae),V.length===1&&V[0]===Ae.type&&K&&(le.else(),(0,n.reportTypeError)(z)),le.endIf()):Y(z,Ae),tt||le.if((0,a._)`${l.default.errors} === ${X||0}`))}}function Y(z,V){const{gen:K,schema:X,opts:{useDefaults:le}}=z;le&&(0,o.assignDefaults)(z,V.type),K.block(()=>{for(const Te of V.rules)(0,r.shouldUseRule)(X,Te)&&G(z,Te.keyword,Te.definition,V.type)})}function W(z,V){z.schemaEnv.meta||!z.opts.strictTypes||(pe(z,V),z.opts.allowUnionTypes||Z(z,V),P(z,z.dataTypes))}function pe(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(",")}"`)}),E(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 P(z,V){const K=z.self.RULES.all;for(const X in K){const le=K[X];if(typeof le=="object"&&(0,r.shouldUseRule)(z.schema,le)){const{type:Te}=le.definition;Te.length&&!Te.some(Fe=>B(V,Fe))&&N(z,`missing type "${Te.join(",")}" for keyword "${X}"`)}}}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 E(z,V){const K=[];for(const X of z.dataTypes)F(V,X)?K.push(X):V.includes("integer")&&X==="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 L{constructor(V,K,X){if((0,s.validateKeywordUsage)(V,K,X),this.gen=V.gen,this.allErrors=V.allErrors,this.keyword=X,this.data=V.data,this.schema=V.schema[X],this.$data=K.$data&&V.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(V,this.schema,X,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",ke(this.$data,V));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,K.schemaType,K.allowUndefined))throw new Error(`${X} 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,X){this.failResult((0,a.not)(V),K,X)}failResult(V,K,X){this.gen.if(V),X?X():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,a.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,a._)`${K} !== undefined && (${(0,a.or)(this.invalid$data(),V)})`)}error(V,K,X){if(K){this.setParams(K),this._error(V,X),this.setParams({});return}this._error(V,X)}_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,X=a.nil){this.gen.block(()=>{this.check$data(V,X),K()})}check$data(V=a.nil,K=a.nil){if(!this.$data)return;const{gen:X,schemaCode:le,schemaType:Te,def:Fe}=this;X.if((0,a.or)((0,a._)`${le} === undefined`,K)),V!==a.nil&&X.assign(V,!0),(Te.length||Fe.validateSchema)&&(X.elseIf(this.invalid$data()),this.$dataError(),V!==a.nil&&X.assign(V,!1)),X.else()}invalid$data(){const{gen:V,schemaCode:K,schemaType:X,def:le,it:Te}=this;return(0,a.or)(Fe(),tt());function Fe(){if(X.length){if(!(K instanceof a.Name))throw new Error("ajv implementation error");const ut=Array.isArray(X)?X:[X];return(0,a._)`${(0,n.checkDataTypes)(ut,K,Te.opts.strictNumbers,n.DataType.Wrong)}`}return a.nil}function tt(){if(le.validateSchema){const ut=V.scopeValue("validate$data",{ref:le.validateSchema});return(0,a._)`!${ut}(${K})`}return a.nil}}subschema(V,K){const X=(0,i.getSubschema)(this.it,V);(0,i.extendSubschemaData)(X,this.it,V),(0,i.extendSubschemaMode)(X,V);const le={...this.it,...X,items:void 0,props:void 0};return h(le,K),le}mergeEvaluated(V,K){const{it:X,gen:le}=this;X.opts.unevaluated&&(X.props!==!0&&V.props!==void 0&&(X.props=u.mergeEvaluated.props(le,V.props,X.props,K)),X.items!==!0&&V.items!==void 0&&(X.items=u.mergeEvaluated.items(le,V.items,X.items,K)))}mergeValidEvaluated(V,K){const{it:X,gen:le}=this;if(X.opts.unevaluated&&(X.props!==!0||X.items!==!0))return le.if(K,()=>this.mergeEvaluated(V,a.Name)),!0}}Dr.KeywordCxt=L;function G(z,V,K,X){const le=new L(z,K,V);"code"in K?K.code(le,X):le.$data&&K.validate?(0,s.funcKeywordCode)(le,K):"macro"in K?(0,s.macroKeywordCode)(le,K):(K.compile||K.validate)&&(0,s.funcKeywordCode)(le,K)}const ee=/^\/(?:[^~]|~0|~1)*$/,se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ke(z,{dataLevel:V,dataNames:K,dataPathArr:X}){let le,Te;if(z==="")return l.default.rootData;if(z[0]==="/"){if(!ee.test(z))throw new Error(`Invalid JSON-pointer: ${z}`);le=z,Te=l.default.rootData}else{const Ye=se.exec(z);if(!Ye)throw new Error(`Invalid JSON-pointer: ${z}`);const $=+Ye[1];if(le=Ye[2],le==="#"){if($>=V)throw new Error(ut("property/index",$));return X[V-$]}if($>V)throw new Error(ut("data",$));if(Te=K[V-$],!le)return Te}let Fe=Te;const tt=le.split("/");for(const Ye of tt)Ye&&(Te=(0,a._)`${Te}${(0,a.getProperty)((0,u.unescapeJsonPointer)(Ye))}`,Fe=(0,a._)`${Fe} && ${Te}`);return Fe;function ut(Ye,$){return`Cannot access ${Ye} ${$} levels up, current level is ${V}`}}return Dr.getData=ke,Dr}var Da={},cy;function fu(){if(cy)return Da;cy=1,Object.defineProperty(Da,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Da.default=e,Da}var za={},uy;function Fa(){if(uy)return za;uy=1,Object.defineProperty(za,"__esModule",{value:!0});const e=ja();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 za.default=t,za}var Yt={},dy;function hu(){if(dy)return Yt;dy=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;const e=Re(),t=fu(),r=cn(),n=ja(),o=Le(),s=Ua();class i{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={}}}Yt.SchemaEnv=i;function a(y){const w=u.call(this,y);if(w)return w;const _=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:h,lines:T}=this.opts.code,{ownProperties:b}=this.opts,k=new e.CodeGen(this.scope,{es5:h,lines:T,ownProperties:b});let S;y.$async&&(S=k.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const I=k.scopeName("validate");y.validateName=I;const x={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:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:I,ValidationError:S,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(y),(0,s.validateFunctionCode)(x),k.optimize(this.opts.code.optimize);const M=k.toString();j=`${k.scopeRefs(r.default.scope)}return ${M}`,this.opts.code.process&&(j=this.opts.code.process(j,y));const A=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(I,{ref:A}),A.errors=null,A.schema=y.schema,A.schemaEnv=y,y.$async&&(A.$async=!0),this.opts.code.source===!0&&(A.source={validateName:I,validateCode:M,scopeValues:k._values}),this.opts.unevaluated){const{props:O,items:H}=x;A.evaluated={props:O instanceof e.Name?void 0:O,items:H instanceof e.Name?void 0:H,dynamicProps:O instanceof e.Name,dynamicItems:H instanceof e.Name},A.source&&(A.source.evaluated=(0,e.stringify)(A.evaluated))}return y.validate=A,y}catch(M){throw delete y.validate,delete y.validateName,j&&this.logger.error("Error compiling schema, function code:",j),M}finally{this._compilations.delete(y)}}Yt.compileSchema=a;function l(y,w,_){var h;_=(0,n.resolveUrl)(this.opts.uriResolver,w,_);const T=y.refs[_];if(T)return T;let b=p.call(this,y,_);if(b===void 0){const k=(h=y.localRefs)===null||h===void 0?void 0:h[_],{schemaId:S}=this.opts;k&&(b=new i({schema:k,schemaId:S,root:y,baseId:w}))}if(b!==void 0)return y.refs[_]=c.call(this,b)}Yt.resolveRef=l;function c(y){return(0,n.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:a.call(this,y)}function u(y){for(const w of this._compilations)if(m(w,y))return w}Yt.getCompilingSchema=u;function m(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let _;for(;typeof(_=this.refs[w])=="string";)w=_;return _||this.schemas[w]||f.call(this,y,w)}function f(y,w){const _=this.opts.uriResolver.parse(w),h=(0,n._getFullPath)(this.opts.uriResolver,_);let T=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&h===T)return v.call(this,_,y);const b=(0,n.normalizeId)(h),k=this.refs[b]||this.schemas[b];if(typeof k=="string"){const S=f.call(this,y,k);return typeof S?.schema!="object"?void 0:v.call(this,_,S)}if(typeof k?.schema=="object"){if(k.validate||a.call(this,k),b===(0,n.normalizeId)(w)){const{schema:S}=k,{schemaId:I}=this.opts,x=S[I];return x&&(T=(0,n.resolveUrl)(this.opts.uriResolver,T,x)),new i({schema:S,schemaId:I,root:y,baseId:T})}return v.call(this,_,k)}}Yt.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function v(y,{baseId:w,schema:_,root:h}){var T;if(((T=y.fragment)===null||T===void 0?void 0:T[0])!=="/")return;for(const S of y.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const I=_[(0,o.unescapeFragment)(S)];if(I===void 0)return;_=I;const x=typeof _=="object"&&_[this.opts.schemaId];!g.has(S)&&x&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,x))}let b;if(typeof _!="boolean"&&_.$ref&&!(0,o.schemaHasRulesButRef)(_,this.RULES)){const S=(0,n.resolveUrl)(this.opts.uriResolver,w,_.$ref);b=f.call(this,h,S)}const{schemaId:k}=this.opts;if(b=b||new i({schema:_,schemaId:k,root:h,baseId:w}),b.schema!==b.root.schema)return b}return Yt}const jx={$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 Va={},fs={exports:{}},mu,py;function fy(){if(py)return mu;py=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 i(p){let f=0;const g={error:!1,address:"",zone:""},v=[],y=[];let w=!1,_=!1,h=s;for(let T=0;T<p.length;T++){const b=p[T];if(!(b==="["||b==="]"))if(b===":"){if(w===!0&&(_=!0),!h(y,v,g))break;if(++f>7){g.error=!0;break}T>0&&p[T-1]===":"&&(w=!0),v.push(":");continue}else if(b==="%"){if(!h(y,v,g))break;h=o}else{y.push(b);continue}}return y.length&&(h===o?g.zone=y.join(""):_?v.push(y.join("")):v.push(r(y))),g.address=v.join(""),g}function a(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const f=i(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=a(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 mu={nonSimpleDomain:n,recomposeAuthority:m,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:a,stringArrayToHexStripped:r},mu}var gu,hy;function Ux(){if(hy)return gu;hy=1;const{isUUID:e}=fy(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(b){return r.indexOf(b)!==-1}function o(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function i(b){const k=String(b.scheme).toLowerCase()==="https";return(b.port===(k?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function a(b){return b.secure=o(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(o(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){const[k,S]=b.resourceName.split("?");b.path=k&&k!=="/"?k:void 0,b.query=S,b.resourceName=void 0}return b.fragment=void 0,b}function c(b,k){if(!b.path)return b.error="URN can not be parsed",b;const S=b.path.match(t);if(S){const I=k.scheme||b.scheme||"urn";b.nid=S[1].toLowerCase(),b.nss=S[2];const x=`${I}:${k.nid||b.nid}`,j=T(x);b.path=void 0,j&&(b=j.parse(b,k))}else b.error=b.error||"URN can not be parsed.";return b}function u(b,k){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");const S=k.scheme||b.scheme||"urn",I=b.nid.toLowerCase(),x=`${S}:${k.nid||I}`,j=T(x);j&&(b=j.serialize(b,k));const M=b,D=b.nss;return M.path=`${I||k.nid}:${D}`,k.skipEscape=!0,M}function m(b,k){const S=b;return S.uuid=S.nss,S.nss=void 0,!k.tolerant&&(!S.uuid||!e(S.uuid))&&(S.error=S.error||"UUID is not valid."),S}function p(b){const k=b;return k.nss=(b.uuid||"").toLowerCase(),k}const f={scheme:"http",domainHost:!0,parse:s,serialize:i},g={scheme:"https",domainHost:f.domainHost,parse:s,serialize:i},v={scheme:"ws",domainHost:!0,parse:a,serialize:l},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},h={http:f,https:g,ws:v,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:m,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(h,null);function T(b){return b&&(h[b]||h[b.toLowerCase()])||void 0}return gu={wsIsSecure:o,SCHEMES:h,isValidSchemeName:n,getSchemeHandler:T},gu}var my;function Dx(){if(my)return fs.exports;my=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=fy(),{SCHEMES:i,getSchemeHandler:a}=Ux();function l(y,w){return typeof y=="string"?y=p(g(y,w),w):typeof y=="object"&&(y=g(p(y,w),w)),y}function c(y,w,_){const h=_?Object.assign({scheme:"null"},_):{scheme:"null"},T=u(g(y,h),g(w,h),h,!0);return h.skipEscape=!0,p(T,h)}function u(y,w,_,h){const T={};return h||(y=g(p(y,_),_),w=g(p(w,_),_)),_=_||{},!_.tolerant&&w.scheme?(T.scheme=w.scheme,T.userinfo=w.userinfo,T.host=w.host,T.port=w.port,T.path=t(w.path||""),T.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(T.userinfo=w.userinfo,T.host=w.host,T.port=w.port,T.path=t(w.path||""),T.query=w.query):(w.path?(w.path[0]==="/"?T.path=t(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?T.path="/"+w.path:y.path?T.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:T.path=w.path,T.path=t(T.path)),T.query=w.query):(T.path=y.path,w.query!==void 0?T.query=w.query:T.query=y.query),T.userinfo=y.userinfo,T.host=y.host,T.port=y.port),T.scheme=y.scheme),T.fragment=w.fragment,T}function m(y,w,_){return typeof y=="string"?(y=unescape(y),y=p(n(g(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{..._,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(g(w,_),!0),{..._,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{..._,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const _={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},h=Object.assign({},w),T=[],b=a(h.scheme||_.scheme);b&&b.serialize&&b.serialize(_,h),_.path!==void 0&&(h.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),h.reference!=="suffix"&&_.scheme&&T.push(_.scheme,":");const k=r(_);if(k!==void 0&&(h.reference!=="suffix"&&T.push("//"),T.push(k),_.path&&_.path[0]!=="/"&&T.push("/")),_.path!==void 0){let S=_.path;!h.absolutePath&&(!b||!b.absolutePath)&&(S=t(S)),k===void 0&&S[0]==="/"&&S[1]==="/"&&(S="/%2F"+S.slice(2)),T.push(S)}return _.query!==void 0&&T.push("?",_.query),_.fragment!==void 0&&T.push("#",_.fragment),T.join("")}const f=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(y,w){const _=Object.assign({},w),h={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let T=!1;_.reference==="suffix"&&(_.scheme?y=_.scheme+":"+y:y="//"+y);const b=y.match(f);if(b){if(h.scheme=b[1],h.userinfo=b[3],h.host=b[4],h.port=parseInt(b[5],10),h.path=b[6]||"",h.query=b[7],h.fragment=b[8],isNaN(h.port)&&(h.port=b[5]),h.host)if(o(h.host)===!1){const I=e(h.host);h.host=I.host.toLowerCase(),T=I.isIPV6}else T=!0;h.scheme===void 0&&h.userinfo===void 0&&h.host===void 0&&h.port===void 0&&h.query===void 0&&!h.path?h.reference="same-document":h.scheme===void 0?h.reference="relative":h.fragment===void 0?h.reference="absolute":h.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==h.reference&&(h.error=h.error||"URI is not a "+_.reference+" reference.");const k=a(_.scheme||h.scheme);if(!_.unicodeSupport&&(!k||!k.unicodeSupport)&&h.host&&(_.domainHost||k&&k.domainHost)&&T===!1&&s(h.host))try{h.host=URL.domainToASCII(h.host.toLowerCase())}catch(S){h.error=h.error||"Host's domain name can not be converted to ASCII: "+S}(!k||k&&!k.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)))),k&&k.parse&&k.parse(h,_)}else h.error=h.error||"URI can not be parsed.";return h}const v={SCHEMES:i,normalize:l,resolve:c,resolveComponent:u,equal:m,serialize:p,parse:g};return fs.exports=v,fs.exports.default=v,fs.exports.fastUri=v,fs.exports}var gy;function zx(){if(gy)return Va;gy=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Dx();return e.code='require("ajv/dist/runtime/uri").default',Va.default=e,Va}var yy;function Fx(){return yy||(yy=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=Ua();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Re();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=fu(),o=Fa(),s=Kg(),i=hu(),a=Re(),l=ja(),c=La(),u=Le(),m=jx,p=zx(),f=(Z,P)=>new RegExp(Z,P);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 P,B,F,E,N,L,G,ee,se,ke,z,V,K,X,le,Te,Fe,tt,ut,Ye,$,re,Ae,yt,Dt;const Be=Z.strict,Br=(P=Z.code)===null||P===void 0?void 0:P.optimize,dt=Br===!0||Br===void 0?1:Br||0,sr=(F=(B=Z.code)===null||B===void 0?void 0:B.regExp)!==null&&F!==void 0?F:f,hn=(E=Z.uriResolver)!==null&&E!==void 0?E:p.default;return{strictSchema:(L=(N=Z.strictSchema)!==null&&N!==void 0?N:Be)!==null&&L!==void 0?L:!0,strictNumbers:(ee=(G=Z.strictNumbers)!==null&&G!==void 0?G:Be)!==null&&ee!==void 0?ee:!0,strictTypes:(ke=(se=Z.strictTypes)!==null&&se!==void 0?se:Be)!==null&&ke!==void 0?ke:"log",strictTuples:(V=(z=Z.strictTuples)!==null&&z!==void 0?z:Be)!==null&&V!==void 0?V:"log",strictRequired:(X=(K=Z.strictRequired)!==null&&K!==void 0?K:Be)!==null&&X!==void 0?X:!1,code:Z.code?{...Z.code,optimize:dt,regExp:sr}:{optimize:dt,regExp:sr},loopRequired:(le=Z.loopRequired)!==null&&le!==void 0?le:_,loopEnum:(Te=Z.loopEnum)!==null&&Te!==void 0?Te:_,meta:(Fe=Z.meta)!==null&&Fe!==void 0?Fe:!0,messages:(tt=Z.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(ut=Z.inlineRefs)!==null&&ut!==void 0?ut:!0,schemaId:(Ye=Z.schemaId)!==null&&Ye!==void 0?Ye:"$id",addUsedSchema:($=Z.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(re=Z.validateSchema)!==null&&re!==void 0?re:!0,validateFormats:(Ae=Z.validateFormats)!==null&&Ae!==void 0?Ae:!0,unicodeRegExp:(yt=Z.unicodeRegExp)!==null&&yt!==void 0?yt:!0,int32range:(Dt=Z.int32range)!==null&&Dt!==void 0?Dt:!0,uriResolver:hn}}class T{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,...h(P)};const{es5:B,lines:F}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:v,es5:B,lines:F}),this.logger=D(P.logger);const E=P.validateFormats;P.validateFormats=!1,this.RULES=(0,s.getRules)(),b.call(this,y,P,"NOT SUPPORTED"),b.call(this,w,P,"DEPRECATED","warn"),this._metaOpts=j.call(this),P.formats&&I.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&x.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),S.call(this),P.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:P,meta:B,schemaId:F}=this.opts;let E=m;F==="id"&&(E={...m},E.id=E.$id,delete E.$id),B&&P&&this.addMetaSchema(E,E[F],!1)}defaultMeta(){const{meta:P,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[B]||P:void 0}validate(P,B){let F;if(typeof P=="string"){if(F=this.getSchema(P),!F)throw new Error(`no schema with key or ref "${P}"`)}else F=this.compile(P);const E=F(B);return"$async"in F||(this.errors=F.errors),E}compile(P,B){const F=this._addSchema(P,B);return F.validate||this._compileSchemaEnv(F)}compileAsync(P,B){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:F}=this.opts;return E.call(this,P,B);async function E(ke,z){await N.call(this,ke.$schema);const V=this._addSchema(ke,z);return V.validate||L.call(this,V)}async function N(ke){ke&&!this.getSchema(ke)&&await E.call(this,{$ref:ke},!0)}async function L(ke){try{return this._compileSchemaEnv(ke)}catch(z){if(!(z instanceof o.default))throw z;return G.call(this,z),await ee.call(this,z.missingSchema),L.call(this,ke)}}function G({missingSchema:ke,missingRef:z}){if(this.refs[ke])throw new Error(`AnySchema ${ke} is loaded but ${z} cannot be resolved`)}async function ee(ke){const z=await se.call(this,ke);this.refs[ke]||await N.call(this,z.$schema),this.refs[ke]||this.addSchema(z,ke,B)}async function se(ke){const z=this._loading[ke];if(z)return z;try{return await(this._loading[ke]=F(ke))}finally{delete this._loading[ke]}}}addSchema(P,B,F,E=this.opts.validateSchema){if(Array.isArray(P)){for(const L of P)this.addSchema(L,void 0,F,E);return this}let N;if(typeof P=="object"){const{schemaId:L}=this.opts;if(N=P[L],N!==void 0&&typeof N!="string")throw new Error(`schema ${L} must be string`)}return B=(0,l.normalizeId)(B||N),this._checkUnique(B),this.schemas[B]=this._addSchema(P,F,B,E,!0),this}addMetaSchema(P,B,F=this.opts.validateSchema){return this.addSchema(P,B,!0,F),this}validateSchema(P,B){if(typeof P=="boolean")return!0;let F;if(F=P.$schema,F!==void 0&&typeof F!="string")throw new Error("$schema must be a string");if(F=F||this.opts.defaultMeta||this.defaultMeta(),!F)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(F,P);if(!E&&B){const N="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(N);else throw new Error(N)}return E}getSchema(P){let B;for(;typeof(B=k.call(this,P))=="string";)P=B;if(B===void 0){const{schemaId:F}=this.opts,E=new i.SchemaEnv({schema:{},schemaId:F});if(B=i.resolveSchema.call(this,E,P),!B)return;this.refs[P]=B}return B.validate||this._compileSchemaEnv(B)}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 B=k.call(this,P);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{const B=P;this._cache.delete(B);let F=P[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(P){for(const B of P)this.addKeyword(B);return this}addKeyword(P,B){let F;if(typeof P=="string")F=P,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=F);else if(typeof P=="object"&&B===void 0){if(B=P,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(O.call(this,F,B),!B)return(0,u.eachItem)(F,N=>H.call(this,N)),this;Y.call(this,B);const E={...B,type:(0,c.getJSONTypes)(B.type),schemaType:(0,c.getJSONTypes)(B.schemaType)};return(0,u.eachItem)(F,E.type.length===0?N=>H.call(this,N,E):N=>E.type.forEach(L=>H.call(this,N,E,L))),this}getKeyword(P){const B=this.RULES.all[P];return typeof B=="object"?B.definition:!!B}removeKeyword(P){const{RULES:B}=this;delete B.keywords[P],delete B.all[P];for(const F of B.rules){const E=F.rules.findIndex(N=>N.keyword===P);E>=0&&F.rules.splice(E,1)}return this}addFormat(P,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[P]=B,this}errorsText(P=this.errors,{separator:B=", ",dataVar:F="data"}={}){return!P||P.length===0?"No errors":P.map(E=>`${F}${E.instancePath} ${E.message}`).reduce((E,N)=>E+B+N)}$dataMetaSchema(P,B){const F=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(const E of B){const N=E.split("/").slice(1);let L=P;for(const G of N)L=L[G];for(const G in F){const ee=F[G];if(typeof ee!="object")continue;const{$data:se}=ee.definition,ke=L[G];se&&ke&&(L[G]=pe(ke))}}return P}_removeAllSchemas(P,B){for(const F in P){const E=P[F];(!B||B.test(F))&&(typeof E=="string"?delete P[F]:E&&!E.meta&&(this._cache.delete(E.schema),delete P[F]))}}_addSchema(P,B,F,E=this.opts.validateSchema,N=this.opts.addUsedSchema){let L;const{schemaId:G}=this.opts;if(typeof P=="object")L=P[G];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 ee=this._cache.get(P);if(ee!==void 0)return ee;F=(0,l.normalizeId)(L||F);const se=l.getSchemaRefs.call(this,P,F);return ee=new i.SchemaEnv({schema:P,schemaId:G,meta:B,baseId:F,localRefs:se}),this._cache.set(ee.schema,ee),N&&!F.startsWith("#")&&(F&&this._checkUnique(F),this.refs[F]=ee),E&&this.validateSchema(P,!0),ee}_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 B=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,P)}finally{this.opts=B}}}T.ValidationError=n.default,T.MissingRefError=o.default,e.default=T;function b(Z,P,B,F="error"){for(const E in Z){const N=E;N in P&&this.logger[F](`${B}: option ${E}. ${Z[N]}`)}}function k(Z){return Z=(0,l.normalizeId)(Z),this.schemas[Z]||this.refs[Z]}function S(){const Z=this.opts.schemas;if(Z)if(Array.isArray(Z))this.addSchema(Z);else for(const P in Z)this.addSchema(Z[P],P)}function I(){for(const Z in this.opts.formats){const P=this.opts.formats[Z];P&&this.addFormat(Z,P)}}function x(Z){if(Array.isArray(Z)){this.addVocabulary(Z);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const P in Z){const B=Z[P];B.keyword||(B.keyword=P),this.addKeyword(B)}}function j(){const Z={...this.opts};for(const P of g)delete Z[P];return Z}const M={log(){},warn(){},error(){}};function D(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 A=/^[a-z_$][a-z0-9_$:-]*$/i;function O(Z,P){const{RULES:B}=this;if((0,u.eachItem)(Z,F=>{if(B.keywords[F])throw new Error(`Keyword ${F} is already defined`);if(!A.test(F))throw new Error(`Keyword ${F} has invalid name`)}),!!P&&P.$data&&!("code"in P||"validate"in P))throw new Error('$data keyword must have "code" or "validate" function')}function H(Z,P,B){var F;const E=P?.post;if(B&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:N}=this;let L=E?N.post:N.rules.find(({type:ee})=>ee===B);if(L||(L={type:B,rules:[]},N.rules.push(L)),N.keywords[Z]=!0,!P)return;const G={keyword:Z,definition:{...P,type:(0,c.getJSONTypes)(P.type),schemaType:(0,c.getJSONTypes)(P.schemaType)}};P.before?Q.call(this,L,G,P.before):L.rules.push(G),N.all[Z]=G,(F=P.implements)===null||F===void 0||F.forEach(ee=>this.addKeyword(ee))}function Q(Z,P,B){const F=Z.rules.findIndex(E=>E.keyword===B);F>=0?Z.rules.splice(F,0,P):(Z.rules.push(P),this.logger.warn(`rule ${B} is not defined`))}function Y(Z){let{metaSchema:P}=Z;P!==void 0&&(Z.$data&&this.opts.$data&&(P=pe(P)),Z.validateSchema=this.compile(P,!0))}const W={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pe(Z){return{anyOf:[Z,W]}}})(au)),au}var Za={},Ba={},Ha={},_y;function Vx(){if(_y)return Ha;_y=1,Object.defineProperty(Ha,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Ha.default=e,Ha}var un={},vy;function Zx(){if(vy)return un;vy=1,Object.defineProperty(un,"__esModule",{value:!0}),un.callRef=un.getValidate=void 0;const e=Fa(),t=gr(),r=Re(),n=cn(),o=hu(),s=Le(),i={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:m,it:p}=c,{baseId:f,schemaEnv:g,validateName:v,opts:y,self:w}=p,{root:_}=g;if((m==="#"||m==="#/")&&f===_.baseId)return T();const h=o.resolveRef.call(w,_,f,m);if(h===void 0)throw new e.default(p.opts.uriResolver,f,m);if(h instanceof o.SchemaEnv)return b(h);return k(h);function T(){if(g===_)return l(c,v,g,g.$async);const S=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${S}.validate`,_,_.$async)}function b(S){const I=a(c,S);l(c,I,S,S.$async)}function k(S){const I=u.scopeValue("schema",y.code.source===!0?{ref:S,code:(0,r.stringify)(S)}:{ref:S}),x=u.name("valid"),j=c.subschema({schema:S,dataTypes:[],schemaPath:r.nil,topSchemaRef:I,errSchemaPath:m},x);c.mergeEvaluated(j),c.ok(x)}}};function a(c,u){const{gen:m}=c;return u.validate?m.scopeValue("validate",{ref:u.validate}):(0,r._)`${m.scopeValue("wrapper",{ref:u})}.validate`}un.getValidate=a;function l(c,u,m,p){const{gen:f,it:g}=c,{allErrors:v,schemaEnv:y,opts:w}=g,_=w.passContext?n.default.this:r.nil;p?h():T();function h(){if(!y.$async)throw new Error("async schema referenced by sync schema");const S=f.let("valid");f.try(()=>{f.code((0,r._)`await ${(0,t.callValidateCode)(c,u,_)}`),k(u),v||f.assign(S,!0)},I=>{f.if((0,r._)`!(${I} instanceof ${g.ValidationError})`,()=>f.throw(I)),b(I),v||f.assign(S,!1)}),c.ok(S)}function T(){c.result((0,t.callValidateCode)(c,u,_),()=>k(u),()=>b(u))}function b(S){const I=(0,r._)`${S}.errors`;f.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${I} : ${n.default.vErrors}.concat(${I})`),f.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function k(S){var I;if(!g.opts.unevaluated)return;const x=(I=m?.validate)===null||I===void 0?void 0:I.evaluated;if(g.props!==!0)if(x&&!x.dynamicProps)x.props!==void 0&&(g.props=s.mergeEvaluated.props(f,x.props,g.props));else{const j=f.var("props",(0,r._)`${S}.evaluated.props`);g.props=s.mergeEvaluated.props(f,j,g.props,r.Name)}if(g.items!==!0)if(x&&!x.dynamicItems)x.items!==void 0&&(g.items=s.mergeEvaluated.items(f,x.items,g.items));else{const j=f.var("items",(0,r._)`${S}.evaluated.items`);g.items=s.mergeEvaluated.items(f,j,g.items,r.Name)}}}return un.callRef=l,un.default=i,un}var wy;function Bx(){if(wy)return Ba;wy=1,Object.defineProperty(Ba,"__esModule",{value:!0});const e=Vx(),t=Zx(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Ba.default=r,Ba}var Ja={},Ga={},by;function Hx(){if(by)return Ga;by=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=Re(),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 Ga.default=o,Ga}var Wa={},ky;function Jx(){if(ky)return Wa;ky=1,Object.defineProperty(Wa,"__esModule",{value:!0});const e=Re(),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 Wa.default=r,Wa}var Ka={},Ya={},Cy;function Gx(){if(Cy)return Ya;Cy=1,Object.defineProperty(Ya,"__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 Ya.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Ya}var Ty;function Wx(){if(Ty)return Ka;Ty=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Re(),t=Le(),r=Gx(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:i}){const a=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${a} than ${i} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:i,data:a,schemaCode:l,it:c}=s,u=i==="maxLength"?e.operators.GT:e.operators.LT,m=c.opts.unicode===!1?(0,e._)`${a}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${a})`;s.fail$data((0,e._)`${m} ${u} ${l}`)}};return Ka.default=o,Ka}var Qa={},Sy;function Kx(){if(Sy)return Qa;Sy=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=gr(),t=Le(),r=Re(),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:i,data:a,$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)(i,f),v=i.let("valid");i.try(()=>i.assign(v,(0,r._)`${g}(${u}, ${p}).test(${a})`),()=>i.assign(v,!1)),s.fail$data((0,r._)`!${v}`)}else{const f=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${f}.test(${a})`)}}};return Qa.default=o,Qa}var Xa={},Iy;function Yx(){if(Iy)return Xa;Iy=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=Re(),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 Xa.default=r,Xa}var ei={},xy;function Qx(){if(xy)return ei;xy=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=gr(),t=Re(),r=Le(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:i,schema:a,schemaCode:l,data:c,$data:u,it:m}=s,{opts:p}=m;if(!u&&a.length===0)return;const f=a.length>=p.loopRequired;if(m.allErrors?g():v(),p.strictRequired){const _=s.parentSchema.properties,{definedProperties:h}=s.it;for(const T of a)if(_?.[T]===void 0&&!h.has(T)){const b=m.schemaEnv.baseId+m.errSchemaPath,k=`required property "${T}" is not defined at "${b}" (strictRequired)`;(0,r.checkStrictMode)(m,k,m.opts.strictRequired)}}function g(){if(f||u)s.block$data(t.nil,y);else for(const _ of a)(0,e.checkReportMissingProp)(s,_)}function v(){const _=i.let("missing");if(f||u){const h=i.let("valid",!0);s.block$data(h,()=>w(_,h)),s.ok(h)}else i.if((0,e.checkMissingProp)(s,a,_)),(0,e.reportMissingProp)(s,_),i.else()}function y(){i.forOf("prop",l,_=>{s.setParams({missingProperty:_}),i.if((0,e.noPropertyInData)(i,c,_,p.ownProperties),()=>s.error())})}function w(_,h){s.setParams({missingProperty:_}),i.forOf(_,l,()=>{i.assign(h,(0,e.propertyInData)(i,c,_,p.ownProperties)),i.if((0,t.not)(h),()=>{s.error(),i.break()})},t.nil)}}};return ei.default=o,ei}var ti={},Ey;function Xx(){if(Ey)return ti;Ey=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Re(),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 ti.default=r,ti}var ri={},ni={},$y;function yu(){if($y)return ni;$y=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=sy();return e.code='require("ajv/dist/runtime/equal").default',ni.default=e,ni}var Ry;function e7(){if(Ry)return ri;Ry=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=La(),t=Re(),r=Le(),n=yu(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i,j:a}})=>(0,t.str)`must NOT have duplicate items (items ## ${a} and ${i} are identical)`,params:({params:{i,j:a}})=>(0,t._)`{i: ${i}, j: ${a}}`},code(i){const{gen:a,data:l,$data:c,schema:u,parentSchema:m,schemaCode:p,it:f}=i;if(!c&&!u)return;const g=a.let("valid"),v=m.items?(0,e.getSchemaTypes)(m.items):[];i.block$data(g,y,(0,t._)`${p} === false`),i.ok(g);function y(){const T=a.let("i",(0,t._)`${l}.length`),b=a.let("j");i.setParams({i:T,j:b}),a.assign(g,!0),a.if((0,t._)`${T} > 1`,()=>(w()?_:h)(T,b))}function w(){return v.length>0&&!v.some(T=>T==="object"||T==="array")}function _(T,b){const k=a.name("item"),S=(0,e.checkDataTypes)(v,k,f.opts.strictNumbers,e.DataType.Wrong),I=a.const("indices",(0,t._)`{}`);a.for((0,t._)`;${T}--;`,()=>{a.let(k,(0,t._)`${l}[${T}]`),a.if(S,(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(b,(0,t._)`${I}[${k}]`),i.error(),a.assign(g,!1).break()}).code((0,t._)`${I}[${k}] = ${T}`)})}function h(T,b){const k=(0,r.useFunc)(a,n.default),S=a.name("outer");a.label(S).for((0,t._)`;${T}--;`,()=>a.for((0,t._)`${b} = ${T}; ${b}--;`,()=>a.if((0,t._)`${k}(${l}[${T}], ${l}[${b}])`,()=>{i.error(),a.assign(g,!1).break(S)})))}}};return ri.default=s,ri}var oi={},Py;function t7(){if(Py)return oi;Py=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=Re(),t=Le(),r=yu(),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 oi.default=o,oi}var si={},Ny;function r7(){if(Ny)return si;Ny=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Re(),t=Le(),r=yu(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:i,data:a,$data:l,schema:c,schemaCode:u,it:m}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=m.opts.loopEnum;let f;const g=()=>f??(f=(0,t.useFunc)(i,r.default));let v;if(p||l)v=i.let("valid"),s.block$data(v,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=i.const("vSchema",u);v=(0,e.or)(...c.map((h,T)=>w(_,T)))}s.pass(v);function y(){i.assign(v,!1),i.forOf("v",u,_=>i.if((0,e._)`${g()}(${a}, ${_})`,()=>i.assign(v,!0).break()))}function w(_,h){const T=c[h];return typeof T=="object"&&T!==null?(0,e._)`${g()}(${a}, ${_}[${h}])`:(0,e._)`${a} === ${T}`}}};return si.default=o,si}var My;function n7(){if(My)return Ja;My=1,Object.defineProperty(Ja,"__esModule",{value:!0});const e=Hx(),t=Jx(),r=Wx(),n=Kx(),o=Yx(),s=Qx(),i=Xx(),a=e7(),l=t7(),c=r7(),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 Ja.default=u,Ja}var ai={},go={},Oy;function Ay(){if(Oy)return go;Oy=1,Object.defineProperty(go,"__esModule",{value:!0}),go.validateAdditionalItems=void 0;const e=Re(),t=Le(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:i,it:a}=s,{items:l}=i;if(!Array.isArray(l)){(0,t.checkStrictMode)(a,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,i){const{gen:a,schema:l,data:c,keyword:u,it:m}=s;m.items=!0;const p=a.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:i.length}),s.pass((0,e._)`${p} <= ${i.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(m,l)){const g=a.var("valid",(0,e._)`${p} <= ${i.length}`);a.if((0,e.not)(g),()=>f(g)),s.ok(g)}function f(g){a.forRange("i",i.length,p,v=>{s.subschema({keyword:u,dataProp:v,dataPropType:t.Type.Num},g),m.allErrors||a.if((0,e.not)(g),()=>a.break())})}}return go.validateAdditionalItems=o,go.default=n,go}var ii={},yo={},qy;function Ly(){if(qy)return yo;qy=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.validateTuple=void 0;const e=Re(),t=Le(),r=gr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:i,it:a}=s;if(Array.isArray(i))return o(s,"additionalItems",i);a.items=!0,!(0,t.alwaysValidSchema)(a,i)&&s.ok((0,r.validateArray)(s))}};function o(s,i,a=s.schema){const{gen:l,parentSchema:c,data:u,keyword:m,it:p}=s;v(c),p.opts.unevaluated&&a.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,a.length,p.items));const f=l.name("valid"),g=l.const("len",(0,e._)`${u}.length`);a.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=a.length,T=h===y.minItems&&(h===y.maxItems||y[i]===!1);if(w.strictTuples&&!T){const b=`"${m}" is ${h}-tuple, but minItems or maxItems/${i} are not specified or different at path "${_}"`;(0,t.checkStrictMode)(p,b,w.strictTuples)}}}return yo.validateTuple=o,yo.default=n,yo}var jy;function o7(){if(jy)return ii;jy=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=Ly(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return ii.default=t,ii}var li={},Uy;function s7(){if(Uy)return li;Uy=1,Object.defineProperty(li,"__esModule",{value:!0});const e=Re(),t=Le(),r=gr(),n=Ay(),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 li.default=s,li}var ci={},Dy;function a7(){if(Dy)return ci;Dy=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Re(),t=Le(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:i,parentSchema:a,data:l,it:c}=o;let u,m;const{minContains:p,maxContains:f}=a;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,i)){let h=(0,e._)`${g} >= ${u}`;m!==void 0&&(h=(0,e._)`${h} && ${g} <= ${m}`),o.pass(h);return}c.items=!0;const v=s.name("valid");m===void 0&&u===1?w(v,()=>s.if(v,()=>s.break())):u===0?(s.let(v,!0),m!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(v,!1),y()),o.result(v,()=>o.reset());function y(){const h=s.name("_valid"),T=s.let("count",0);w(h,()=>s.if(h,()=>_(T)))}function w(h,T){s.forRange("i",0,g,b=>{o.subschema({keyword:"contains",dataProp:b,dataPropType:t.Type.Num,compositeRule:!0},h),T()})}function _(h){s.code((0,e._)`${h}++`),m===void 0?s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0).break()):(s.if((0,e._)`${h} > ${m}`,()=>s.assign(v,!1).break()),u===1?s.assign(v,!0):s.if((0,e._)`${h} >= ${u}`,()=>s.assign(v,!0)))}}};return ci.default=n,ci}var _u={},zy;function i7(){return zy||(zy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Re(),r=Le(),n=gr();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
86
|
missingProperty: ${m},
|
|
87
87
|
depsCount: ${c},
|
|
88
|
-
deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);i(l,c),a(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 i(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=i;function a(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=a,e.default=o})(lu)),lu}var ai={},jy;function r7(){if(jy)return ai;jy=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=Re(),t=Le(),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 ai.default=n,ai}var ii={},Uy;function Dy(){if(Uy)return ii;Uy=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=mr(),t=Re(),r=ln(),n=Le(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:i})=>(0,t._)`{additionalProperty: ${i.additionalProperty}}`},code(i){const{gen:a,schema:l,parentSchema:c,data:u,errsCount:m,it:p}=i;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(),i.ok((0,t._)`${m} === ${r.default.errors}`);function w(){a.forIn("key",u,k=>{!v.length&&!y.length?T(k):a.if(_(k),()=>T(k))})}function _(k){let S;if(v.length>8){const I=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(a,I,k)}else v.length?S=(0,t.or)(...v.map(I=>(0,t._)`${k} === ${I}`)):S=t.nil;return y.length&&(S=(0,t.or)(S,...y.map(I=>(0,t._)`${(0,e.usePattern)(i,I)}.test(${k})`))),(0,t.not)(S)}function h(k){a.code((0,t._)`delete ${u}[${k}]`)}function T(k){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){h(k);return}if(l===!1){i.setParams({additionalProperty:k}),i.error(),f||a.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=a.name("valid");g.removeAdditional==="failing"?(b(k,S,!1),a.if((0,t.not)(S),()=>{i.reset(),h(k)})):(b(k,S),f||a.if((0,t.not)(S),()=>a.break()))}}function b(k,S,I){const x={keyword:"additionalProperties",dataProp:k,dataPropType:n.Type.Str};I===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(x,S)}}};return ii.default=s,ii}var li={},zy;function n7(){if(zy)return li;zy=1,Object.defineProperty(li,"__esModule",{value:!0});const e=Aa(),t=mr(),r=Le(),n=Dy(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const m=(0,t.allSchemaProperties)(a);for(const y of m)u.definedProperties.add(y);u.opts.unevaluated&&m.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(i,(0,r.toHash)(m),u.props));const p=m.filter(y=>!(0,r.alwaysValidSchema)(u,a[y]));if(p.length===0)return;const f=i.name("valid");for(const y of p)g(y)?v(y):(i.if((0,t.propertyInData)(i,c,y,u.opts.ownProperties)),v(y),u.allErrors||i.else().var(f,!0),i.endIf()),s.it.definedProperties.add(y),s.ok(f);function g(y){return u.opts.useDefaults&&!u.compositeRule&&a[y].default!==void 0}function v(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return li.default=o,li}var ci={},Fy;function o7(){if(Fy)return ci;Fy=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=mr(),t=Re(),r=Le(),n=Le(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,data:l,parentSchema:c,it:u}=s,{opts:m}=u,p=(0,e.allSchemaProperties)(a),f=p.filter(T=>(0,r.alwaysValidSchema)(u,a[T]));if(p.length===0||f.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const g=m.strictSchema&&!m.allowMatchingProperties&&c.properties,v=i.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(i,u.props));const{props:y}=u;w();function w(){for(const T of p)g&&_(T),u.allErrors?h(T):(i.var(v,!0),h(T),i.if(v))}function _(T){for(const b in g)new RegExp(T).test(b)&&(0,r.checkStrictMode)(u,`property ${b} matches pattern ${T} (use allowMatchingProperties)`)}function h(T){i.forIn("key",l,b=>{i.if((0,t._)`${(0,e.usePattern)(s,T)}.test(${b})`,()=>{const k=f.includes(T);k||s.subschema({keyword:"patternProperties",schemaProp:T,dataProp:b,dataPropType:n.Type.Str},v),u.opts.unevaluated&&y!==!0?i.assign((0,t._)`${y}[${b}]`,!0):!k&&!u.allErrors&&i.if((0,t.not)(v),()=>i.break())})})}}};return ci.default=o,ci}var ui={},Vy;function s7(){if(Vy)return ui;Vy=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=Le(),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 ui.default=t,ui}var di={},Zy;function a7(){if(Zy)return di;Zy=1,Object.defineProperty(di,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:mr().validateUnion,error:{message:"must match a schema in anyOf"}};return di.default=t,di}var pi={},By;function i7(){if(By)return pi;By=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Re(),t=Le(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:i,parentSchema:a,it:l}=o;if(!Array.isArray(i))throw new Error("ajv implementation error");if(l.opts.discriminator&&a.discriminator)return;const c=i,u=s.let("valid",!1),m=s.let("passing",null),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 pi.default=n,pi}var fi={},Hy;function l7(){if(Hy)return fi;Hy=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=Le(),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 fi.default=t,fi}var hi={},Jy;function c7(){if(Jy)return hi;Jy=1,Object.defineProperty(hi,"__esModule",{value:!0});const e=Re(),t=Le(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:i,parentSchema:a,it:l}=s;a.then===void 0&&a.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const m=i.let("valid",!0),p=i.name("_valid");if(f(),s.reset(),c&&u){const v=i.let("ifClause");s.setParams({ifClause:v}),i.if(p,g("then",v),g("else",v))}else c?i.if(p,g("then")):i.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);i.assign(m,p),s.mergeValidEvaluated(w,m),y?i.assign(y,(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 hi.default=n,hi}var mi={},Gy;function u7(){if(Gy)return mi;Gy=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Le(),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 mi.default=t,mi}var Wy;function d7(){if(Wy)return ri;Wy=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=Py(),t=Qx(),r=My(),n=Xx(),o=e7(),s=t7(),i=r7(),a=Dy(),l=n7(),c=o7(),u=s7(),m=a7(),p=i7(),f=l7(),g=c7(),v=u7();function y(w=!1){const _=[u.default,m.default,p.default,f.default,g.default,v.default,i.default,a.default,s.default,l.default,c.default];return w?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return ri.default=y,ri}var gi={},yi={},Ky;function p7(){if(Ky)return yi;Ky=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=Re(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:i,$data:a,schema:l,schemaCode:c,it:u}=n,{opts:m,errSchemaPath:p,schemaEnv:f,self:g}=u;if(!m.validateFormats)return;a?v():y();function v(){const w=s.scopeValue("formats",{ref:g.formats,code:m.code.formats}),_=s.const("fDef",(0,e._)`${w}[${c}]`),h=s.let("fType"),T=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(h,(0,e._)`${_}.type || "string"`).assign(T,(0,e._)`${_}.validate`),()=>s.assign(h,(0,e._)`"string"`).assign(T,_)),n.fail$data((0,e.or)(b(),k()));function b(){return m.strictSchema===!1?e.nil:(0,e._)`${c} && !${T}`}function k(){const S=f.$async?(0,e._)`(${_}.async ? await ${T}(${i}) : ${T}(${i}))`:(0,e._)`${T}(${i})`,I=(0,e._)`(typeof ${T} == "function" ? ${S} : ${T}.test(${i}))`;return(0,e._)`${T} && ${T} !== true && ${h} === ${o} && !${I}`}}function y(){const w=g.formats[l];if(!w){b();return}if(w===!0)return;const[_,h,T]=k(w);_===o&&n.pass(S());function b(){if(m.strictSchema===!1){g.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function k(I){const x=I instanceof RegExp?(0,e.regexpCode)(I):m.code.formats?(0,e._)`${m.code.formats}${(0,e.getProperty)(l)}`:void 0,j=s.scopeValue("formats",{key:l,ref:I,code:x});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${j}.validate`]:["string",I,j]}function S(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!f.$async)throw new Error("async format in sync schema");return(0,e._)`await ${T}(${i})`}return typeof h=="function"?(0,e._)`${T}(${i})`:(0,e._)`${T}.test(${i})`}}}};return yi.default=r,yi}var Yy;function f7(){if(Yy)return gi;Yy=1,Object.defineProperty(gi,"__esModule",{value:!0});const t=[p7().default];return gi.default=t,gi}var Un={},Qy;function h7(){return Qy||(Qy=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.contentVocabulary=Un.metadataVocabulary=void 0,Un.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Un.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Un}var Xy;function m7(){if(Xy)return Da;Xy=1,Object.defineProperty(Da,"__esModule",{value:!0});const e=Ux(),t=Yx(),r=d7(),n=f7(),o=h7(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Da.default=s,Da}var _i={},us={},e_;function g7(){if(e_)return us;e_=1,Object.defineProperty(us,"__esModule",{value:!0}),us.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(us.DiscrError=e={})),us}var t_;function y7(){if(t_)return _i;t_=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=Re(),t=g7(),r=ou(),n=ja(),o=Le(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:a,tagName:l}})=>a===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:a,tag:l,tagName:c}})=>(0,e._)`{error: ${a}, tag: ${c}, tagValue: ${l}}`},code(a){const{gen:l,data:c,schema:u,parentSchema:m,it:p}=a,{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(),()=>a.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:g})),a.ok(v);function w(){const T=h();l.if(!1);for(const b in T)l.elseIf((0,e._)`${y} === ${b}`),l.assign(v,_(T[b]));l.else(),a.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:g}),l.endIf()}function _(T){const b=l.name("valid"),k=a.subschema({keyword:"oneOf",schemaProp:T},b);return a.mergeEvaluated(k,e.Name),b}function h(){var T;const b={},k=I(m);let S=!0;for(let M=0;M<f.length;M++){let D=f[M];if(D?.$ref&&!(0,o.schemaHasRulesButRef)(D,p.self.RULES)){const O=D.$ref;if(D=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,O),D instanceof r.SchemaEnv&&(D=D.schema),D===void 0)throw new n.default(p.opts.uriResolver,p.baseId,O)}const A=(T=D?.properties)===null||T===void 0?void 0:T[g];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${g}"`);S=S&&(k||I(D)),x(A,M)}if(!S)throw new Error(`discriminator: "${g}" must be required`);return b;function I({required:M}){return Array.isArray(M)&&M.includes(g)}function x(M,D){if(M.const)j(M.const,D);else if(M.enum)for(const A of M.enum)j(A,D);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function j(M,D){if(typeof M!="string"||M in b)throw new Error(`discriminator: "${g}" values must be unique strings`);b[M]=D}}}};return _i.default=i,_i}const _7={$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 r_;function n_(){return r_||(r_=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=qx(),n=m7(),o=y7(),s=_7,i=["/properties"],a="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,i):s;this.addMetaSchema(g,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=Aa();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Re();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=nu();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return m.default}});var p=ja();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})($a,$a.exports)),$a.exports}var v7=n_();const w7=wl(v7);var vi={exports:{}},cu={},o_;function b7(){return o_||(o_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(M,D){return{validate:M,compare:D}}e.fullFormats={date:t(s,i),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:j,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:k},int64:{type:"number",validate:S},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,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 D=n.exec(M);if(!D)return!1;const A=+D[1],O=+D[2],H=+D[3];return O>=1&&O<=12&&H>=1&&H<=(O===2&&r(A)?29:o[O])}function i(M,D){if(M&&D)return M>D?1:M<D?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(M){return function(A){const O=a.exec(A);if(!O)return!1;const H=+O[1],Q=+O[2],Y=+O[3],W=O[4],pe=O[5]==="-"?-1:1,Z=+(O[6]||0),P=+(O[7]||0);if(Z>23||P>59||M&&!W)return!1;if(H<=23&&Q<=59&&Y<60)return!0;const B=Q-P*pe,F=H-Z*pe-(B<0?1:0);return(F===23||F===-1)&&(B===59||B===-1)&&Y<61}}function c(M,D){if(!(M&&D))return;const A=new Date("2020-01-01T"+M).valueOf(),O=new Date("2020-01-01T"+D).valueOf();if(A&&O)return A-O}function u(M,D){if(!(M&&D))return;const A=a.exec(M),O=a.exec(D);if(A&&O)return M=A[1]+A[2]+A[3],D=O[1]+O[2]+O[3],M>D?1:M<D?-1:0}const m=/t|\s/i;function p(M){const D=l(M);return function(O){const H=O.split(m);return H.length===2&&s(H[0])&&D(H[1])}}function f(M,D){if(!(M&&D))return;const A=new Date(M).valueOf(),O=new Date(D).valueOf();if(A&&O)return A-O}function g(M,D){if(!(M&&D))return;const[A,O]=M.split(m),[H,Q]=D.split(m),Y=i(A,H);if(Y!==void 0)return Y||c(O,Q)}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 T=-2147483648,b=2**31-1;function k(M){return Number.isInteger(M)&&M<=b&&M>=T}function S(M){return Number.isInteger(M)}function I(){return!0}const x=/[^\\]\\Z/;function j(M){if(x.test(M))return!1;try{return new RegExp(M),!0}catch{return!1}}})(cu)),cu}var uu={},s_;function k7(){return s_||(s_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=n_(),r=Re(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:a,schemaCode:l})=>(0,r.str)`should be ${o[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>(0,r._)`{comparison: ${o[a].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(a){const{gen:l,data:c,schemaCode:u,keyword:m,it:p}=a,{opts:f,self:g}=p;if(!f.validateFormats)return;const v=new t.KeywordCxt(p,g.RULES.all.format.definition,"format");v.$data?y():w();function y(){const h=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),T=l.const("fmt",(0,r._)`${h}[${v.schemaCode}]`);a.fail$data((0,r.or)((0,r._)`typeof ${T} != "object"`,(0,r._)`${T} instanceof RegExp`,(0,r._)`typeof ${T}.compare != "function"`,_(T)))}function w(){const h=v.schema,T=g.formats[h];if(!T||T===!0)return;if(typeof T!="object"||T instanceof RegExp||typeof T.compare!="function")throw new Error(`"${m}": format "${h}" does not define "compare" function`);const b=l.scopeValue("formats",{key:h,ref:T,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(h)}`:void 0});a.fail$data(_(b))}function _(h){return(0,r._)`${h}.compare(${c}, ${u}) ${o[m].fail} 0`}},dependencies:["format"]};const i=a=>(a.addKeyword(e.formatLimitDefinition),a);e.default=i})(uu)),uu}var a_;function C7(){return a_||(a_=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=b7(),n=k7(),o=Re(),s=new o.Name("fullFormats"),i=new o.Name("fastFormats"),a=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[m,p]=u.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,s],f=u.formats||r.formatNames;return l(c,f,m,p),u.keywords&&(0,n.default)(c),c};a.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=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a})(vi,vi.exports)),vi.exports}var T7=C7();const S7=wl(T7);function I7(){const e=new w7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return S7(e),e}class x7{constructor(t){this._ajv=t??I7()}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 E7{constructor(t){this._client=t}async*callToolStream(t,r=os,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 be(xe.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 be(xe.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof be){yield{type:"error",error:u};return}yield{type:"error",error:new be(xe.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 $7(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 R7(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 wi(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&&wi(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&wi(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&wi(r,t)}}function P7(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 bi extends Sx{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 x7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",wc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",vc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",hc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new E7(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ix(this._capabilities,t)}setRequestHandler(t,r){const o=Mg(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ea(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=an(Cc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new be(xe.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:m}=u.data;m.mode=m.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=P7(this._capabilities.elicitation);if(m.mode==="form"&&!p)throw new be(xe.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!f)throw new be(xe.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(m.task){const _=an(rs,g);if(!_.success){const h=_.error instanceof Error?_.error.message:String(_.error);throw new be(xe.InvalidParams,`Invalid task creation result: ${h}`)}return _.data}const v=an(Tc,g);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new be(xe.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{wi(w,y.content)}catch{}return y};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){const a=async(l,c)=>{const u=an(bc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new be(xe.InvalidParams,`Invalid sampling request: ${y}`)}const{params:m}=u.data,p=await Promise.resolve(r(l,c));if(m.task){const y=an(rs,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new be(xe.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const g=m.tools||m.toolChoice?s2:kc,v=an(g,p);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new be(xe.InvalidParams,`Invalid sampling result: ${y}`)}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:pa,capabilities:this._capabilities,clientInfo:this._clientInfo}},Vm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!V5.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){$7(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&R7(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Mn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},a2,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Mn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},e2,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Xm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Wm,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Km,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Ym,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Mn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Mn,r)}async callTool(t,r=os,n){if(this.isToolTaskRequired(t.name))throw new be(xe.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 be(xe.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 be(xe.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof be?i:new be(xe.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},r2,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=qT.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:a}=s.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{const m=await o();l(null,m)}catch(m){const p=m instanceof Error?m:new Error(String(m));l(p,null)}},u=()=>{if(a){const m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);const p=setTimeout(c,a);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class i_ 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(l_(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(l_(this),r)}}function N7(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function du(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(du).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${du(e.cause)}`:e.message:`${e}`}function l_(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var c_=e=>{throw TypeError(e)},pu=(e,t,r)=>t.has(e)||c_("Cannot "+r),Oe=(e,t,r)=>(pu(e,t,"read from private field"),r?r.call(e):t.get(e)),wt=(e,t,r)=>t.has(e)?c_("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),et=(e,t,r,n)=>(pu(e,t,"write to private field"),t.set(e,r),r),Fr=(e,t,r)=>(pu(e,t,"access private method"),r),Ht,Dn,fo,ki,Ci,ds,ho,ps,un,mo,go,yo,fs,gr,fu,hu,mu,u_,gu,yu,hs,_u,vu;class Ti extends EventTarget{constructor(t,r){var n,o;super(),wt(this,gr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,wt(this,Ht),wt(this,Dn),wt(this,fo),wt(this,ki),wt(this,Ci),wt(this,ds),wt(this,ho),wt(this,ps,null),wt(this,un),wt(this,mo),wt(this,go,null),wt(this,yo,null),wt(this,fs,null),wt(this,hu,async s=>{var i;Oe(this,mo).reset();const{body:a,redirected:l,status:c,headers:u}=s;if(c===204){Fr(this,gr,hs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?et(this,fo,new URL(s.url)):et(this,fo,void 0),c!==200){Fr(this,gr,hs).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Fr(this,gr,hs).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Oe(this,Ht)===this.CLOSED)return;et(this,Ht,this.OPEN);const m=new Event("open");if((i=Oe(this,fs))==null||i.call(this,m),this.dispatchEvent(m),typeof a!="object"||!a||!("getReader"in a)){Fr(this,gr,hs).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,f=a.getReader();let g=!0;do{const{done:v,value:y}=await f.read();y&&Oe(this,mo).feed(p.decode(y,{stream:!v})),v&&(g=!1,Oe(this,mo).reset(),Fr(this,gr,_u).call(this))}while(g)}),wt(this,mu,s=>{et(this,un,void 0),!(s.name==="AbortError"||s.type==="aborted")&&Fr(this,gr,_u).call(this,du(s))}),wt(this,gu,s=>{typeof s.id=="string"&&et(this,ps,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:Oe(this,fo)?Oe(this,fo).origin:Oe(this,Dn).origin,lastEventId:s.id||""});Oe(this,yo)&&(!s.event||s.event==="message")&&Oe(this,yo).call(this,i),this.dispatchEvent(i)}),wt(this,yu,s=>{et(this,ds,s)}),wt(this,vu,()=>{et(this,ho,void 0),Oe(this,Ht)===this.CONNECTING&&Fr(this,gr,fu).call(this)});try{if(t instanceof URL)et(this,Dn,t);else if(typeof t=="string")et(this,Dn,new URL(t,M7()));else throw new Error("Invalid URL")}catch{throw N7("An invalid or illegal string was specified")}et(this,mo,mf({onEvent:Oe(this,gu),onRetry:Oe(this,yu)})),et(this,Ht,this.CONNECTING),et(this,ds,3e3),et(this,Ci,(n=r?.fetch)!=null?n:globalThis.fetch),et(this,ki,(o=r?.withCredentials)!=null?o:!1),Fr(this,gr,fu).call(this)}get readyState(){return Oe(this,Ht)}get url(){return Oe(this,Dn).href}get withCredentials(){return Oe(this,ki)}get onerror(){return Oe(this,go)}set onerror(t){et(this,go,t)}get onmessage(){return Oe(this,yo)}set onmessage(t){et(this,yo,t)}get onopen(){return Oe(this,fs)}set onopen(t){et(this,fs,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(){Oe(this,ho)&&clearTimeout(Oe(this,ho)),Oe(this,Ht)!==this.CLOSED&&(Oe(this,un)&&Oe(this,un).abort(),et(this,Ht,this.CLOSED),et(this,un,void 0))}}Ht=new WeakMap,Dn=new WeakMap,fo=new WeakMap,ki=new WeakMap,Ci=new WeakMap,ds=new WeakMap,ho=new WeakMap,ps=new WeakMap,un=new WeakMap,mo=new WeakMap,go=new WeakMap,yo=new WeakMap,fs=new WeakMap,gr=new WeakSet,fu=function(){et(this,Ht,this.CONNECTING),et(this,un,new AbortController),Oe(this,Ci)(Oe(this,Dn),Fr(this,gr,u_).call(this)).then(Oe(this,hu)).catch(Oe(this,mu))},hu=new WeakMap,mu=new WeakMap,u_=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Oe(this,ps)?{"Last-Event-ID":Oe(this,ps)}:void 0},cache:"no-store",signal:(e=Oe(this,un))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},gu=new WeakMap,yu=new WeakMap,hs=function(e,t){var r;Oe(this,Ht)!==this.CLOSED&&et(this,Ht,this.CLOSED);const n=new i_("error",{code:t,message:e});(r=Oe(this,go))==null||r.call(this,n),this.dispatchEvent(n)},_u=function(e,t){var r;if(Oe(this,Ht)===this.CLOSED)return;et(this,Ht,this.CONNECTING);const n=new i_("error",{code:t,message:e});(r=Oe(this,go))==null||r.call(this,n),this.dispatchEvent(n),et(this,ho,setTimeout(Oe(this,vu),Oe(this,ds)))},vu=new WeakMap,Ti.CONNECTING=0,Ti.OPEN=1,Ti.CLOSED=2;function M7(){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 O7 extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class wu{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=Lm(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new or("No auth provider");let t;try{t=await On(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 or;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=da(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 Ti(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}=ba(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 O7(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=Nn.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 or("No auth provider");if(await On(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or("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}=ba(o);if(this._resourceMetadataUrl=i,this._scope=a,await On(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new or;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 A7="mcp";class d_{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,A7),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=Nn.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 _o=yr;(function(e,t){const r=yr,n=yr,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())}})(Si,-118057+3521*-35+-2099*-233);const q7=()=>{const e=yr,t=yr,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}},L7=(e,t,r)=>{const n=yr,o=yr,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 p_{constructor(t){this._port=t}async[_o(401)](){const t=_o,r=_o;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const i=t;try{const a=Nn.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=yr,l=yr;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=_o,o=_o;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class j7 extends p_{constructor(t,r=q7()){const n=_o,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)](L7,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function Si(){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 Si=function(){return e},Si()}function yr(e,t){const r=Si();return yr=function(n,o){return n=n-(17227+1*-16844),r[n]},yr(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())}})(Ii,-411935*1+228107+208149*2);const U7=async(e,t,r)=>{var n;const o=He,s=He,i={};i.VRyiJ="tools/list",i.VkPYu="tools/call",i[o(475)]=o(411),i.SoCaE="resources/templates/list",i[s(484)]="resources/read",i[o(461)]="prompts/get",i.srIIC=s(477),i[s(436)]=s(478),i[s(442)]=o(437),i.dEmVs=o(465);const a=i,{id:l,method:c,params:u}=r;let m={};switch(c){case a.VRyiJ:m=await t.listTools(u);break;case a.VkPYu:m=await t.callTool(u);break;case a.fgMSD:m=await t.listResources(u);break;case a[s(466)]:m=await t.listResourceTemplates(u);break;case a.sthgI:m=await t[o(455)](u);break;case s(486):m=await t.subscribeResource(u);break;case o(410):m=await t.unsubscribeResource(u);break;case a[s(461)]:m=await t[s(414)](u);break;case a[o(412)]:m=await t[o(491)](u);break;case a[o(436)]:m=await t[o(478)]();break;case a.kkNqg:m=await t.complete(u);break;case o(464):m=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=m,p.jsonrpc=a[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},D7=async(e,t,r)=>{var n;const o=He,s=He,i={};i[o(487)]=s(462),i.ypHTC="ping",i.fPExS=o(465);const a=i,{id:l,method:c,params:u}=r;let m={};switch(c){case"roots/list":const f={};f.method=c,f[s(446)]=u,m=await t[o(469)](f,l2);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,m=await t.request(g,kc);break;case a[o(487)]:const v={};v.method=c,v[s(446)]=u,m=await t.request(v,Tc);break;case a.ypHTC:const y={};y.method=c,m=await t.request(y,Mn);break}const p={};return p.result=m,p.jsonrpc=a.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),m};function He(e,t){const r=Ii();return He=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},He(e,t)}const z7=(e,t)=>{const r=He,n=He,o={vYlhn:function(i,a){return i===a},DhPFX:r(470),NYVNC:function(i,a,l,c){return i(a,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(i,a)=>{var l,c,u,m,p;const f=n,g=r,{id:v,method:y}=i;try{o[f(451)](y,o.DhPFX)?await s.call(e,i,a):await o[g(474)](U7,e,t,i)}catch(w){const{code:_,message:h,data:T}=w;try{if(_){const b={};b[g(485)]=_,b[f(422)]=h,b.data=T;const k={};k[g(448)]=b,k.jsonrpc=o[f(417)],k.id=v,await((l=e?.transport)==null?void 0:l[g(460)](k))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(b){(p=(m=e?.transport)==null?void 0:m.onerror)==null||p.call(m,b)}}}},F7=(e,t)=>{const r=He,n=He,o={};o[r(476)]=r(439),o[r(431)]=function(i,a){return i!==a},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async i=>{var a,l;const c=r,u=n,{method:m,params:p}=i;if(m!==s[c(476)]&&(s.QWYMz(m,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](i)}catch(f){(l=(a=e?.[c(488)])==null?void 0:a[c(480)])==null||l.call(a,f)}}},V7=(e,t)=>async r=>{var n,o,s,i,a;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(D7,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){(a=(i=e?.[l(488)])==null?void 0:i.onerror)==null||a.call(i,v)}}},Z7=(e,t)=>async r=>{var n,o,s;const i=He,a=He,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[i(420)]=a(453);const c=l,{method:u,params:m}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[a(420)])||m?.[a(490)]))try{const p={...r};p.jsonrpc=i(465),await((n=t?.[i(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function Ii(){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 Ii=function(){return e},Ii()}const B7=(e,t)=>async r=>{var n,o,s,i,a,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(i=(s=e?.transport)==null?void 0:s[c(480)])==null||i.call(s,f)}catch(w){(l=(a=e?.[c(488)])==null?void 0:a[u(480)])==null||l.call(a,w)}}},bu=()=>{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)},i=()=>{const l=He;r[l(430)]=-505*7+1322+2213},a={};return a.handleListener=n,a[e(447)]=o,a.removeListener=s,a.clearListener=i,a},H7=e=>{const t=He,r=He,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(423)](bu);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)](bu);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(bu);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=i,e[r(426)]=a}},J7=(e,{beforeInit:t,afterInit:r}={})=>{const n=He,o=He,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(H7,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)})},G7=Vr;(function(e,t){const r=Vr,n=Vr,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())}})(xi,995159+-6*-266138+-1619768);const W7=()=>{const e=Vr,t=Vr,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)})},K7=e=>{const t=Vr,r=Vr,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)]("")},dn={};dn[G7(211)]=W7,dn.randomBytes=K7;function Vr(e,t){const r=xi();return Vr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},Vr(e,t)}function xi(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return xi=function(){return e},xi()}function Zr(e,t){const r=Ei();return Zr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Zr(e,t)}const _r=Zr,ms=Zr;(function(e,t){const r=Zr,n=Zr,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())}})(Ei,-4*308317+753182*2+658196);const Y7=(e,t)=>{const r=Zr,n=Zr,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)](z7,e,t),F7(e,t);const s=o[n(283)](V7,t,e),i=o[n(294)](B7,t,e),a=o[r(277)](Z7,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)}},ku=(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,wu)&&((i=r._eventSource)==null||i.addEventListener(n.AIICR,()=>{var a;(a=r[Zr(295)])==null||a.close()})),n.Qalmc(Y7,e,t)},s={};s.afterInit=o,n.Qalmc(J7,t,s)},f_=(e,t=dn[_r(299)]())=>{const r=_r,n=_r,o={RVabx:function(u,m,p){return u(m,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const i=s,a={};a["sse-session-id"]=t;const l={};l.headers=a,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,m){const p=r,f=r,g=new Headers(m?.[p(268)]||{});Object.entries(i).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,i.Authorization=n(256)+e),c},h_=(e,t=dn[_r(299)]())=>{const r=ms,n=_r,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},Cu=async(e,t,r)=>{const n=_r,o=_r,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,or)){const l=await t();return await i[n(257)](l),await Cu(e,t,r)}else throw a}},m_=(e,t)=>{const r=ms,n=ms,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 Ei(){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 Ei=function(){return e},Ei()}const Q7=async e=>{const t=ms,r=_r,n={GKDjq:function(x,j,M){return x(j,M)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(x){return x()},kdowC:function(x,j,M,D){return x(j,M,D)},KkViY:"sessionId"},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:m}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const f=p,g=a||dn[r(299)](),v=n[t(289)](f_,i,g);if(c){const x={...v.requestInit,...c};x[r(268)]={...v[r(280)][t(268)],...c.headers},f.requestInit=x}else f.requestInit=v[t(280)];if(u){const x={...v[t(270)],...u};f.eventSourceInit=x}else f.eventSourceInit=v[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const _=w,h={};h.name=n[r(261)],h[t(288)]=n.mcbiU;const T={};T[t(251)]=_;const b=new bi(h,T),k=()=>new wu(new URL(s),f);let S=n[t(282)](k);if(l){const x=m_(l,m);S=await n[t(263)](Cu,b,x,k)}else await b.connect(S);ku(b,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const I={};return I.transport=S,I.sessionId=S[r(286)],I},X7=async e=>{const t=ms,r=_r,n={wfHUn:function(x,j,M){return x(j,M)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(x){return x()},PdsSn:function(x,j,M,D){return x(j,M,D)}},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:m}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const f=p,g=a||dn.randomUUID(),v=n[r(272)](h_,i,g);if(c){const x={...v[t(280)],...c};x.headers={...v.requestInit[t(268)],...c.headers},f.requestInit=x}else f[r(280)]=v[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const _=w,h={};h.name=n[t(262)],h.version=n.omKPe;const T={};T.capabilities=_;const b=new bi(h,T),k=()=>new ka(new URL(s),f);let S=n.rSiEq(k);if(l){const x=n[t(272)](m_,l,m);S=await n[t(296)](Cu,b,x,k)}else await b[t(260)](S);n.PdsSn(ku,b,o,S);const I={};return I.transport=S,I[r(286)]=S[r(286)],I},eE=async e=>{const t=_r,r=_r,n={eZwNI:function(w,_,h,T){return w(_,h,T)}},{client:o,url:s,token:i,sessionId:a}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,m={};m.name="mcp-socket-proxy-client",m.version=r(248);const p={};p[r(251)]=u;const f=new bi(m,p),g=a||dn[r(299)](),v=new d_(new URL(s+"?sessionId="+g+r(265)+i));await f.connect(v),n[t(259)](ku,f,o,v);const y={};return y.transport=v,y[r(286)]=g,y},pn=vr,gs=vr;(function(e,t){const r=vr,n=vr,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())}})($i,1297719+-42747*-22+-1289197);function vr(e,t){const r=$i();return vr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},vr(e,t)}const tE=()=>dn.randomBytes(-8746+-382*-23);class r${constructor(t){const r=vr,n=vr,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(tE),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=vr,c=vr,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();(a=(i=this._callBackPromise).resolve)==null||a.call(i,f.code)}async[pn(191)](t,r){const n=pn,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=vr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[pn(206)]}get[gs(190)](){return this._clientMetadata}[pn(213)](){return this[pn(197)]}[gs(218)](){return this[gs(200)]}[pn(194)](t){this._clientInformation=t}tokens(){return this[gs(210)]}saveTokens(t){const r=gs;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[pn(212)](){const t=pn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function $i(){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 $i=function(){return e},$i()}(function(e,t){for(var r=Pi,n=Pi,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())}})(Ri,262*-2438+1346066*-1+2*1373311);function Ri(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Ri=function(){return e},Ri()}function Pi(e,t){var r=Ri();return Pi=function(n,o){n=n-287;var s=r[n];return s},Pi(e,t)}class rE{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new bi(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:i,onError:a}=t;if(i===!0){const u={client:this.client,url:r,token:n,sessionId:o};let m;return await(async()=>{const{transport:f,sessionId:g}=s==="sse"?await Q7(u):s==="socket"?await eE(u):await X7(u);f.onerror=async v=>{a?.(v)},m={transport:f,sessionId:g}})(),m}const l=new URL(r);let c;if(s==="channel"&&(c=new j7(r),await this.client.connect(c)),s==="sse"){const u=f_(n,o);c=new wu(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new d_(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=h_(n,o);c=new ka(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,os,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(Cc,t)}onCreateMessage(t){this.client.setRequestHandler(bc,t)}onListRoots(t){this.client.setRequestHandler(i2,t)}onToolListChanged(t){this.client.setNotificationHandler(wc,t)}onPromptListChanged(t){this.client.setNotificationHandler(vc,t)}onResourceListChanged(t){this.client.setNotificationHandler(hc,t)}onResourceUpdated(t){this.client.setNotificationHandler(Qm,t)}onLoggingMessage(t){this.client.setNotificationHandler(o2,t)}async onPagehide(t){t.persisted||(nE(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const nE=e=>e instanceof ka,g_=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]=Df({description:o,inputSchema:ro({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}};function oE(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);i(l,c),a(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 i(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=i;function a(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=a,e.default=o})(_u)),_u}var ui={},Fy;function l7(){if(Fy)return ui;Fy=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=Re(),t=Le(),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 ui.default=n,ui}var di={},Vy;function Zy(){if(Vy)return di;Vy=1,Object.defineProperty(di,"__esModule",{value:!0});const e=gr(),t=Re(),r=cn(),n=Le(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:i})=>(0,t._)`{additionalProperty: ${i.additionalProperty}}`},code(i){const{gen:a,schema:l,parentSchema:c,data:u,errsCount:m,it:p}=i;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(),i.ok((0,t._)`${m} === ${r.default.errors}`);function w(){a.forIn("key",u,k=>{!v.length&&!y.length?T(k):a.if(_(k),()=>T(k))})}function _(k){let S;if(v.length>8){const I=(0,n.schemaRefOrVal)(p,c.properties,"properties");S=(0,e.isOwnProperty)(a,I,k)}else v.length?S=(0,t.or)(...v.map(I=>(0,t._)`${k} === ${I}`)):S=t.nil;return y.length&&(S=(0,t.or)(S,...y.map(I=>(0,t._)`${(0,e.usePattern)(i,I)}.test(${k})`))),(0,t.not)(S)}function h(k){a.code((0,t._)`delete ${u}[${k}]`)}function T(k){if(g.removeAdditional==="all"||g.removeAdditional&&l===!1){h(k);return}if(l===!1){i.setParams({additionalProperty:k}),i.error(),f||a.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const S=a.name("valid");g.removeAdditional==="failing"?(b(k,S,!1),a.if((0,t.not)(S),()=>{i.reset(),h(k)})):(b(k,S),f||a.if((0,t.not)(S),()=>a.break()))}}function b(k,S,I){const x={keyword:"additionalProperties",dataProp:k,dataPropType:n.Type.Str};I===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),i.subschema(x,S)}}};return di.default=s,di}var pi={},By;function c7(){if(By)return pi;By=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Ua(),t=gr(),r=Le(),n=Zy(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const m=(0,t.allSchemaProperties)(a);for(const y of m)u.definedProperties.add(y);u.opts.unevaluated&&m.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(i,(0,r.toHash)(m),u.props));const p=m.filter(y=>!(0,r.alwaysValidSchema)(u,a[y]));if(p.length===0)return;const f=i.name("valid");for(const y of p)g(y)?v(y):(i.if((0,t.propertyInData)(i,c,y,u.opts.ownProperties)),v(y),u.allErrors||i.else().var(f,!0),i.endIf()),s.it.definedProperties.add(y),s.ok(f);function g(y){return u.opts.useDefaults&&!u.compositeRule&&a[y].default!==void 0}function v(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},f)}}};return pi.default=o,pi}var fi={},Hy;function u7(){if(Hy)return fi;Hy=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=gr(),t=Re(),r=Le(),n=Le(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:i,schema:a,data:l,parentSchema:c,it:u}=s,{opts:m}=u,p=(0,e.allSchemaProperties)(a),f=p.filter(T=>(0,r.alwaysValidSchema)(u,a[T]));if(p.length===0||f.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const g=m.strictSchema&&!m.allowMatchingProperties&&c.properties,v=i.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(i,u.props));const{props:y}=u;w();function w(){for(const T of p)g&&_(T),u.allErrors?h(T):(i.var(v,!0),h(T),i.if(v))}function _(T){for(const b in g)new RegExp(T).test(b)&&(0,r.checkStrictMode)(u,`property ${b} matches pattern ${T} (use allowMatchingProperties)`)}function h(T){i.forIn("key",l,b=>{i.if((0,t._)`${(0,e.usePattern)(s,T)}.test(${b})`,()=>{const k=f.includes(T);k||s.subschema({keyword:"patternProperties",schemaProp:T,dataProp:b,dataPropType:n.Type.Str},v),u.opts.unevaluated&&y!==!0?i.assign((0,t._)`${y}[${b}]`,!0):!k&&!u.allErrors&&i.if((0,t.not)(v),()=>i.break())})})}}};return fi.default=o,fi}var hi={},Jy;function d7(){if(Jy)return hi;Jy=1,Object.defineProperty(hi,"__esModule",{value:!0});const e=Le(),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 hi.default=t,hi}var mi={},Gy;function p7(){if(Gy)return mi;Gy=1,Object.defineProperty(mi,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:gr().validateUnion,error:{message:"must match a schema in anyOf"}};return mi.default=t,mi}var gi={},Wy;function f7(){if(Wy)return gi;Wy=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=Re(),t=Le(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:i,parentSchema:a,it:l}=o;if(!Array.isArray(i))throw new Error("ajv implementation error");if(l.opts.discriminator&&a.discriminator)return;const c=i,u=s.let("valid",!1),m=s.let("passing",null),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 gi.default=n,gi}var yi={},Ky;function h7(){if(Ky)return yi;Ky=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=Le(),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 yi.default=t,yi}var _i={},Yy;function m7(){if(Yy)return _i;Yy=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=Re(),t=Le(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:i,parentSchema:a,it:l}=s;a.then===void 0&&a.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const m=i.let("valid",!0),p=i.name("_valid");if(f(),s.reset(),c&&u){const v=i.let("ifClause");s.setParams({ifClause:v}),i.if(p,g("then",v),g("else",v))}else c?i.if(p,g("then")):i.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);i.assign(m,p),s.mergeValidEvaluated(w,m),y?i.assign(y,(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 _i.default=n,_i}var vi={},Qy;function g7(){if(Qy)return vi;Qy=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=Le(),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 vi.default=t,vi}var Xy;function y7(){if(Xy)return ai;Xy=1,Object.defineProperty(ai,"__esModule",{value:!0});const e=Ay(),t=o7(),r=Ly(),n=s7(),o=a7(),s=i7(),i=l7(),a=Zy(),l=c7(),c=u7(),u=d7(),m=p7(),p=f7(),f=h7(),g=m7(),v=g7();function y(w=!1){const _=[u.default,m.default,p.default,f.default,g.default,v.default,i.default,a.default,s.default,l.default,c.default];return w?_.push(t.default,n.default):_.push(e.default,r.default),_.push(o.default),_}return ai.default=y,ai}var wi={},bi={},e_;function _7(){if(e_)return bi;e_=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Re(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:i,$data:a,schema:l,schemaCode:c,it:u}=n,{opts:m,errSchemaPath:p,schemaEnv:f,self:g}=u;if(!m.validateFormats)return;a?v():y();function v(){const w=s.scopeValue("formats",{ref:g.formats,code:m.code.formats}),_=s.const("fDef",(0,e._)`${w}[${c}]`),h=s.let("fType"),T=s.let("format");s.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>s.assign(h,(0,e._)`${_}.type || "string"`).assign(T,(0,e._)`${_}.validate`),()=>s.assign(h,(0,e._)`"string"`).assign(T,_)),n.fail$data((0,e.or)(b(),k()));function b(){return m.strictSchema===!1?e.nil:(0,e._)`${c} && !${T}`}function k(){const S=f.$async?(0,e._)`(${_}.async ? await ${T}(${i}) : ${T}(${i}))`:(0,e._)`${T}(${i})`,I=(0,e._)`(typeof ${T} == "function" ? ${S} : ${T}.test(${i}))`;return(0,e._)`${T} && ${T} !== true && ${h} === ${o} && !${I}`}}function y(){const w=g.formats[l];if(!w){b();return}if(w===!0)return;const[_,h,T]=k(w);_===o&&n.pass(S());function b(){if(m.strictSchema===!1){g.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function k(I){const x=I instanceof RegExp?(0,e.regexpCode)(I):m.code.formats?(0,e._)`${m.code.formats}${(0,e.getProperty)(l)}`:void 0,j=s.scopeValue("formats",{key:l,ref:I,code:x});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${j}.validate`]:["string",I,j]}function S(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!f.$async)throw new Error("async format in sync schema");return(0,e._)`await ${T}(${i})`}return typeof h=="function"?(0,e._)`${T}(${i})`:(0,e._)`${T}.test(${i})`}}}};return bi.default=r,bi}var t_;function v7(){if(t_)return wi;t_=1,Object.defineProperty(wi,"__esModule",{value:!0});const t=[_7().default];return wi.default=t,wi}var Dn={},r_;function w7(){return r_||(r_=1,Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.contentVocabulary=Dn.metadataVocabulary=void 0,Dn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Dn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Dn}var n_;function b7(){if(n_)return Za;n_=1,Object.defineProperty(Za,"__esModule",{value:!0});const e=Bx(),t=n7(),r=y7(),n=v7(),o=w7(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Za.default=s,Za}var ki={},hs={},o_;function k7(){if(o_)return hs;o_=1,Object.defineProperty(hs,"__esModule",{value:!0}),hs.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(hs.DiscrError=e={})),hs}var s_;function C7(){if(s_)return ki;s_=1,Object.defineProperty(ki,"__esModule",{value:!0});const e=Re(),t=k7(),r=hu(),n=Fa(),o=Le(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:a,tagName:l}})=>a===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:a,tag:l,tagName:c}})=>(0,e._)`{error: ${a}, tag: ${c}, tagValue: ${l}}`},code(a){const{gen:l,data:c,schema:u,parentSchema:m,it:p}=a,{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(),()=>a.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:g})),a.ok(v);function w(){const T=h();l.if(!1);for(const b in T)l.elseIf((0,e._)`${y} === ${b}`),l.assign(v,_(T[b]));l.else(),a.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:g}),l.endIf()}function _(T){const b=l.name("valid"),k=a.subschema({keyword:"oneOf",schemaProp:T},b);return a.mergeEvaluated(k,e.Name),b}function h(){var T;const b={},k=I(m);let S=!0;for(let M=0;M<f.length;M++){let D=f[M];if(D?.$ref&&!(0,o.schemaHasRulesButRef)(D,p.self.RULES)){const O=D.$ref;if(D=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,O),D instanceof r.SchemaEnv&&(D=D.schema),D===void 0)throw new n.default(p.opts.uriResolver,p.baseId,O)}const A=(T=D?.properties)===null||T===void 0?void 0:T[g];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${g}"`);S=S&&(k||I(D)),x(A,M)}if(!S)throw new Error(`discriminator: "${g}" must be required`);return b;function I({required:M}){return Array.isArray(M)&&M.includes(g)}function x(M,D){if(M.const)j(M.const,D);else if(M.enum)for(const A of M.enum)j(A,D);else throw new Error(`discriminator: "properties/${g}" must have "const" or "enum"`)}function j(M,D){if(typeof M!="string"||M in b)throw new Error(`discriminator: "${g}" values must be unique strings`);b[M]=D}}}};return ki.default=i,ki}const T7={$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 a_;function i_(){return a_||(a_=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=Fx(),n=b7(),o=C7(),s=T7,i=["/properties"],a="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,i):s;this.addMetaSchema(g,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=Ua();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Re();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=fu();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return m.default}});var p=Fa();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Ma,Ma.exports)),Ma.exports}var S7=i_();const I7=bl(S7);var Ci={exports:{}},vu={},l_;function x7(){return l_||(l_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(M,D){return{validate:M,compare:D}}e.fullFormats={date:t(s,i),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:j,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:k},int64:{type:"number",validate:S},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,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 D=n.exec(M);if(!D)return!1;const A=+D[1],O=+D[2],H=+D[3];return O>=1&&O<=12&&H>=1&&H<=(O===2&&r(A)?29:o[O])}function i(M,D){if(M&&D)return M>D?1:M<D?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(M){return function(A){const O=a.exec(A);if(!O)return!1;const H=+O[1],Q=+O[2],Y=+O[3],W=O[4],pe=O[5]==="-"?-1:1,Z=+(O[6]||0),P=+(O[7]||0);if(Z>23||P>59||M&&!W)return!1;if(H<=23&&Q<=59&&Y<60)return!0;const B=Q-P*pe,F=H-Z*pe-(B<0?1:0);return(F===23||F===-1)&&(B===59||B===-1)&&Y<61}}function c(M,D){if(!(M&&D))return;const A=new Date("2020-01-01T"+M).valueOf(),O=new Date("2020-01-01T"+D).valueOf();if(A&&O)return A-O}function u(M,D){if(!(M&&D))return;const A=a.exec(M),O=a.exec(D);if(A&&O)return M=A[1]+A[2]+A[3],D=O[1]+O[2]+O[3],M>D?1:M<D?-1:0}const m=/t|\s/i;function p(M){const D=l(M);return function(O){const H=O.split(m);return H.length===2&&s(H[0])&&D(H[1])}}function f(M,D){if(!(M&&D))return;const A=new Date(M).valueOf(),O=new Date(D).valueOf();if(A&&O)return A-O}function g(M,D){if(!(M&&D))return;const[A,O]=M.split(m),[H,Q]=D.split(m),Y=i(A,H);if(Y!==void 0)return Y||c(O,Q)}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 T=-2147483648,b=2**31-1;function k(M){return Number.isInteger(M)&&M<=b&&M>=T}function S(M){return Number.isInteger(M)}function I(){return!0}const x=/[^\\]\\Z/;function j(M){if(x.test(M))return!1;try{return new RegExp(M),!0}catch{return!1}}})(vu)),vu}var wu={},c_;function E7(){return c_||(c_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=i_(),r=Re(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:a,schemaCode:l})=>(0,r.str)`should be ${o[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>(0,r._)`{comparison: ${o[a].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(a){const{gen:l,data:c,schemaCode:u,keyword:m,it:p}=a,{opts:f,self:g}=p;if(!f.validateFormats)return;const v=new t.KeywordCxt(p,g.RULES.all.format.definition,"format");v.$data?y():w();function y(){const h=l.scopeValue("formats",{ref:g.formats,code:f.code.formats}),T=l.const("fmt",(0,r._)`${h}[${v.schemaCode}]`);a.fail$data((0,r.or)((0,r._)`typeof ${T} != "object"`,(0,r._)`${T} instanceof RegExp`,(0,r._)`typeof ${T}.compare != "function"`,_(T)))}function w(){const h=v.schema,T=g.formats[h];if(!T||T===!0)return;if(typeof T!="object"||T instanceof RegExp||typeof T.compare!="function")throw new Error(`"${m}": format "${h}" does not define "compare" function`);const b=l.scopeValue("formats",{key:h,ref:T,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(h)}`:void 0});a.fail$data(_(b))}function _(h){return(0,r._)`${h}.compare(${c}, ${u}) ${o[m].fail} 0`}},dependencies:["format"]};const i=a=>(a.addKeyword(e.formatLimitDefinition),a);e.default=i})(wu)),wu}var u_;function $7(){return u_||(u_=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=x7(),n=E7(),o=Re(),s=new o.Name("fullFormats"),i=new o.Name("fastFormats"),a=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[m,p]=u.mode==="fast"?[r.fastFormats,i]:[r.fullFormats,s],f=u.formats||r.formatNames;return l(c,f,m,p),u.keywords&&(0,n.default)(c),c};a.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=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a})(Ci,Ci.exports)),Ci.exports}var R7=$7();const P7=bl(R7);function N7(){const e=new I7({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return P7(e),e}class M7{constructor(t){this._ajv=t??N7()}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 O7{constructor(t){this._client=t}async*callToolStream(t,r=os,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 be(xe.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 be(xe.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof be){yield{type:"error",error:u};return}yield{type:"error",error:new be(xe.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 A7(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 q7(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 Ti(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&&Ti(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&Ti(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&Ti(r,t)}}function L7(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class Si extends Px{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 M7,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",bc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",wc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",mc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new O7(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Nx(this._capabilities,t)}setRequestHandler(t,r){const o=Lg(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Na(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=ln(Tc,l);if(!u.success){const _=u.error instanceof Error?u.error.message:String(u.error);throw new be(xe.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:m}=u.data;m.mode=m.mode??"form";const{supportsFormMode:p,supportsUrlMode:f}=L7(this._capabilities.elicitation);if(m.mode==="form"&&!p)throw new be(xe.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!f)throw new be(xe.InvalidParams,"Client does not support URL-mode elicitation requests");const g=await Promise.resolve(r(l,c));if(m.task){const _=ln(rs,g);if(!_.success){const h=_.error instanceof Error?_.error.message:String(_.error);throw new be(xe.InvalidParams,`Invalid task creation result: ${h}`)}return _.data}const v=ln(Sc,g);if(!v.success){const _=v.error instanceof Error?v.error.message:String(v.error);throw new be(xe.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{Ti(w,y.content)}catch{}return y};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){const a=async(l,c)=>{const u=ln(kc,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new be(xe.InvalidParams,`Invalid sampling request: ${y}`)}const{params:m}=u.data,p=await Promise.resolve(r(l,c));if(m.task){const y=ln(rs,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new be(xe.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const g=m.tools||m.toolChoice?s2:Cc,v=ln(g,p);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new be(xe.InvalidParams,`Invalid sampling result: ${y}`)}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:pa,capabilities:this._capabilities,clientInfo:this._clientInfo}},Vm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!H5.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){A7(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&q7(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Mn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},a2,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Mn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},e2,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},Xm,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Wm,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Km,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},Ym,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Mn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Mn,r)}async callTool(t,r=os,n){if(this.isToolTaskRequired(t.name))throw new be(xe.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 be(xe.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 be(xe.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof be?i:new be(xe.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},r2,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=UT.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:i,debounceMs:a}=s.data,{onChanged:l}=n,c=async()=>{if(!i){l(null,null);return}try{const m=await o();l(null,m)}catch(m){const p=m instanceof Error?m:new Error(String(m));l(p,null)}},u=()=>{if(a){const m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);const p=setTimeout(c,a);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}const j7="mcp";class d_{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,j7),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=Nn.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 _o=yr;(function(e,t){const r=yr,n=yr,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())}})(Ii,-118057+3521*-35+-2099*-233);const U7=()=>{const e=yr,t=yr,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}},D7=(e,t,r)=>{const n=yr,o=yr,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 p_{constructor(t){this._port=t}async[_o(401)](){const t=_o,r=_o;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const i=t;try{const a=Nn.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=yr,l=yr;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=_o,o=_o;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class z7 extends p_{constructor(t,r=U7()){const n=_o,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)](D7,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}function Ii(){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 Ii=function(){return e},Ii()}function yr(e,t){const r=Ii();return yr=function(n,o){return n=n-(17227+1*-16844),r[n]},yr(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())}})(xi,-411935*1+228107+208149*2);const F7=async(e,t,r)=>{var n;const o=He,s=He,i={};i.VRyiJ="tools/list",i.VkPYu="tools/call",i[o(475)]=o(411),i.SoCaE="resources/templates/list",i[s(484)]="resources/read",i[o(461)]="prompts/get",i.srIIC=s(477),i[s(436)]=s(478),i[s(442)]=o(437),i.dEmVs=o(465);const a=i,{id:l,method:c,params:u}=r;let m={};switch(c){case a.VRyiJ:m=await t.listTools(u);break;case a.VkPYu:m=await t.callTool(u);break;case a.fgMSD:m=await t.listResources(u);break;case a[s(466)]:m=await t.listResourceTemplates(u);break;case a.sthgI:m=await t[o(455)](u);break;case s(486):m=await t.subscribeResource(u);break;case o(410):m=await t.unsubscribeResource(u);break;case a[s(461)]:m=await t[s(414)](u);break;case a[o(412)]:m=await t[o(491)](u);break;case a[o(436)]:m=await t[o(478)]();break;case a.kkNqg:m=await t.complete(u);break;case o(464):m=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=m,p.jsonrpc=a[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},V7=async(e,t,r)=>{var n;const o=He,s=He,i={};i[o(487)]=s(462),i.ypHTC="ping",i.fPExS=o(465);const a=i,{id:l,method:c,params:u}=r;let m={};switch(c){case"roots/list":const f={};f.method=c,f[s(446)]=u,m=await t[o(469)](f,l2);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,m=await t.request(g,Cc);break;case a[o(487)]:const v={};v.method=c,v[s(446)]=u,m=await t.request(v,Sc);break;case a.ypHTC:const y={};y.method=c,m=await t.request(y,Mn);break}const p={};return p.result=m,p.jsonrpc=a.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),m};function He(e,t){const r=xi();return He=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},He(e,t)}const Z7=(e,t)=>{const r=He,n=He,o={vYlhn:function(i,a){return i===a},DhPFX:r(470),NYVNC:function(i,a,l,c){return i(a,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(i,a)=>{var l,c,u,m,p;const f=n,g=r,{id:v,method:y}=i;try{o[f(451)](y,o.DhPFX)?await s.call(e,i,a):await o[g(474)](F7,e,t,i)}catch(w){const{code:_,message:h,data:T}=w;try{if(_){const b={};b[g(485)]=_,b[f(422)]=h,b.data=T;const k={};k[g(448)]=b,k.jsonrpc=o[f(417)],k.id=v,await((l=e?.transport)==null?void 0:l[g(460)](k))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(b){(p=(m=e?.transport)==null?void 0:m.onerror)==null||p.call(m,b)}}}},B7=(e,t)=>{const r=He,n=He,o={};o[r(476)]=r(439),o[r(431)]=function(i,a){return i!==a},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async i=>{var a,l;const c=r,u=n,{method:m,params:p}=i;if(m!==s[c(476)]&&(s.QWYMz(m,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](i)}catch(f){(l=(a=e?.[c(488)])==null?void 0:a[c(480)])==null||l.call(a,f)}}},H7=(e,t)=>async r=>{var n,o,s,i,a;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(V7,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){(a=(i=e?.[l(488)])==null?void 0:i.onerror)==null||a.call(i,v)}}},J7=(e,t)=>async r=>{var n,o,s;const i=He,a=He,l={};l.xmcLM=function(p,f){return p!==f},l.xSWLt="notifications/initialized",l[i(420)]=a(453);const c=l,{method:u,params:m}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[a(420)])||m?.[a(490)]))try{const p={...r};p.jsonrpc=i(465),await((n=t?.[i(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function xi(){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 xi=function(){return e},xi()}const G7=(e,t)=>async r=>{var n,o,s,i,a,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(i=(s=e?.transport)==null?void 0:s[c(480)])==null||i.call(s,f)}catch(w){(l=(a=e?.[c(488)])==null?void 0:a[u(480)])==null||l.call(a,w)}}},bu=()=>{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)},i=()=>{const l=He;r[l(430)]=-505*7+1322+2213},a={};return a.handleListener=n,a[e(447)]=o,a.removeListener=s,a.clearListener=i,a},W7=e=>{const t=He,r=He,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:i,clearListener:a}=n[t(423)](bu);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)](bu);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(bu);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=i,e[r(426)]=a}},K7=(e,{beforeInit:t,afterInit:r}={})=>{const n=He,o=He,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(W7,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)})},Y7=Vr;(function(e,t){const r=Vr,n=Vr,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())}})(Ei,995159+-6*-266138+-1619768);const Q7=()=>{const e=Vr,t=Vr,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)})},X7=e=>{const t=Vr,r=Vr,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)]("")},dn={};dn[Y7(211)]=Q7,dn.randomBytes=X7;function Vr(e,t){const r=Ei();return Vr=function(n,o){return n=n-(-7373+7187*1+395),r[n]},Vr(e,t)}function Ei(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Ei=function(){return e},Ei()}function Zr(e,t){const r=$i();return Zr=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},Zr(e,t)}const _r=Zr,ms=Zr;(function(e,t){const r=Zr,n=Zr,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())}})($i,-4*308317+753182*2+658196);const eE=(e,t)=>{const r=Zr,n=Zr,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)](Z7,e,t),B7(e,t);const s=o[n(283)](H7,t,e),i=o[n(294)](G7,t,e),a=o[r(277)](J7,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)}},ku=(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,Ia)&&((i=r._eventSource)==null||i.addEventListener(n.AIICR,()=>{var a;(a=r[Zr(295)])==null||a.close()})),n.Qalmc(eE,e,t)},s={};s.afterInit=o,n.Qalmc(K7,t,s)},f_=(e,t=dn[_r(299)]())=>{const r=_r,n=_r,o={RVabx:function(u,m,p){return u(m,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const i=s,a={};a["sse-session-id"]=t;const l={};l.headers=a,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,m){const p=r,f=r,g=new Headers(m?.[p(268)]||{});Object.entries(i).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,i.Authorization=n(256)+e),c},h_=(e,t=dn[_r(299)]())=>{const r=ms,n=_r,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},Cu=async(e,t,r)=>{const n=_r,o=_r,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,or)){const l=await t();return await i[n(257)](l),await Cu(e,t,r)}else throw a}},m_=(e,t)=>{const r=ms,n=ms,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 $i(){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 $i=function(){return e},$i()}const tE=async e=>{const t=ms,r=_r,n={GKDjq:function(x,j,M){return x(j,M)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(x){return x()},kdowC:function(x,j,M,D){return x(j,M,D)},KkViY:"sessionId"},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:m}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const f=p,g=a||dn[r(299)](),v=n[t(289)](f_,i,g);if(c){const x={...v.requestInit,...c};x[r(268)]={...v[r(280)][t(268)],...c.headers},f.requestInit=x}else f.requestInit=v[t(280)];if(u){const x={...v[t(270)],...u};f.eventSourceInit=x}else f.eventSourceInit=v[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const _=w,h={};h.name=n[r(261)],h[t(288)]=n.mcbiU;const T={};T[t(251)]=_;const b=new Si(h,T),k=()=>new Ia(new URL(s),f);let S=n[t(282)](k);if(l){const x=m_(l,m);S=await n[t(263)](Cu,b,x,k)}else await b.connect(S);ku(b,o,S),S.sessionId=S[r(274)].searchParams[t(297)](n.KkViY);const I={};return I.transport=S,I.sessionId=S[r(286)],I},rE=async e=>{const t=ms,r=_r,n={wfHUn:function(x,j,M){return x(j,M)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(x){return x()},PdsSn:function(x,j,M,D){return x(j,M,D)}},{client:o,url:s,token:i,sessionId:a,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:m}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const f=p,g=a||dn.randomUUID(),v=n[r(272)](h_,i,g);if(c){const x={...v[t(280)],...c};x.headers={...v.requestInit[t(268)],...c.headers},f.requestInit=x}else f[r(280)]=v[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const _=w,h={};h.name=n[t(262)],h.version=n.omKPe;const T={};T.capabilities=_;const b=new Si(h,T),k=()=>new ka(new URL(s),f);let S=n.rSiEq(k);if(l){const x=n[t(272)](m_,l,m);S=await n[t(296)](Cu,b,x,k)}else await b[t(260)](S);n.PdsSn(ku,b,o,S);const I={};return I.transport=S,I[r(286)]=S[r(286)],I},nE=async e=>{const t=_r,r=_r,n={eZwNI:function(w,_,h,T){return w(_,h,T)}},{client:o,url:s,token:i,sessionId:a}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,m={};m.name="mcp-socket-proxy-client",m.version=r(248);const p={};p[r(251)]=u;const f=new Si(m,p),g=a||dn[r(299)](),v=new d_(new URL(s+"?sessionId="+g+r(265)+i));await f.connect(v),n[t(259)](ku,f,o,v);const y={};return y.transport=v,y[r(286)]=g,y},pn=vr,gs=vr;(function(e,t){const r=vr,n=vr,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())}})(Ri,1297719+-42747*-22+-1289197);function vr(e,t){const r=Ri();return vr=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},vr(e,t)}const oE=()=>dn.randomBytes(-8746+-382*-23);class r${constructor(t){const r=vr,n=vr,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(oE),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=vr,c=vr,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();(a=(i=this._callBackPromise).resolve)==null||a.call(i,f.code)}async[pn(191)](t,r){const n=pn,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=vr;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[pn(206)]}get[gs(190)](){return this._clientMetadata}[pn(213)](){return this[pn(197)]}[gs(218)](){return this[gs(200)]}[pn(194)](t){this._clientInformation=t}tokens(){return this[gs(210)]}saveTokens(t){const r=gs;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[pn(212)](){const t=pn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function Ri(){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 Ri=function(){return e},Ri()}(function(e,t){for(var r=Ni,n=Ni,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())}})(Pi,262*-2438+1346066*-1+2*1373311);function Pi(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Pi=function(){return e},Pi()}function Ni(e,t){var r=Pi();return Ni=function(n,o){n=n-287;var s=r[n];return s},Ni(e,t)}class sE{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Si(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:i,onError:a}=t;if(i===!0){const u={client:this.client,url:r,token:n,sessionId:o};let m;return await(async()=>{const{transport:f,sessionId:g}=s==="sse"?await tE(u):s==="socket"?await nE(u):await rE(u);f.onerror=async v=>{a?.(v)},m={transport:f,sessionId:g}})(),m}const l=new URL(r);let c;if(s==="channel"&&(c=new z7(r),await this.client.connect(c)),s==="sse"){const u=f_(n,o);c=new Ia(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new d_(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=h_(n,o);c=new ka(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,os,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(Tc,t)}onCreateMessage(t){this.client.setRequestHandler(kc,t)}onListRoots(t){this.client.setRequestHandler(i2,t)}onToolListChanged(t){this.client.setNotificationHandler(bc,t)}onPromptListChanged(t){this.client.setNotificationHandler(wc,t)}onResourceListChanged(t){this.client.setNotificationHandler(mc,t)}onResourceUpdated(t){this.client.setNotificationHandler(Qm,t)}onLoggingMessage(t){this.client.setNotificationHandler(o2,t)}async onPagehide(t){t.persisted||(aE(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const aE=e=>e instanceof ka,g_=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]=Df({description:o,inputSchema:ro({...s,properties:s.properties??{},additionalProperties:!1}),execute:i})}return t}catch(r){throw r}};function iE(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
|
|
89
89
|
# 工具调用
|
|
90
90
|
|
|
91
91
|
你可以根据需要调用以下工具:
|
|
@@ -121,20 +121,20 @@ Thought: 用户想要获取今天的日期,我需要调用日期相关的工
|
|
|
121
121
|
- 必须严格按照 XML 格式调用工具
|
|
122
122
|
- arguments 必须是有效的 JSON 格式
|
|
123
123
|
- 如果不需要调用工具,直接给出最终答案即可
|
|
124
|
-
`,r}function y_(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
|
|
125
|
-
${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)},m=a[0]?.role==="system"?a:[u,...a];return t===
|
|
124
|
+
`,r}function y_(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 lE={openai:V2,deepseek:qg};class cE{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=lE[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"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new ka(new URL(o.url),{requestInit:s})}else if("type"in t&&t.type==="sse"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Ia(new URL(o.url),{requestInit:s})}else"type"in t&&t.type==="extension"?r=new Ex(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await Z5({transport:r});return o.__transport__=r,o}else{const o=new sE({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 xa||r&&r instanceof p_)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 g_(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={},r=!0){const n=Object.values(this.mcpTools).reduce((o,s)=>({...o,...s}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=iE(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
|
|
125
|
+
${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)},m=a[0]?.role==="system"?a:[u,...a];return t===Gl?this._chatReActStream(m,s,l,n,o):this._chatReActNonStream(m,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const i=[];for(let a=r.length-1;a>=0;a--){const l=r[a];if(this._messageHasImage(l.content))if(s<n)i.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&i.unshift(u)}else i.unshift(l)}return o.push(...i),o}async _chatReActNonStream(t,r,n,o,s){let i=[...t];const a=t[0]?.role==="system"?t[0]:null,l=a?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(a,l,u),{tools:f,...g}=s,y=(await sm({model:this.llm(n),messages:p,...g})).text,w={role:"assistant",content:y};l.push(w),i.push(w);const _=y_(y,r);if(!_)return this.responseMessages=i,{text:y,response:{messages:i}};const h=await this._executeReActToolCall(_.toolName,_.arguments,r),k={role:"user",content:`<tool_response>
|
|
126
126
|
${h.success?JSON.stringify(h.result):`工具执行失败 - ${h.error}`}
|
|
127
|
-
</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((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=i._buildMessagesForModel(g,v,_),{tools:T,...b}=s;delete b.system,delete b.onFinish;const k=await
|
|
127
|
+
</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((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=i._buildMessagesForModel(g,v,_),{tools:T,...b}=s;delete b.system,delete b.onFinish;const k=await Gl({...b,model:a,messages:h});let S="";for await(const Q of k.fullStream)Q.type==="text-delta"?(S+=Q.text||"",p.enqueue({type:"text-delta",text:Q.text})):Q.type==="text-start"?p.enqueue({type:"text-start"}):Q.type==="text-end"||Q.type==="finish-step"||Q.type==="finish"||Q.type==="start"||Q.type==="start-step"||p.enqueue(Q);w+=S;const I={role:"assistant",content:w};v.push(I),f.push(I);const x=y_(w,r);if(!x){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=f,l({messages:f});return}if(x.toolName==="computer"&&x.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.responseMessages=f,l({messages:f});return}const j=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:j,toolName:x.toolName});const M=JSON.stringify(x.arguments,null,2);p.enqueue({type:"tool-input-delta",id:j,delta:M}),p.enqueue({type:"tool-input-end",id:j}),p.enqueue({type:"tool-call",toolCallId:j,toolName:x.toolName,input:x.arguments});const D=await i._executeReActToolCall(x.toolName,x.arguments,r);let A,O=D.result;if(D.success&&D.result&&typeof D.result=="object"&&D.result.screenshot){A=D.result.screenshot;const{screenshot:Q,...Y}=D.result;O=Y}let H="";if(D.success){O&&Array.isArray(O.content)&&O.content.length>0&&O.content[0].text?H=O.content[0].text:H=JSON.stringify(O);let Q=`<tool_response>
|
|
128
128
|
${H}
|
|
129
129
|
</tool_response>`;A&&(Q+=`
|
|
130
|
-
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:j,result:Q});const Y=A?{role:"user",content:[{type:"text",text:Q},{type:"image",image:A}]}:{role:"user",content:Q};v.push(Y),f.push(Y),w=""}else H=`工具执行失败 - ${D.error}`,p.enqueue({type:"tool-error",toolCallId:j,input:x.arguments,error:{message:H}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.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=this._tempMergeTools(o.tools,!1),i={model:this.llm(r),stopWhen:
|
|
131
|
-
]))+`;$r.KANJI=new RegExp(r,"g"),$r.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),$r.BYTE=new RegExp(n,"g"),$r.NUMERIC=new RegExp(e,"g"),$r.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return $r.testKanji=function(l){return o.test(l)},$r.testNumeric=function(l){return s.test(l)},$r.testAlphanumeric=function(l){return i.test(l)},$r}var A_;function Fn(){return A_||(A_=1,(function(e){const t=N_(),r=O_();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}}})(qu)),qu}var q_;function
|
|
132
|
-
Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},Vu=r,Vu}var Zu={exports:{}},F_;function
|
|
133
|
-
Suggested mode is: `+t.toString(T));switch(h===t.KANJI&&!a.isKanjiModeEnabled()&&(h=t.BYTE),h){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(_){return _.reduce(function(h,T){return typeof T=="string"?h.push(y(T,null)):T.data&&h.push(y(T.data,T.mode)),h},[])},e.fromString=function(_,h){const T=m(_,a.isKanjiModeEnabled()),b=g(T),k=v(b,h),S=l.find_path(k.map,"start","end"),I=[];for(let x=1;x<S.length-1;x++)I.push(k.table[S[x]].node);return e.fromArray(f(I))},e.rawSplit=function(_){return e.fromArray(m(_,a.isKanjiModeEnabled()))}})(Uu)),Uu}var Z_;function
|
|
130
|
+
请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:j,result:Q});const Y=A?{role:"user",content:[{type:"text",text:Q},{type:"image",image:A}]}:{role:"user",content:Q};v.push(Y),f.push(Y),w=""}else H=`工具执行失败 - ${D.error}`,p.enqueue({type:"tool-error",toolCallId:j,input:x.arguments,error:{message:H}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),i.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=this._tempMergeTools(o.tools,!1),i={model:this.llm(r),stopWhen:Bl(n),...o,tools:s,activeTools:this._getActiveToolNames(s)};let a=null;if(o.message&&!o.messages)a={role:"user",content:o.message},this.responseMessages.push(a),i.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const c=o.messages[o.messages.length-1];c.role==="user"&&(a=c)}const l=t(i);return l?.response?.then(c=>{const u=c.messages?.[0];a&&u?.role!=="user"&&this.responseMessages.push(a),this.responseMessages.push(...c.messages)}),l}async chat(t){return this._chat(sm,t)}async chatStream(t){return this._chat(Gl,t)}}var vo={},Tu,__;function uE(){return __||(__=1,Tu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Tu}var Su={},fn={},v_;function zn(){if(v_)return fn;v_=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 fn.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},fn.getSymbolTotalCodewords=function(n){return t[n]},fn.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},fn.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},fn.isKanjiModeEnabled=function(){return typeof e<"u"},fn.toSJIS=function(n){return e(n)},fn}var Iu={},w_;function xu(){return w_||(w_=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}}})(Iu)),Iu}var Eu,b_;function dE(){if(b_)return Eu;b_=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Eu=e,Eu}var $u,k_;function pE(){if(k_)return $u;k_=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]},$u=e,$u}var Ru={},C_;function fE(){return C_||(C_=1,(function(e){const t=zn().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let l=1;l<o-1;l++)a[l]=a[l-1]-i;return a.push(6),a.reverse()},e.getPositions=function(n){const o=[],s=e.getRowColCoords(n),i=s.length;for(let a=0;a<i;a++)for(let l=0;l<i;l++)a===0&&l===0||a===0&&l===i-1||a===i-1&&l===0||o.push([s[a],s[l]]);return o}})(Ru)),Ru}var Pu={},T_;function hE(){if(T_)return Pu;T_=1;const e=zn().getSymbolSize,t=7;return Pu.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Pu}var Nu={},S_;function mE(){return S_||(S_=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,l=0,c=null,u=null;for(let m=0;m<s;m++){a=l=0,c=u=null;for(let p=0;p<s;p++){let f=o.get(m,p);f===c?a++:(a>=5&&(i+=t.N1+(a-5)),c=f,a=1),f=o.get(p,m),f===u?l++:(l>=5&&(i+=t.N1+(l-5)),u=f,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}})(Nu)),Nu}var Mi={},I_;function x_(){if(I_)return Mi;I_=1;const e=xu(),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 Mi.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}},Mi.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}},Mi}var Mu={},ys={},E_;function gE(){if(E_)return ys;E_=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]})(),ys.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},ys.exp=function(n){return e[n]},ys.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},ys}var $_;function yE(){return $_||($_=1,(function(e){const t=gE();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}})(Mu)),Mu}var Ou,R_;function _E(){if(R_)return Ou;R_=1;const e=yE();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},Ou=t,Ou}var Au={},qu={},Lu={},P_;function N_(){return P_||(P_=1,Lu.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Lu}var $r={},M_;function O_(){if(M_)return $r;M_=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
|
|
131
|
+
]))+`;$r.KANJI=new RegExp(r,"g"),$r.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),$r.BYTE=new RegExp(n,"g"),$r.NUMERIC=new RegExp(e,"g"),$r.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return $r.testKanji=function(l){return o.test(l)},$r.testNumeric=function(l){return s.test(l)},$r.testAlphanumeric=function(l){return i.test(l)},$r}var A_;function Fn(){return A_||(A_=1,(function(e){const t=N_(),r=O_();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}}})(qu)),qu}var q_;function vE(){return q_||(q_=1,(function(e){const t=zn(),r=x_(),n=xu(),o=Fn(),s=N_(),i=7973,a=t.getBCHDigit(i);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)-a>=0;)g^=i<<t.getBCHDigit(g)-a;return f<<12|g}})(Au)),Au}var ju={},L_;function wE(){if(L_)return ju;L_=1;const e=zn(),t=1335,r=21522,n=e.getBCHDigit(t);return ju.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},ju}var Uu={},Du,j_;function bE(){if(j_)return Du;j_=1;const e=Fn();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))},Du=t,Du}var zu,U_;function kE(){if(U_)return zu;U_=1;const e=Fn(),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)},zu=r,zu}var Fu,D_;function CE(){if(D_)return Fu;D_=1;const e=Fn();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},Fu=t,Fu}var Vu,z_;function TE(){if(z_)return Vu;z_=1;const e=Fn(),t=zn();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]+`
|
|
132
|
+
Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},Vu=r,Vu}var Zu={exports:{}},F_;function SE(){return F_||(F_=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},i={};i[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var l,c,u,m,p,f,g,v,y;!a.empty();){l=a.pop(),c=l.value,m=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],g=m+f,v=i[u],y=typeof i[u]>"u",(y||v>g)&&(i[u]=g,a.push(u,g),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})(Zu)),Zu.exports}var V_;function IE(){return V_||(V_=1,(function(e){const t=Fn(),r=bE(),n=kE(),o=CE(),s=TE(),i=O_(),a=zn(),l=SE();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,_,h){const T=[];let b;for(;(b=w.exec(h))!==null;)T.push({data:b[0],index:b.index,mode:_,length:b[0].length});return T}function m(w){const _=u(i.NUMERIC,t.NUMERIC,w),h=u(i.ALPHANUMERIC,t.ALPHANUMERIC,w);let T,b;return a.isKanjiModeEnabled()?(T=u(i.BYTE,t.BYTE,w),b=u(i.KANJI,t.KANJI,w)):(T=u(i.BYTE_KANJI,t.BYTE,w),b=[]),_.concat(h,T,b).sort(function(S,I){return S.index-I.index}).map(function(S){return{data:S.data,mode:S.mode,length:S.length}})}function p(w,_){switch(_){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function f(w){return w.reduce(function(_,h){const T=_.length-1>=0?_[_.length-1]:null;return T&&T.mode===h.mode?(_[_.length-1].data+=h.data,_):(_.push(h),_)},[])}function g(w){const _=[];for(let h=0;h<w.length;h++){const T=w[h];switch(T.mode){case t.NUMERIC:_.push([T,{data:T.data,mode:t.ALPHANUMERIC,length:T.length},{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.ALPHANUMERIC:_.push([T,{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.KANJI:_.push([T,{data:T.data,mode:t.BYTE,length:c(T.data)}]);break;case t.BYTE:_.push([{data:T.data,mode:t.BYTE,length:c(T.data)}])}}return _}function v(w,_){const h={},T={start:{}};let b=["start"];for(let k=0;k<w.length;k++){const S=w[k],I=[];for(let x=0;x<S.length;x++){const j=S[x],M=""+k+x;I.push(M),h[M]={node:j,lastCount:0},T[M]={};for(let D=0;D<b.length;D++){const A=b[D];h[A]&&h[A].node.mode===j.mode?(T[A][M]=p(h[A].lastCount+j.length,j.mode)-p(h[A].lastCount,j.mode),h[A].lastCount+=j.length):(h[A]&&(h[A].lastCount=j.length),T[A][M]=p(j.length,j.mode)+4+t.getCharCountIndicator(j.mode,_))}}b=I}for(let k=0;k<b.length;k++)T[b[k]].end=0;return{map:T,table:h}}function y(w,_){let h;const T=t.getBestModeForData(w);if(h=t.from(_,T),h!==t.BYTE&&h.bit<T.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(h)+`.
|
|
133
|
+
Suggested mode is: `+t.toString(T));switch(h===t.KANJI&&!a.isKanjiModeEnabled()&&(h=t.BYTE),h){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(_){return _.reduce(function(h,T){return typeof T=="string"?h.push(y(T,null)):T.data&&h.push(y(T.data,T.mode)),h},[])},e.fromString=function(_,h){const T=m(_,a.isKanjiModeEnabled()),b=g(T),k=v(b,h),S=l.find_path(k.map,"start","end"),I=[];for(let x=1;x<S.length-1;x++)I.push(k.table[S[x]].node);return e.fromArray(f(I))},e.rawSplit=function(_){return e.fromArray(m(_,a.isKanjiModeEnabled()))}})(Uu)),Uu}var Z_;function xE(){if(Z_)return Su;Z_=1;const e=zn(),t=xu(),r=dE(),n=pE(),o=fE(),s=hE(),i=mE(),a=x_(),l=_E(),c=vE(),u=wE(),m=Fn(),p=IE();function f(k,S){const I=k.size,x=s.getPositions(S);for(let j=0;j<x.length;j++){const M=x[j][0],D=x[j][1];for(let A=-1;A<=7;A++)if(!(M+A<=-1||I<=M+A))for(let O=-1;O<=7;O++)D+O<=-1||I<=D+O||(A>=0&&A<=6&&(O===0||O===6)||O>=0&&O<=6&&(A===0||A===6)||A>=2&&A<=4&&O>=2&&O<=4?k.set(M+A,D+O,!0,!0):k.set(M+A,D+O,!1,!0))}}function g(k){const S=k.size;for(let I=8;I<S-8;I++){const x=I%2===0;k.set(I,6,x,!0),k.set(6,I,x,!0)}}function v(k,S){const I=o.getPositions(S);for(let x=0;x<I.length;x++){const j=I[x][0],M=I[x][1];for(let D=-2;D<=2;D++)for(let A=-2;A<=2;A++)D===-2||D===2||A===-2||A===2||D===0&&A===0?k.set(j+D,M+A,!0,!0):k.set(j+D,M+A,!1,!0)}}function y(k,S){const I=k.size,x=c.getEncodedBits(S);let j,M,D;for(let A=0;A<18;A++)j=Math.floor(A/3),M=A%3+I-8-3,D=(x>>A&1)===1,k.set(j,M,D,!0),k.set(M,j,D,!0)}function w(k,S,I){const x=k.size,j=u.getEncodedBits(S,I);let M,D;for(M=0;M<15;M++)D=(j>>M&1)===1,M<6?k.set(M,8,D,!0):M<8?k.set(M+1,8,D,!0):k.set(x-15+M,8,D,!0),M<8?k.set(8,x-M-1,D,!0):M<9?k.set(8,15-M-1+1,D,!0):k.set(8,15-M-1,D,!0);k.set(x-8,8,1,!0)}function _(k,S){const I=k.size;let x=-1,j=I-1,M=7,D=0;for(let A=I-1;A>0;A-=2)for(A===6&&A--;;){for(let O=0;O<2;O++)if(!k.isReserved(j,A-O)){let H=!1;D<S.length&&(H=(S[D]>>>M&1)===1),k.set(j,A-O,H),M--,M===-1&&(D++,M=7)}if(j+=x,j<0||I<=j){j-=x,x=-x;break}}}function h(k,S,I){const x=new r;I.forEach(function(O){x.put(O.mode.bit,4),x.put(O.getLength(),m.getCharCountIndicator(O.mode,k)),O.write(x)});const j=e.getSymbolTotalCodewords(k),M=a.getTotalCodewordsCount(k,S),D=(j-M)*8;for(x.getLengthInBits()+4<=D&&x.put(0,4);x.getLengthInBits()%8!==0;)x.putBit(0);const A=(D-x.getLengthInBits())/8;for(let O=0;O<A;O++)x.put(O%2?17:236,8);return T(x,k,S)}function T(k,S,I){const x=e.getSymbolTotalCodewords(S),j=a.getTotalCodewordsCount(S,I),M=x-j,D=a.getBlocksCount(S,I),A=x%D,O=D-A,H=Math.floor(x/D),Q=Math.floor(M/D),Y=Q+1,W=H-Q,pe=new l(W);let Z=0;const P=new Array(D),B=new Array(D);let F=0;const E=new Uint8Array(k.buffer);for(let se=0;se<D;se++){const ke=se<O?Q:Y;P[se]=E.slice(Z,Z+ke),B[se]=pe.encode(P[se]),Z+=ke,F=Math.max(F,ke)}const N=new Uint8Array(x);let L=0,G,ee;for(G=0;G<F;G++)for(ee=0;ee<D;ee++)G<P[ee].length&&(N[L++]=P[ee][G]);for(G=0;G<W;G++)for(ee=0;ee<D;ee++)N[L++]=B[ee][G];return N}function b(k,S,I,x){let j;if(Array.isArray(k))j=p.fromArray(k);else if(typeof k=="string"){let H=S;if(!H){const Q=p.rawSplit(k);H=c.getBestVersionForData(Q,I)}j=p.fromString(k,H||40)}else throw new Error("Invalid data");const M=c.getBestVersionForData(j,I);if(!M)throw new Error("The amount of data is too big to be stored in a QR Code");if(!S)S=M;else if(S<M)throw new Error(`
|
|
134
134
|
The chosen QR Code version cannot contain this amount of data.
|
|
135
135
|
Minimum version required to store current data is: `+M+`.
|
|
136
|
-
`);const D=h(S,I,j),A=e.getSymbolSize(S),O=new n(A);return f(O,S),g(O),v(O,S),w(O,I,0),S>=7&&y(O,S),_(O,D),isNaN(x)&&(x=i.getBestMask(O,w.bind(null,O,I))),i.applyMask(x,O),w(O,I,x),{modules:O,version:S,errorCorrectionLevel:I,maskPattern:x,segments:j}}return Su.create=function(S,I){if(typeof S>"u"||S==="")throw new Error("No input text");let x=t.M,j,M;return typeof I<"u"&&(x=t.from(I.errorCorrectionLevel,t.M),j=c.from(I.version),M=i.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),b(S,j,x,M)},Su}var Bu={},Hu={},B_;function H_(){return B_||(B_=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const i=o.modules.size,a=o.modules.data,l=e.getScale(i,s),c=Math.floor((i+s.margin*2)*l),u=s.margin*l,m=[s.color.light,s.color.dark];for(let 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[a[y*i+w]?1:0]}n[g++]=v.r,n[g++]=v.g,n[g++]=v.b,n[g]=v.a}}})(Hu)),Hu}var J_;function
|
|
137
|
-
`;return typeof a=="function"&&a(null,y),y},Ju}var W_;function
|
|
136
|
+
`);const D=h(S,I,j),A=e.getSymbolSize(S),O=new n(A);return f(O,S),g(O),v(O,S),w(O,I,0),S>=7&&y(O,S),_(O,D),isNaN(x)&&(x=i.getBestMask(O,w.bind(null,O,I))),i.applyMask(x,O),w(O,I,x),{modules:O,version:S,errorCorrectionLevel:I,maskPattern:x,segments:j}}return Su.create=function(S,I){if(typeof S>"u"||S==="")throw new Error("No input text");let x=t.M,j,M;return typeof I<"u"&&(x=t.from(I.errorCorrectionLevel,t.M),j=c.from(I.version),M=i.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),b(S,j,x,M)},Su}var Bu={},Hu={},B_;function H_(){return B_||(B_=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,i=n.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const i=o.modules.size,a=o.modules.data,l=e.getScale(i,s),c=Math.floor((i+s.margin*2)*l),u=s.margin*l,m=[s.color.light,s.color.dark];for(let 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[a[y*i+w]?1:0]}n[g++]=v.r,n[g++]=v.g,n[g++]=v.b,n[g]=v.a}}})(Hu)),Hu}var J_;function EE(){return J_||(J_=1,(function(e){const t=H_();function r(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,i,a){let l=a,c=i;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),i||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),m=c.getContext("2d"),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,i,a){let l=a;typeof l>"u"&&(!i||!i.getContext)&&(l=i,i=void 0),l||(l={});const c=e.render(s,i,l),u=l.type||"image/png",m=l.rendererOpts||{};return c.toDataURL(u,m.quality)}})(Bu)),Bu}var Ju={},G_;function $E(){if(G_)return Ju;G_=1;const e=H_();function t(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function r(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function n(o,s,i){let a="",l=0,c=!1,u=0;for(let m=0;m<o.length;m++){const p=Math.floor(m%s),f=Math.floor(m/s);!p&&!c&&(c=!0),o[m]?(u++,m>0&&p>0&&o[m-1]||(a+=c?r("M",p+i,.5+f+i):r("m",l,0),l=0,c=!1),p+1<s&&o[m+1]||(a+=r("h",u),u=0)):l++}return a}return Ju.render=function(s,i,a){const l=e.getOptions(i),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>
|
|
137
|
+
`;return typeof a=="function"&&a(null,y),y},Ju}var W_;function RE(){if(W_)return vo;W_=1;const e=uE(),t=xE(),r=EE(),n=$E();function o(s,i,a,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=a,a=i,i=l=void 0):m===3&&(i.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=a,a=i,i=void 0))}else{if(m<1)throw new Error("Too few arguments provided");return m===1?(a=i,i=l=void 0):m===2&&!i.getContext&&(l=a,a=i,i=void 0),new Promise(function(f,g){try{const v=t.create(a,l);f(s(v,i,l))}catch(v){g(v)}})}try{const f=t.create(a,l);c(null,s(f,i,l))}catch(f){c(f)}}return vo.create=t.create,vo.toCanvas=o.bind(null,r.render),vo.toDataURL=o.bind(null,r.renderToDataURL),vo.toString=o.bind(null,function(s,i,a){return n.render(s,a)}),vo}var PE=RE();const K_=bl(PE);class Y_{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 K_.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return K_.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const NE={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={...NE,...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=`
|
|
138
138
|
<div class="${this.opts.className}__arrow"></div>
|
|
139
139
|
<div class="${this.opts.className}__inner">${t}</div>
|
|
140
140
|
`}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 Q_="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(Q_))return;const e=document.createElement("style");e.id=Q_,e.textContent=`
|
|
@@ -184,7 +184,7 @@ Minimum version required to store current data is: `+M+`.
|
|
|
184
184
|
transform: translateY(-50%);
|
|
185
185
|
border-right-color: rgba(0,0,0,.75);
|
|
186
186
|
}
|
|
187
|
-
`,document.head.appendChild(e)})();const PE="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",NE="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",ME="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",OE="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",AE="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",qE="https://chat.opentiny.design",LE="https://ai.opentiny.design/next-remoter",jE="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",X_=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:OE},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:PE},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:ME},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:NE}]};class UE{constructor(t){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 RE(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||LE,remoteUrl:t.remoteUrl||qE,logoUrl:t.logoUrl||jE},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 this.options.sessionId?t?X_(this.options).map(r=>{const n=t.find(o=>o.action===r.action);return n?{...r,...n,show:n.show!==void 0?n.show:r.show}:r}):X_(this.options):[]}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
|
|
187
|
+
`,document.head.appendChild(e)})();const X_="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",ev="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",tv="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",rv="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",OE="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",AE="https://chat.opentiny.design",qE="https://ai.opentiny.design/next-remoter",LE="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",jE=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:rv},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:X_},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:tv},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:ev}]};class UE{constructor(t){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"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||qE,remoteUrl:t.remoteUrl||AE,logoUrl:t.logoUrl||LE},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){const r={"qr-code":rv,"ai-chat":X_,"remote-url":tv,"remote-control":ev};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?jE(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=`
|
|
188
188
|
<div class="tiny-remoter-floating-block__icon">
|
|
189
189
|
<img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
|
|
190
190
|
</div>
|
|
@@ -195,18 +195,18 @@ Minimum version required to store current data is: `+M+`.
|
|
|
195
195
|
<div class="tiny-remoter-dropdown-item__content">
|
|
196
196
|
<div title="${r.tip}">${r.text}</div>
|
|
197
197
|
<div class="tiny-remoter-dropdown-item__desc-wrapper">
|
|
198
|
-
<div class="tiny-remoter-dropdown-item__desc ${r.active?"tiny-remoter-dropdown-item__desc--active":""} ${r.know?"tiny-remoter-dropdown-item__desc--know":""}">${r.desc}</div>
|
|
198
|
+
<div class="tiny-remoter-dropdown-item__desc ${r.active?"tiny-remoter-dropdown-item__desc--active":""} ${r.know?"tiny-remoter-dropdown-item__desc--know":""}">${r.desc??""}</div>
|
|
199
199
|
<div>
|
|
200
200
|
${r.showCopyIcon?`
|
|
201
201
|
<div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
|
|
202
|
-
<img src="${
|
|
202
|
+
<img src="${OE}"/>
|
|
203
203
|
</div>
|
|
204
204
|
`:""}
|
|
205
205
|
</div>
|
|
206
206
|
</div>
|
|
207
207
|
</div>
|
|
208
208
|
</div>
|
|
209
|
-
`).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.
|
|
209
|
+
`).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(){const t=this.menuItems.find(n=>n.action==="remote-control"),r=t?.desc||t?.text||(this.options.sessionId?this.options.sessionId.slice(-6):"");r&&this.copyToClipboard(r)}copyRemoteURL(){const t=this.menuItems.find(s=>s.action==="remote-url"),r=this.options.sessionId?this.options.remoteUrl+this.sessionPrefix+this.options.sessionId:"",o=(t?.desc&&t.desc!==this.options.remoteUrl?t.desc:void 0)||r||t?.text||"";o&&this.copyToClipboard(o)}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(){if(!this.options.sessionId)return;const r=await new Y_((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
|
|
210
210
|
<div style="text-align: center; padding: 32px;">
|
|
211
211
|
<!-- 二维码容器 - 添加渐变背景和阴影效果 -->
|
|
212
212
|
<div style="
|
|
@@ -632,4 +632,4 @@ Minimum version required to store current data is: `+M+`.
|
|
|
632
632
|
color: white;
|
|
633
633
|
}
|
|
634
634
|
}
|
|
635
|
-
`,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const DE=(e={})=>new UE(e);Mr.AgentModelProvider=
|
|
635
|
+
`,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const DE=(e={})=>new UE(e);Mr.AgentModelProvider=cE,Mr.QrCode=Y_,Mr.createRemoter=DE,Mr.getAISDKTools=g_,Object.defineProperty(Mr,Symbol.toStringTag,{value:"Module"})}));
|