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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,13 +1,13 @@
1
- (function(Pe,tn){typeof exports=="object"&&typeof module<"u"?tn(exports):typeof define=="function"&&define.amd?define(["exports"],tn):(Pe=typeof globalThis<"u"?globalThis:Pe||self,tn(Pe.WebMCP={}))})(this,(function(Pe){"use strict";function tn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $o={exports:{}},Ni={},yr={},rn={},Li={},ji={},qi={},id;function Eo(){return id||(id=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(_){if(super(),!t.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}}}t.Name=r;class n extends e{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((g,b)=>`${g}${b}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((g,b)=>(b instanceof r&&(g[b.str]=(g[b.str]||0)+1),g),{})}}t._Code=n,t.nil=new n("");function s(y,..._){const g=[y[0]];let b=0;for(;b<_.length;)i(g,_[b]),g.push(y[++b]);return new n(g)}t._=s;const o=new n("+");function a(y,..._){const g=[d(y[0])];let b=0;for(;b<_.length;)g.push(o),i(g,_[b]),g.push(o,d(y[++b]));return l(g),new n(g)}t.str=a;function i(y,_){_ instanceof n?y.push(..._._items):_ instanceof r?y.push(_):y.push(p(_))}t.addCodeArg=i;function l(y){let _=1;for(;_<y.length-1;){if(y[_]===o){const g=c(y[_-1],y[_+1]);if(g!==void 0){y.splice(_-1,3,g);continue}y[_++]="+"}_++}}function c(y,_){if(_==='""')return y;if(y==='""')return _;if(typeof y=="string")return _ instanceof r||y[y.length-1]!=='"'?void 0:typeof _!="string"?`${y.slice(0,-1)}${_}"`:_[0]==='"'?y.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(y instanceof r))return`"${y}${_.slice(1)}`}function u(y,_){return _.emptyStr()?y:y.emptyStr()?_:a`${y}${_}`}t.strConcat=u;function p(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:d(Array.isArray(y)?y.join(","):y)}function h(y){return new n(d(y))}t.stringify=h;function d(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=d;function f(y){return typeof y=="string"&&t.IDENTIFIER.test(y)?new n(`.${y}`):s`[${y}]`}t.getProperty=f;function w(y){if(typeof y=="string"&&t.IDENTIFIER.test(y))return new n(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}t.getEsmExportName=w;function m(y){return new n(y.toString())}t.regexpCode=m})(qi)),qi}var zi={},ld;function cd(){return ld||(ld=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=Eo();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||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class s{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof e.Name?c:this.name(c)}name(c){return new e.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,p;if(!((p=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||p===void 0)&&p.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}}}t.Scope=s;class o extends e.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:p}){this.value=c,this.scopePath=(0,e._)`.${new e.Name(u)}[${p}]`}}t.ValueScopeName=o;const a=(0,e._)`\n`;class i extends s{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:e.nil}}get(){return this._scope}name(c){return new o(c,this._newName(c))}value(c,u){var p;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const h=this.toName(c),{prefix:d}=h,f=(p=u.key)!==null&&p!==void 0?p:u.ref;let w=this._values[d];if(w){const _=w.get(f);if(_)return _}else w=this._values[d]=new Map;w.set(f,h);const m=this._scope[d]||(this._scope[d]=[]),y=m.length;return m[y]=u.ref,h.setValue(u,{property:d,itemIndex:y}),h}getValue(c,u){const p=this._values[c];if(p)return p.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,p=>{if(p.scopePath===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return(0,e._)`${c}${p.scopePath}`})}scopeCode(c=this._values,u,p){return this._reduceValues(c,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},u,p)}_reduceValues(c,u,p={},h){let d=e.nil;for(const f in c){const w=c[f];if(!w)continue;const m=p[f]=p[f]||new Map;w.forEach(y=>{if(m.has(y))return;m.set(y,n.Started);let _=u(y);if(_){const g=this.opts.es5?t.varKinds.var:t.varKinds.const;d=(0,e._)`${d}${g} ${y} = ${_};${this.opts._n}`}else if(_=h?.(y))d=(0,e._)`${d}${_}${this.opts._n}`;else throw new r(y);m.set(y,n.Completed)})}return d}}t.ValueScope=i})(zi)),zi}var ud;function $e(){return ud||(ud=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=Eo(),r=cd();var n=Eo();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var s=cd();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class o{optimizeNodes(){return this}optimizeNames(E,R){return this}}class a extends o{constructor(E,R,$){super(),this.varKind=E,this.name=R,this.rhs=$}render({es5:E,_n:R}){const $=E?r.varKinds.var:this.varKind,B=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${B};`+R}optimizeNames(E,R){if(E[this.name.str])return this.rhs&&(this.rhs=V(this.rhs,E,R)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends o{constructor(E,R,$){super(),this.lhs=E,this.rhs=R,this.sideEffects=$}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,R){if(!(this.lhs instanceof e.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=V(this.rhs,E,R),this}get names(){const E=this.lhs instanceof e.Name?{}:{...this.lhs.names};return U(E,this.rhs)}}class l extends i{constructor(E,R,$,B){super(E,$,B),this.op=R}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class p extends o{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class h extends o{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,R){return this.code=V(this.code,E,R),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class d extends o{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((R,$)=>R+$.render(E),"")}optimizeNodes(){const{nodes:E}=this;let R=E.length;for(;R--;){const $=E[R].optimizeNodes();Array.isArray($)?E.splice(R,1,...$):$?E[R]=$:E.splice(R,1)}return E.length>0?this:void 0}optimizeNames(E,R){const{nodes:$}=this;let B=$.length;for(;B--;){const W=$[B];W.optimizeNames(E,R)||(se(E,W.names),$.splice(B,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((E,R)=>D(E,R.names),{})}}class f extends d{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class w extends d{}class m extends f{}m.kind="else";class y extends f{constructor(E,R){super(R),this.condition=E}render(E){let R=`if(${this.condition})`+super.render(E);return this.else&&(R+="else "+this.else.render(E)),R}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let R=this.else;if(R){const $=R.optimizeNodes();R=this.else=Array.isArray($)?new m($):$}if(R)return E===!1?R instanceof y?R:R.nodes:this.nodes.length?this:new y(fe(E),R instanceof y?[R]:R.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,R){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(E,R),!!(super.optimizeNames(E,R)||this.else))return this.condition=V(this.condition,E,R),this}get names(){const E=super.names;return U(E,this.condition),this.else&&D(E,this.else.names),E}}y.kind="if";class _ extends f{}_.kind="for";class g extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iteration=V(this.iteration,E,R),this}get names(){return D(super.names,this.iteration.names)}}class b extends _{constructor(E,R,$,B){super(),this.varKind=E,this.name=R,this.from=$,this.to=B}render(E){const R=E.es5?r.varKinds.var:this.varKind,{name:$,from:B,to:W}=this;return`for(${R} ${$}=${B}; ${$}<${W}; ${$}++)`+super.render(E)}get names(){const E=U(super.names,this.from);return U(E,this.to)}}class k extends _{constructor(E,R,$,B){super(),this.loop=E,this.varKind=R,this.name=$,this.iterable=B}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iterable=V(this.iterable,E,R),this}get names(){return D(super.names,this.iterable.names)}}class S extends f{constructor(E,R,$){super(),this.name=E,this.args=R,this.async=$}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}S.kind="func";class T extends d{render(E){return"return "+super.render(E)}}T.kind="return";class x extends f{render(E){let R="try"+super.render(E);return this.catch&&(R+=this.catch.render(E)),this.finally&&(R+=this.finally.render(E)),R}optimizeNodes(){var E,R;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(E,R){var $,B;return super.optimizeNames(E,R),($=this.catch)===null||$===void 0||$.optimizeNames(E,R),(B=this.finally)===null||B===void 0||B.optimizeNames(E,R),this}get names(){const E=super.names;return this.catch&&D(E,this.catch.names),this.finally&&D(E,this.finally.names),E}}class I extends f{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}I.kind="catch";class A extends f{render(E){return"finally"+super.render(E)}}A.kind="finally";class P{constructor(E,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
2
- `:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,R){const $=this._extScope.value(E,R);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(E,R){return this._extScope.getValue(E,R)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,R,$,B){const W=this._scope.toName(R);return $!==void 0&&B&&(this._constants[W.str]=$),this._leafNode(new a(E,W,$)),W}const(E,R,$){return this._def(r.varKinds.const,E,R,$)}let(E,R,$){return this._def(r.varKinds.let,E,R,$)}var(E,R,$){return this._def(r.varKinds.var,E,R,$)}assign(E,R,$){return this._leafNode(new i(E,R,$))}add(E,R){return this._leafNode(new l(E,t.operators.ADD,R))}code(E){return typeof E=="function"?E():E!==e.nil&&this._leafNode(new h(E)),this}object(...E){const R=["{"];for(const[$,B]of E)R.length>1&&R.push(","),R.push($),($!==B||this.opts.es5)&&(R.push(":"),(0,e.addCodeArg)(R,B));return R.push("}"),new e._Code(R)}if(E,R,$){if(this._blockNode(new y(E)),R&&$)this.code(R).else().code($).endIf();else if(R)this.code(R).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new y(E))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(y,m)}_for(E,R){return this._blockNode(E),R&&this.code(R).endFor(),this}for(E,R){return this._for(new g(E),R)}forRange(E,R,$,B,W=this.opts.es5?r.varKinds.var:r.varKinds.let){const ye=this._scope.toName(E);return this._for(new b(W,ye,R,$),()=>B(ye))}forOf(E,R,$,B=r.varKinds.const){const W=this._scope.toName(E);if(this.opts.es5){const ye=R instanceof e.Name?R:this.var("_arr",R);return this.forRange("_i",0,(0,e._)`${ye}.length`,pe=>{this.var(W,(0,e._)`${ye}[${pe}]`),$(W)})}return this._for(new k("of",B,W,R),()=>$(W))}forIn(E,R,$,B=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,e._)`Object.keys(${R})`,$);const W=this._scope.toName(E);return this._for(new k("in",B,W,R),()=>$(W))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const R=new T;if(this._blockNode(R),this.code(E),R.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(E,R,$){if(!R&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const B=new x;if(this._blockNode(B),this.code(E),R){const W=this.name("e");this._currNode=B.catch=new I(W),R(W)}return $&&(this._currNode=B.finally=new A,this.code($)),this._endBlockNode(I,A)}throw(E){return this._leafNode(new p(E))}block(E,R){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(R),this}endBlock(E){const R=this._blockStarts.pop();if(R===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-R;if($<0||E!==void 0&&$!==E)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${E} expected`);return this._nodes.length=R,this}func(E,R=e.nil,$,B){return this._blockNode(new S(E,R,$)),B&&this.code(B).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,R){const $=this._currNode;if($ instanceof E||R&&$ instanceof R)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${R?`${E.kind}/${R.kind}`:E.kind}"`)}_elseNode(E){const R=this._currNode;if(!(R instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=R.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const R=this._nodes;R[R.length-1]=E}}t.CodeGen=P;function D(q,E){for(const R in E)q[R]=(q[R]||0)+(E[R]||0);return q}function U(q,E){return E instanceof e._CodeOrName?D(q,E.names):q}function V(q,E,R){if(q instanceof e.Name)return $(q);if(!B(q))return q;return new e._Code(q._items.reduce((W,ye)=>(ye instanceof e.Name&&(ye=$(ye)),ye instanceof e._Code?W.push(...ye._items):W.push(ye),W),[]));function $(W){const ye=R[W.str];return ye===void 0||E[W.str]!==1?W:(delete E[W.str],ye)}function B(W){return W instanceof e._Code&&W._items.some(ye=>ye instanceof e.Name&&E[ye.str]===1&&R[ye.str]!==void 0)}}function se(q,E){for(const R in E)q[R]=(q[R]||0)-(E[R]||0)}function fe(q){return typeof q=="boolean"||typeof q=="number"||q===null?!q:(0,e._)`!${F(q)}`}t.not=fe;const de=O(t.operators.AND);function re(...q){return q.reduce(de)}t.and=re;const _e=O(t.operators.OR);function H(...q){return q.reduce(_e)}t.or=H;function O(q){return(E,R)=>E===e.nil?R:R===e.nil?E:(0,e._)`${F(E)} ${q} ${F(R)}`}function F(q){return q instanceof e.Name?q:(0,e._)`(${q})`}})(ji)),ji}var Ee={},dd;function Oe(){if(dd)return Ee;dd=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.checkStrictMode=Ee.getErrorPath=Ee.Type=Ee.useFunc=Ee.setEvaluated=Ee.evaluatedPropsToName=Ee.mergeEvaluated=Ee.eachItem=Ee.unescapeJsonPointer=Ee.escapeJsonPointer=Ee.escapeFragment=Ee.unescapeFragment=Ee.schemaRefOrVal=Ee.schemaHasRulesButRef=Ee.schemaHasRules=Ee.checkUnknownRules=Ee.alwaysValidSchema=Ee.toHash=void 0;const t=$e(),e=Eo();function r(k){const S={};for(const T of k)S[T]=!0;return S}Ee.toHash=r;function n(k,S){return typeof S=="boolean"?S:Object.keys(S).length===0?!0:(s(k,S),!o(S,k.self.RULES.all))}Ee.alwaysValidSchema=n;function s(k,S=k.schema){const{opts:T,self:x}=k;if(!T.strictSchema||typeof S=="boolean")return;const I=x.RULES.keywords;for(const A in S)I[A]||b(k,`unknown keyword: "${A}"`)}Ee.checkUnknownRules=s;function o(k,S){if(typeof k=="boolean")return!k;for(const T in k)if(S[T])return!0;return!1}Ee.schemaHasRules=o;function a(k,S){if(typeof k=="boolean")return!k;for(const T in k)if(T!=="$ref"&&S.all[T])return!0;return!1}Ee.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:S},T,x,I){if(!I){if(typeof T=="number"||typeof T=="boolean")return T;if(typeof T=="string")return(0,t._)`${T}`}return(0,t._)`${k}${S}${(0,t.getProperty)(x)}`}Ee.schemaRefOrVal=i;function l(k){return p(decodeURIComponent(k))}Ee.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}Ee.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}Ee.escapeJsonPointer=u;function p(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}Ee.unescapeJsonPointer=p;function h(k,S){if(Array.isArray(k))for(const T of k)S(T);else S(k)}Ee.eachItem=h;function d({mergeNames:k,mergeToName:S,mergeValues:T,resultToName:x}){return(I,A,P,D)=>{const U=P===void 0?A:P instanceof t.Name?(A instanceof t.Name?k(I,A,P):S(I,A,P),P):A instanceof t.Name?(S(I,P,A),A):T(A,P);return D===t.Name&&!(U instanceof t.Name)?x(I,U):U}}Ee.mergeEvaluated={props:d({mergeNames:(k,S,T)=>k.if((0,t._)`${T} !== true && ${S} !== undefined`,()=>{k.if((0,t._)`${S} === true`,()=>k.assign(T,!0),()=>k.assign(T,(0,t._)`${T} || {}`).code((0,t._)`Object.assign(${T}, ${S})`))}),mergeToName:(k,S,T)=>k.if((0,t._)`${T} !== true`,()=>{S===!0?k.assign(T,!0):(k.assign(T,(0,t._)`${T} || {}`),w(k,T,S))}),mergeValues:(k,S)=>k===!0?!0:{...k,...S},resultToName:f}),items:d({mergeNames:(k,S,T)=>k.if((0,t._)`${T} !== true && ${S} !== undefined`,()=>k.assign(T,(0,t._)`${S} === true ? true : ${T} > ${S} ? ${T} : ${S}`)),mergeToName:(k,S,T)=>k.if((0,t._)`${T} !== true`,()=>k.assign(T,S===!0?!0:(0,t._)`${T} > ${S} ? ${T} : ${S}`)),mergeValues:(k,S)=>k===!0?!0:Math.max(k,S),resultToName:(k,S)=>k.var("items",S)})};function f(k,S){if(S===!0)return k.var("props",!0);const T=k.var("props",(0,t._)`{}`);return S!==void 0&&w(k,T,S),T}Ee.evaluatedPropsToName=f;function w(k,S,T){Object.keys(T).forEach(x=>k.assign((0,t._)`${S}${(0,t.getProperty)(x)}`,!0))}Ee.setEvaluated=w;const m={};function y(k,S){return k.scopeValue("func",{ref:S,code:m[S.code]||(m[S.code]=new e._Code(S.code))})}Ee.useFunc=y;var _;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(_||(Ee.Type=_={}));function g(k,S,T){if(k instanceof t.Name){const x=S===_.Num;return T?x?(0,t._)`"[" + ${k} + "]"`:(0,t._)`"['" + ${k} + "']"`:x?(0,t._)`"/" + ${k}`:(0,t._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return T?(0,t.getProperty)(k).toString():"/"+u(k)}Ee.getErrorPath=g;function b(k,S,T=k.opts.strictSchema){if(T){if(S=`strict mode: ${S}`,T===!0)throw new Error(S);k.self.logger.warn(S)}}return Ee.checkStrictMode=b,Ee}var xo={},pd;function Nr(){if(pd)return xo;pd=1,Object.defineProperty(xo,"__esModule",{value:!0});const t=$e(),e={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};return xo.default=e,xo}var fd;function Io(){return fd||(fd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=$e(),r=Oe(),n=Nr();t.keywordError={message:({keyword:m})=>(0,e.str)`must pass "${m}" keyword validation`},t.keyword$DataError={message:({keyword:m,schemaType:y})=>y?(0,e.str)`"${m}" keyword must be ${y} ($data)`:(0,e.str)`"${m}" keyword is invalid ($data)`};function s(m,y=t.keywordError,_,g){const{it:b}=m,{gen:k,compositeRule:S,allErrors:T}=b,x=p(m,y,_);g??(S||T)?l(k,x):c(b,(0,e._)`[${x}]`)}t.reportError=s;function o(m,y=t.keywordError,_){const{it:g}=m,{gen:b,compositeRule:k,allErrors:S}=g,T=p(m,y,_);l(b,T),k||S||c(g,n.default.vErrors)}t.reportExtraError=o;function a(m,y){m.assign(n.default.errors,y),m.if((0,e._)`${n.default.vErrors} !== null`,()=>m.if(y,()=>m.assign((0,e._)`${n.default.vErrors}.length`,y),()=>m.assign(n.default.vErrors,null)))}t.resetErrorsCount=a;function i({gen:m,keyword:y,schemaValue:_,data:g,errsCount:b,it:k}){if(b===void 0)throw new Error("ajv implementation error");const S=m.name("err");m.forRange("i",b,n.default.errors,T=>{m.const(S,(0,e._)`${n.default.vErrors}[${T}]`),m.if((0,e._)`${S}.instancePath === undefined`,()=>m.assign((0,e._)`${S}.instancePath`,(0,e.strConcat)(n.default.instancePath,k.errorPath))),m.assign((0,e._)`${S}.schemaPath`,(0,e.str)`${k.errSchemaPath}/${y}`),k.opts.verbose&&(m.assign((0,e._)`${S}.schema`,_),m.assign((0,e._)`${S}.data`,g))})}t.extendErrors=i;function l(m,y){const _=m.const("err",y);m.if((0,e._)`${n.default.vErrors} === null`,()=>m.assign(n.default.vErrors,(0,e._)`[${_}]`),(0,e._)`${n.default.vErrors}.push(${_})`),m.code((0,e._)`${n.default.errors}++`)}function c(m,y){const{gen:_,validateName:g,schemaEnv:b}=m;b.$async?_.throw((0,e._)`new ${m.ValidationError}(${y})`):(_.assign((0,e._)`${g}.errors`,y),_.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function p(m,y,_){const{createErrors:g}=m.it;return g===!1?(0,e._)`{}`:h(m,y,_)}function h(m,y,_={}){const{gen:g,it:b}=m,k=[d(b,_),f(m,_)];return w(m,y,k),g.object(...k)}function d({errorPath:m},{instancePath:y}){const _=y?(0,e.str)`${m}${(0,r.getErrorPath)(y,r.Type.Str)}`:m;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,_)]}function f({keyword:m,it:{errSchemaPath:y}},{schemaPath:_,parentSchema:g}){let b=g?y:(0,e.str)`${y}/${m}`;return _&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,b]}function w(m,{params:y,message:_},g){const{keyword:b,data:k,schemaValue:S,it:T}=m,{opts:x,propertyName:I,topSchemaRef:A,schemaPath:P}=T;g.push([u.keyword,b],[u.params,typeof y=="function"?y(m):y||(0,e._)`{}`]),x.messages&&g.push([u.message,typeof _=="function"?_(m):_]),x.verbose&&g.push([u.schema,S],[u.parentSchema,(0,e._)`${A}${P}`],[n.default.data,k]),I&&g.push([u.propertyName,I])}})(Li)),Li}var hd;function S_(){if(hd)return rn;hd=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.boolOrEmptySchema=rn.topBoolOrEmptySchema=void 0;const t=Io(),e=$e(),r=Nr(),n={message:"boolean schema is false"};function s(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,e._)`${u}.errors`,null),l.return(!0))}rn.topBoolOrEmptySchema=s;function o(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}rn.boolOrEmptySchema=o;function a(i,l){const{gen:c,data:u}=i,p={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,t.reportError)(p,n,void 0,l)}return rn}var st={},nn={},md;function gd(){if(md)return nn;md=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.getRules=nn.isJSONType=void 0;const t=["string","number","integer","boolean","null","object","array"],e=new Set(t);function r(s){return typeof s=="string"&&e.has(s)}nn.isJSONType=r;function n(){const s={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...s,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},s.number,s.string,s.array,s.object],post:{rules:[]},all:{},keywords:{}}}return nn.getRules=n,nn}var wr={},vd;function _d(){if(vd)return wr;vd=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.shouldUseRule=wr.shouldUseGroup=wr.schemaHasRulesForType=void 0;function t({schema:n,self:s},o){const a=s.RULES.types[o];return a&&a!==!0&&e(n,a)}wr.schemaHasRulesForType=t;function e(n,s){return s.rules.some(o=>r(n,o))}wr.shouldUseGroup=e;function r(n,s){var o;return n[s.keyword]!==void 0||((o=s.definition.implements)===null||o===void 0?void 0:o.some(a=>n[a]!==void 0))}return wr.shouldUseRule=r,wr}var yd;function Ro(){if(yd)return st;yd=1,Object.defineProperty(st,"__esModule",{value:!0}),st.reportTypeError=st.checkDataTypes=st.checkDataType=st.coerceAndCheckDataType=st.getJSONTypes=st.getSchemaTypes=st.DataType=void 0;const t=gd(),e=_d(),r=Io(),n=$e(),s=Oe();var o;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(o||(st.DataType=o={}));function a(_){const g=i(_.type);if(g.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!g.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&g.push("null")}return g}st.getSchemaTypes=a;function i(_){const g=Array.isArray(_)?_:_?[_]:[];if(g.every(t.isJSONType))return g;throw new Error("type must be JSONType or JSONType[]: "+g.join(","))}st.getJSONTypes=i;function l(_,g){const{gen:b,data:k,opts:S}=_,T=u(g,S.coerceTypes),x=g.length>0&&!(T.length===0&&g.length===1&&(0,e.schemaHasRulesForType)(_,g[0]));if(x){const I=f(g,k,S.strictNumbers,o.Wrong);b.if(I,()=>{T.length?p(_,g,T):m(_)})}return x}st.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,g){return g?_.filter(b=>c.has(b)||g==="array"&&b==="array"):[]}function p(_,g,b){const{gen:k,data:S,opts:T}=_,x=k.let("dataType",(0,n._)`typeof ${S}`),I=k.let("coerced",(0,n._)`undefined`);T.coerceTypes==="array"&&k.if((0,n._)`${x} == 'object' && Array.isArray(${S}) && ${S}.length == 1`,()=>k.assign(S,(0,n._)`${S}[0]`).assign(x,(0,n._)`typeof ${S}`).if(f(g,S,T.strictNumbers),()=>k.assign(I,S))),k.if((0,n._)`${I} !== undefined`);for(const P of b)(c.has(P)||P==="array"&&T.coerceTypes==="array")&&A(P);k.else(),m(_),k.endIf(),k.if((0,n._)`${I} !== undefined`,()=>{k.assign(S,I),h(_,I)});function A(P){switch(P){case"string":k.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(I,(0,n._)`"" + ${S}`).elseIf((0,n._)`${S} === null`).assign(I,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${x} == "boolean" || ${S} === null
1
+ (function(Pe,tn){typeof exports=="object"&&typeof module<"u"?tn(exports):typeof define=="function"&&define.amd?define(["exports"],tn):(Pe=typeof globalThis<"u"?globalThis:Pe||self,tn(Pe.WebMCP={}))})(this,(function(Pe){"use strict";function tn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $o={exports:{}},Ni={},yr={},rn={},Li={},ji={},qi={},ad;function Eo(){return ad||(ad=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(_){if(super(),!t.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}}}t.Name=r;class n extends e{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((g,b)=>`${g}${b}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((g,b)=>(b instanceof r&&(g[b.str]=(g[b.str]||0)+1),g),{})}}t._Code=n,t.nil=new n("");function s(y,..._){const g=[y[0]];let b=0;for(;b<_.length;)i(g,_[b]),g.push(y[++b]);return new n(g)}t._=s;const o=new n("+");function a(y,..._){const g=[d(y[0])];let b=0;for(;b<_.length;)g.push(o),i(g,_[b]),g.push(o,d(y[++b]));return l(g),new n(g)}t.str=a;function i(y,_){_ instanceof n?y.push(..._._items):_ instanceof r?y.push(_):y.push(p(_))}t.addCodeArg=i;function l(y){let _=1;for(;_<y.length-1;){if(y[_]===o){const g=c(y[_-1],y[_+1]);if(g!==void 0){y.splice(_-1,3,g);continue}y[_++]="+"}_++}}function c(y,_){if(_==='""')return y;if(y==='""')return _;if(typeof y=="string")return _ instanceof r||y[y.length-1]!=='"'?void 0:typeof _!="string"?`${y.slice(0,-1)}${_}"`:_[0]==='"'?y.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(y instanceof r))return`"${y}${_.slice(1)}`}function u(y,_){return _.emptyStr()?y:y.emptyStr()?_:a`${y}${_}`}t.strConcat=u;function p(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:d(Array.isArray(y)?y.join(","):y)}function h(y){return new n(d(y))}t.stringify=h;function d(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=d;function f(y){return typeof y=="string"&&t.IDENTIFIER.test(y)?new n(`.${y}`):s`[${y}]`}t.getProperty=f;function w(y){if(typeof y=="string"&&t.IDENTIFIER.test(y))return new n(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}t.getEsmExportName=w;function m(y){return new n(y.toString())}t.regexpCode=m})(qi)),qi}var zi={},id;function ld(){return id||(id=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=Eo();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||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class s{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof e.Name?c:this.name(c)}name(c){return new e.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,p;if(!((p=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||p===void 0)&&p.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}}}t.Scope=s;class o extends e.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:p}){this.value=c,this.scopePath=(0,e._)`.${new e.Name(u)}[${p}]`}}t.ValueScopeName=o;const a=(0,e._)`\n`;class i extends s{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:e.nil}}get(){return this._scope}name(c){return new o(c,this._newName(c))}value(c,u){var p;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const h=this.toName(c),{prefix:d}=h,f=(p=u.key)!==null&&p!==void 0?p:u.ref;let w=this._values[d];if(w){const _=w.get(f);if(_)return _}else w=this._values[d]=new Map;w.set(f,h);const m=this._scope[d]||(this._scope[d]=[]),y=m.length;return m[y]=u.ref,h.setValue(u,{property:d,itemIndex:y}),h}getValue(c,u){const p=this._values[c];if(p)return p.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,p=>{if(p.scopePath===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return(0,e._)`${c}${p.scopePath}`})}scopeCode(c=this._values,u,p){return this._reduceValues(c,h=>{if(h.value===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return h.value.code},u,p)}_reduceValues(c,u,p={},h){let d=e.nil;for(const f in c){const w=c[f];if(!w)continue;const m=p[f]=p[f]||new Map;w.forEach(y=>{if(m.has(y))return;m.set(y,n.Started);let _=u(y);if(_){const g=this.opts.es5?t.varKinds.var:t.varKinds.const;d=(0,e._)`${d}${g} ${y} = ${_};${this.opts._n}`}else if(_=h?.(y))d=(0,e._)`${d}${_}${this.opts._n}`;else throw new r(y);m.set(y,n.Completed)})}return d}}t.ValueScope=i})(zi)),zi}var cd;function $e(){return cd||(cd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=Eo(),r=ld();var n=Eo();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var s=ld();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class o{optimizeNodes(){return this}optimizeNames(E,R){return this}}class a extends o{constructor(E,R,$){super(),this.varKind=E,this.name=R,this.rhs=$}render({es5:E,_n:R}){const $=E?r.varKinds.var:this.varKind,B=this.rhs===void 0?"":` = ${this.rhs}`;return`${$} ${this.name}${B};`+R}optimizeNames(E,R){if(E[this.name.str])return this.rhs&&(this.rhs=V(this.rhs,E,R)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends o{constructor(E,R,$){super(),this.lhs=E,this.rhs=R,this.sideEffects=$}render({_n:E}){return`${this.lhs} = ${this.rhs};`+E}optimizeNames(E,R){if(!(this.lhs instanceof e.Name&&!E[this.lhs.str]&&!this.sideEffects))return this.rhs=V(this.rhs,E,R),this}get names(){const E=this.lhs instanceof e.Name?{}:{...this.lhs.names};return U(E,this.rhs)}}class l extends i{constructor(E,R,$,B){super(E,$,B),this.op=R}render({_n:E}){return`${this.lhs} ${this.op}= ${this.rhs};`+E}}class c extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`${this.label}:`+E}}class u extends o{constructor(E){super(),this.label=E,this.names={}}render({_n:E}){return`break${this.label?` ${this.label}`:""};`+E}}class p extends o{constructor(E){super(),this.error=E}render({_n:E}){return`throw ${this.error};`+E}get names(){return this.error.names}}class h extends o{constructor(E){super(),this.code=E}render({_n:E}){return`${this.code};`+E}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(E,R){return this.code=V(this.code,E,R),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class d extends o{constructor(E=[]){super(),this.nodes=E}render(E){return this.nodes.reduce((R,$)=>R+$.render(E),"")}optimizeNodes(){const{nodes:E}=this;let R=E.length;for(;R--;){const $=E[R].optimizeNodes();Array.isArray($)?E.splice(R,1,...$):$?E[R]=$:E.splice(R,1)}return E.length>0?this:void 0}optimizeNames(E,R){const{nodes:$}=this;let B=$.length;for(;B--;){const W=$[B];W.optimizeNames(E,R)||(se(E,W.names),$.splice(B,1))}return $.length>0?this:void 0}get names(){return this.nodes.reduce((E,R)=>D(E,R.names),{})}}class f extends d{render(E){return"{"+E._n+super.render(E)+"}"+E._n}}class w extends d{}class m extends f{}m.kind="else";class y extends f{constructor(E,R){super(R),this.condition=E}render(E){let R=`if(${this.condition})`+super.render(E);return this.else&&(R+="else "+this.else.render(E)),R}optimizeNodes(){super.optimizeNodes();const E=this.condition;if(E===!0)return this.nodes;let R=this.else;if(R){const $=R.optimizeNodes();R=this.else=Array.isArray($)?new m($):$}if(R)return E===!1?R instanceof y?R:R.nodes:this.nodes.length?this:new y(fe(E),R instanceof y?[R]:R.nodes);if(!(E===!1||!this.nodes.length))return this}optimizeNames(E,R){var $;if(this.else=($=this.else)===null||$===void 0?void 0:$.optimizeNames(E,R),!!(super.optimizeNames(E,R)||this.else))return this.condition=V(this.condition,E,R),this}get names(){const E=super.names;return U(E,this.condition),this.else&&D(E,this.else.names),E}}y.kind="if";class _ extends f{}_.kind="for";class g extends _{constructor(E){super(),this.iteration=E}render(E){return`for(${this.iteration})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iteration=V(this.iteration,E,R),this}get names(){return D(super.names,this.iteration.names)}}class b extends _{constructor(E,R,$,B){super(),this.varKind=E,this.name=R,this.from=$,this.to=B}render(E){const R=E.es5?r.varKinds.var:this.varKind,{name:$,from:B,to:W}=this;return`for(${R} ${$}=${B}; ${$}<${W}; ${$}++)`+super.render(E)}get names(){const E=U(super.names,this.from);return U(E,this.to)}}class k extends _{constructor(E,R,$,B){super(),this.loop=E,this.varKind=R,this.name=$,this.iterable=B}render(E){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(E)}optimizeNames(E,R){if(super.optimizeNames(E,R))return this.iterable=V(this.iterable,E,R),this}get names(){return D(super.names,this.iterable.names)}}class S extends f{constructor(E,R,$){super(),this.name=E,this.args=R,this.async=$}render(E){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(E)}}S.kind="func";class T extends d{render(E){return"return "+super.render(E)}}T.kind="return";class x extends f{render(E){let R="try"+super.render(E);return this.catch&&(R+=this.catch.render(E)),this.finally&&(R+=this.finally.render(E)),R}optimizeNodes(){var E,R;return super.optimizeNodes(),(E=this.catch)===null||E===void 0||E.optimizeNodes(),(R=this.finally)===null||R===void 0||R.optimizeNodes(),this}optimizeNames(E,R){var $,B;return super.optimizeNames(E,R),($=this.catch)===null||$===void 0||$.optimizeNames(E,R),(B=this.finally)===null||B===void 0||B.optimizeNames(E,R),this}get names(){const E=super.names;return this.catch&&D(E,this.catch.names),this.finally&&D(E,this.finally.names),E}}class I extends f{constructor(E){super(),this.error=E}render(E){return`catch(${this.error})`+super.render(E)}}I.kind="catch";class A extends f{render(E){return"finally"+super.render(E)}}A.kind="finally";class P{constructor(E,R={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...R,_n:R.lines?`
2
+ `:""},this._extScope=E,this._scope=new r.Scope({parent:E}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(E){return this._scope.name(E)}scopeName(E){return this._extScope.name(E)}scopeValue(E,R){const $=this._extScope.value(E,R);return(this._values[$.prefix]||(this._values[$.prefix]=new Set)).add($),$}getScopeValue(E,R){return this._extScope.getValue(E,R)}scopeRefs(E){return this._extScope.scopeRefs(E,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(E,R,$,B){const W=this._scope.toName(R);return $!==void 0&&B&&(this._constants[W.str]=$),this._leafNode(new a(E,W,$)),W}const(E,R,$){return this._def(r.varKinds.const,E,R,$)}let(E,R,$){return this._def(r.varKinds.let,E,R,$)}var(E,R,$){return this._def(r.varKinds.var,E,R,$)}assign(E,R,$){return this._leafNode(new i(E,R,$))}add(E,R){return this._leafNode(new l(E,t.operators.ADD,R))}code(E){return typeof E=="function"?E():E!==e.nil&&this._leafNode(new h(E)),this}object(...E){const R=["{"];for(const[$,B]of E)R.length>1&&R.push(","),R.push($),($!==B||this.opts.es5)&&(R.push(":"),(0,e.addCodeArg)(R,B));return R.push("}"),new e._Code(R)}if(E,R,$){if(this._blockNode(new y(E)),R&&$)this.code(R).else().code($).endIf();else if(R)this.code(R).endIf();else if($)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(E){return this._elseNode(new y(E))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(y,m)}_for(E,R){return this._blockNode(E),R&&this.code(R).endFor(),this}for(E,R){return this._for(new g(E),R)}forRange(E,R,$,B,W=this.opts.es5?r.varKinds.var:r.varKinds.let){const ye=this._scope.toName(E);return this._for(new b(W,ye,R,$),()=>B(ye))}forOf(E,R,$,B=r.varKinds.const){const W=this._scope.toName(E);if(this.opts.es5){const ye=R instanceof e.Name?R:this.var("_arr",R);return this.forRange("_i",0,(0,e._)`${ye}.length`,pe=>{this.var(W,(0,e._)`${ye}[${pe}]`),$(W)})}return this._for(new k("of",B,W,R),()=>$(W))}forIn(E,R,$,B=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(E,(0,e._)`Object.keys(${R})`,$);const W=this._scope.toName(E);return this._for(new k("in",B,W,R),()=>$(W))}endFor(){return this._endBlockNode(_)}label(E){return this._leafNode(new c(E))}break(E){return this._leafNode(new u(E))}return(E){const R=new T;if(this._blockNode(R),this.code(E),R.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(E,R,$){if(!R&&!$)throw new Error('CodeGen: "try" without "catch" and "finally"');const B=new x;if(this._blockNode(B),this.code(E),R){const W=this.name("e");this._currNode=B.catch=new I(W),R(W)}return $&&(this._currNode=B.finally=new A,this.code($)),this._endBlockNode(I,A)}throw(E){return this._leafNode(new p(E))}block(E,R){return this._blockStarts.push(this._nodes.length),E&&this.code(E).endBlock(R),this}endBlock(E){const R=this._blockStarts.pop();if(R===void 0)throw new Error("CodeGen: not in self-balancing block");const $=this._nodes.length-R;if($<0||E!==void 0&&$!==E)throw new Error(`CodeGen: wrong number of nodes: ${$} vs ${E} expected`);return this._nodes.length=R,this}func(E,R=e.nil,$,B){return this._blockNode(new S(E,R,$)),B&&this.code(B).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(E=1){for(;E-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(E){return this._currNode.nodes.push(E),this}_blockNode(E){this._currNode.nodes.push(E),this._nodes.push(E)}_endBlockNode(E,R){const $=this._currNode;if($ instanceof E||R&&$ instanceof R)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${R?`${E.kind}/${R.kind}`:E.kind}"`)}_elseNode(E){const R=this._currNode;if(!(R instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=R.else=E,this}get _root(){return this._nodes[0]}get _currNode(){const E=this._nodes;return E[E.length-1]}set _currNode(E){const R=this._nodes;R[R.length-1]=E}}t.CodeGen=P;function D(q,E){for(const R in E)q[R]=(q[R]||0)+(E[R]||0);return q}function U(q,E){return E instanceof e._CodeOrName?D(q,E.names):q}function V(q,E,R){if(q instanceof e.Name)return $(q);if(!B(q))return q;return new e._Code(q._items.reduce((W,ye)=>(ye instanceof e.Name&&(ye=$(ye)),ye instanceof e._Code?W.push(...ye._items):W.push(ye),W),[]));function $(W){const ye=R[W.str];return ye===void 0||E[W.str]!==1?W:(delete E[W.str],ye)}function B(W){return W instanceof e._Code&&W._items.some(ye=>ye instanceof e.Name&&E[ye.str]===1&&R[ye.str]!==void 0)}}function se(q,E){for(const R in E)q[R]=(q[R]||0)-(E[R]||0)}function fe(q){return typeof q=="boolean"||typeof q=="number"||q===null?!q:(0,e._)`!${F(q)}`}t.not=fe;const de=O(t.operators.AND);function re(...q){return q.reduce(de)}t.and=re;const _e=O(t.operators.OR);function H(...q){return q.reduce(_e)}t.or=H;function O(q){return(E,R)=>E===e.nil?R:R===e.nil?E:(0,e._)`${F(E)} ${q} ${F(R)}`}function F(q){return q instanceof e.Name?q:(0,e._)`(${q})`}})(ji)),ji}var Ee={},ud;function Oe(){if(ud)return Ee;ud=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.checkStrictMode=Ee.getErrorPath=Ee.Type=Ee.useFunc=Ee.setEvaluated=Ee.evaluatedPropsToName=Ee.mergeEvaluated=Ee.eachItem=Ee.unescapeJsonPointer=Ee.escapeJsonPointer=Ee.escapeFragment=Ee.unescapeFragment=Ee.schemaRefOrVal=Ee.schemaHasRulesButRef=Ee.schemaHasRules=Ee.checkUnknownRules=Ee.alwaysValidSchema=Ee.toHash=void 0;const t=$e(),e=Eo();function r(k){const S={};for(const T of k)S[T]=!0;return S}Ee.toHash=r;function n(k,S){return typeof S=="boolean"?S:Object.keys(S).length===0?!0:(s(k,S),!o(S,k.self.RULES.all))}Ee.alwaysValidSchema=n;function s(k,S=k.schema){const{opts:T,self:x}=k;if(!T.strictSchema||typeof S=="boolean")return;const I=x.RULES.keywords;for(const A in S)I[A]||b(k,`unknown keyword: "${A}"`)}Ee.checkUnknownRules=s;function o(k,S){if(typeof k=="boolean")return!k;for(const T in k)if(S[T])return!0;return!1}Ee.schemaHasRules=o;function a(k,S){if(typeof k=="boolean")return!k;for(const T in k)if(T!=="$ref"&&S.all[T])return!0;return!1}Ee.schemaHasRulesButRef=a;function i({topSchemaRef:k,schemaPath:S},T,x,I){if(!I){if(typeof T=="number"||typeof T=="boolean")return T;if(typeof T=="string")return(0,t._)`${T}`}return(0,t._)`${k}${S}${(0,t.getProperty)(x)}`}Ee.schemaRefOrVal=i;function l(k){return p(decodeURIComponent(k))}Ee.unescapeFragment=l;function c(k){return encodeURIComponent(u(k))}Ee.escapeFragment=c;function u(k){return typeof k=="number"?`${k}`:k.replace(/~/g,"~0").replace(/\//g,"~1")}Ee.escapeJsonPointer=u;function p(k){return k.replace(/~1/g,"/").replace(/~0/g,"~")}Ee.unescapeJsonPointer=p;function h(k,S){if(Array.isArray(k))for(const T of k)S(T);else S(k)}Ee.eachItem=h;function d({mergeNames:k,mergeToName:S,mergeValues:T,resultToName:x}){return(I,A,P,D)=>{const U=P===void 0?A:P instanceof t.Name?(A instanceof t.Name?k(I,A,P):S(I,A,P),P):A instanceof t.Name?(S(I,P,A),A):T(A,P);return D===t.Name&&!(U instanceof t.Name)?x(I,U):U}}Ee.mergeEvaluated={props:d({mergeNames:(k,S,T)=>k.if((0,t._)`${T} !== true && ${S} !== undefined`,()=>{k.if((0,t._)`${S} === true`,()=>k.assign(T,!0),()=>k.assign(T,(0,t._)`${T} || {}`).code((0,t._)`Object.assign(${T}, ${S})`))}),mergeToName:(k,S,T)=>k.if((0,t._)`${T} !== true`,()=>{S===!0?k.assign(T,!0):(k.assign(T,(0,t._)`${T} || {}`),w(k,T,S))}),mergeValues:(k,S)=>k===!0?!0:{...k,...S},resultToName:f}),items:d({mergeNames:(k,S,T)=>k.if((0,t._)`${T} !== true && ${S} !== undefined`,()=>k.assign(T,(0,t._)`${S} === true ? true : ${T} > ${S} ? ${T} : ${S}`)),mergeToName:(k,S,T)=>k.if((0,t._)`${T} !== true`,()=>k.assign(T,S===!0?!0:(0,t._)`${T} > ${S} ? ${T} : ${S}`)),mergeValues:(k,S)=>k===!0?!0:Math.max(k,S),resultToName:(k,S)=>k.var("items",S)})};function f(k,S){if(S===!0)return k.var("props",!0);const T=k.var("props",(0,t._)`{}`);return S!==void 0&&w(k,T,S),T}Ee.evaluatedPropsToName=f;function w(k,S,T){Object.keys(T).forEach(x=>k.assign((0,t._)`${S}${(0,t.getProperty)(x)}`,!0))}Ee.setEvaluated=w;const m={};function y(k,S){return k.scopeValue("func",{ref:S,code:m[S.code]||(m[S.code]=new e._Code(S.code))})}Ee.useFunc=y;var _;(function(k){k[k.Num=0]="Num",k[k.Str=1]="Str"})(_||(Ee.Type=_={}));function g(k,S,T){if(k instanceof t.Name){const x=S===_.Num;return T?x?(0,t._)`"[" + ${k} + "]"`:(0,t._)`"['" + ${k} + "']"`:x?(0,t._)`"/" + ${k}`:(0,t._)`"/" + ${k}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return T?(0,t.getProperty)(k).toString():"/"+u(k)}Ee.getErrorPath=g;function b(k,S,T=k.opts.strictSchema){if(T){if(S=`strict mode: ${S}`,T===!0)throw new Error(S);k.self.logger.warn(S)}}return Ee.checkStrictMode=b,Ee}var xo={},dd;function Nr(){if(dd)return xo;dd=1,Object.defineProperty(xo,"__esModule",{value:!0});const t=$e(),e={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};return xo.default=e,xo}var pd;function Io(){return pd||(pd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=$e(),r=Oe(),n=Nr();t.keywordError={message:({keyword:m})=>(0,e.str)`must pass "${m}" keyword validation`},t.keyword$DataError={message:({keyword:m,schemaType:y})=>y?(0,e.str)`"${m}" keyword must be ${y} ($data)`:(0,e.str)`"${m}" keyword is invalid ($data)`};function s(m,y=t.keywordError,_,g){const{it:b}=m,{gen:k,compositeRule:S,allErrors:T}=b,x=p(m,y,_);g??(S||T)?l(k,x):c(b,(0,e._)`[${x}]`)}t.reportError=s;function o(m,y=t.keywordError,_){const{it:g}=m,{gen:b,compositeRule:k,allErrors:S}=g,T=p(m,y,_);l(b,T),k||S||c(g,n.default.vErrors)}t.reportExtraError=o;function a(m,y){m.assign(n.default.errors,y),m.if((0,e._)`${n.default.vErrors} !== null`,()=>m.if(y,()=>m.assign((0,e._)`${n.default.vErrors}.length`,y),()=>m.assign(n.default.vErrors,null)))}t.resetErrorsCount=a;function i({gen:m,keyword:y,schemaValue:_,data:g,errsCount:b,it:k}){if(b===void 0)throw new Error("ajv implementation error");const S=m.name("err");m.forRange("i",b,n.default.errors,T=>{m.const(S,(0,e._)`${n.default.vErrors}[${T}]`),m.if((0,e._)`${S}.instancePath === undefined`,()=>m.assign((0,e._)`${S}.instancePath`,(0,e.strConcat)(n.default.instancePath,k.errorPath))),m.assign((0,e._)`${S}.schemaPath`,(0,e.str)`${k.errSchemaPath}/${y}`),k.opts.verbose&&(m.assign((0,e._)`${S}.schema`,_),m.assign((0,e._)`${S}.data`,g))})}t.extendErrors=i;function l(m,y){const _=m.const("err",y);m.if((0,e._)`${n.default.vErrors} === null`,()=>m.assign(n.default.vErrors,(0,e._)`[${_}]`),(0,e._)`${n.default.vErrors}.push(${_})`),m.code((0,e._)`${n.default.errors}++`)}function c(m,y){const{gen:_,validateName:g,schemaEnv:b}=m;b.$async?_.throw((0,e._)`new ${m.ValidationError}(${y})`):(_.assign((0,e._)`${g}.errors`,y),_.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function p(m,y,_){const{createErrors:g}=m.it;return g===!1?(0,e._)`{}`:h(m,y,_)}function h(m,y,_={}){const{gen:g,it:b}=m,k=[d(b,_),f(m,_)];return w(m,y,k),g.object(...k)}function d({errorPath:m},{instancePath:y}){const _=y?(0,e.str)`${m}${(0,r.getErrorPath)(y,r.Type.Str)}`:m;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,_)]}function f({keyword:m,it:{errSchemaPath:y}},{schemaPath:_,parentSchema:g}){let b=g?y:(0,e.str)`${y}/${m}`;return _&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,b]}function w(m,{params:y,message:_},g){const{keyword:b,data:k,schemaValue:S,it:T}=m,{opts:x,propertyName:I,topSchemaRef:A,schemaPath:P}=T;g.push([u.keyword,b],[u.params,typeof y=="function"?y(m):y||(0,e._)`{}`]),x.messages&&g.push([u.message,typeof _=="function"?_(m):_]),x.verbose&&g.push([u.schema,S],[u.parentSchema,(0,e._)`${A}${P}`],[n.default.data,k]),I&&g.push([u.propertyName,I])}})(Li)),Li}var fd;function S_(){if(fd)return rn;fd=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.boolOrEmptySchema=rn.topBoolOrEmptySchema=void 0;const t=Io(),e=$e(),r=Nr(),n={message:"boolean schema is false"};function s(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,e._)`${u}.errors`,null),l.return(!0))}rn.topBoolOrEmptySchema=s;function o(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}rn.boolOrEmptySchema=o;function a(i,l){const{gen:c,data:u}=i,p={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,t.reportError)(p,n,void 0,l)}return rn}var st={},nn={},hd;function md(){if(hd)return nn;hd=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.getRules=nn.isJSONType=void 0;const t=["string","number","integer","boolean","null","object","array"],e=new Set(t);function r(s){return typeof s=="string"&&e.has(s)}nn.isJSONType=r;function n(){const s={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...s,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},s.number,s.string,s.array,s.object],post:{rules:[]},all:{},keywords:{}}}return nn.getRules=n,nn}var wr={},gd;function vd(){if(gd)return wr;gd=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.shouldUseRule=wr.shouldUseGroup=wr.schemaHasRulesForType=void 0;function t({schema:n,self:s},o){const a=s.RULES.types[o];return a&&a!==!0&&e(n,a)}wr.schemaHasRulesForType=t;function e(n,s){return s.rules.some(o=>r(n,o))}wr.shouldUseGroup=e;function r(n,s){var o;return n[s.keyword]!==void 0||((o=s.definition.implements)===null||o===void 0?void 0:o.some(a=>n[a]!==void 0))}return wr.shouldUseRule=r,wr}var _d;function Ro(){if(_d)return st;_d=1,Object.defineProperty(st,"__esModule",{value:!0}),st.reportTypeError=st.checkDataTypes=st.checkDataType=st.coerceAndCheckDataType=st.getJSONTypes=st.getSchemaTypes=st.DataType=void 0;const t=md(),e=vd(),r=Io(),n=$e(),s=Oe();var o;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(o||(st.DataType=o={}));function a(_){const g=i(_.type);if(g.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!g.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&g.push("null")}return g}st.getSchemaTypes=a;function i(_){const g=Array.isArray(_)?_:_?[_]:[];if(g.every(t.isJSONType))return g;throw new Error("type must be JSONType or JSONType[]: "+g.join(","))}st.getJSONTypes=i;function l(_,g){const{gen:b,data:k,opts:S}=_,T=u(g,S.coerceTypes),x=g.length>0&&!(T.length===0&&g.length===1&&(0,e.schemaHasRulesForType)(_,g[0]));if(x){const I=f(g,k,S.strictNumbers,o.Wrong);b.if(I,()=>{T.length?p(_,g,T):m(_)})}return x}st.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(_,g){return g?_.filter(b=>c.has(b)||g==="array"&&b==="array"):[]}function p(_,g,b){const{gen:k,data:S,opts:T}=_,x=k.let("dataType",(0,n._)`typeof ${S}`),I=k.let("coerced",(0,n._)`undefined`);T.coerceTypes==="array"&&k.if((0,n._)`${x} == 'object' && Array.isArray(${S}) && ${S}.length == 1`,()=>k.assign(S,(0,n._)`${S}[0]`).assign(x,(0,n._)`typeof ${S}`).if(f(g,S,T.strictNumbers),()=>k.assign(I,S))),k.if((0,n._)`${I} !== undefined`);for(const P of b)(c.has(P)||P==="array"&&T.coerceTypes==="array")&&A(P);k.else(),m(_),k.endIf(),k.if((0,n._)`${I} !== undefined`,()=>{k.assign(S,I),h(_,I)});function A(P){switch(P){case"string":k.elseIf((0,n._)`${x} == "number" || ${x} == "boolean"`).assign(I,(0,n._)`"" + ${S}`).elseIf((0,n._)`${S} === null`).assign(I,(0,n._)`""`);return;case"number":k.elseIf((0,n._)`${x} == "boolean" || ${S} === null
3
3
  || (${x} == "string" && ${S} && ${S} == +${S})`).assign(I,(0,n._)`+${S}`);return;case"integer":k.elseIf((0,n._)`${x} === "boolean" || ${S} === null
4
4
  || (${x} === "string" && ${S} && ${S} == +${S} && !(${S} % 1))`).assign(I,(0,n._)`+${S}`);return;case"boolean":k.elseIf((0,n._)`${S} === "false" || ${S} === 0 || ${S} === null`).assign(I,!1).elseIf((0,n._)`${S} === "true" || ${S} === 1`).assign(I,!0);return;case"null":k.elseIf((0,n._)`${S} === "" || ${S} === 0 || ${S} === false`),k.assign(I,null);return;case"array":k.elseIf((0,n._)`${x} === "string" || ${x} === "number"
5
- || ${x} === "boolean" || ${S} === null`).assign(I,(0,n._)`[${S}]`)}}}function h({gen:_,parentData:g,parentDataProperty:b},k){_.if((0,n._)`${g} !== undefined`,()=>_.assign((0,n._)`${g}[${b}]`,k))}function d(_,g,b,k=o.Correct){const S=k===o.Correct?n.operators.EQ:n.operators.NEQ;let T;switch(_){case"null":return(0,n._)`${g} ${S} null`;case"array":T=(0,n._)`Array.isArray(${g})`;break;case"object":T=(0,n._)`${g} && typeof ${g} == "object" && !Array.isArray(${g})`;break;case"integer":T=x((0,n._)`!(${g} % 1) && !isNaN(${g})`);break;case"number":T=x();break;default:return(0,n._)`typeof ${g} ${S} ${_}`}return k===o.Correct?T:(0,n.not)(T);function x(I=n.nil){return(0,n.and)((0,n._)`typeof ${g} == "number"`,I,b?(0,n._)`isFinite(${g})`:n.nil)}}st.checkDataType=d;function f(_,g,b,k){if(_.length===1)return d(_[0],g,b,k);let S;const T=(0,s.toHash)(_);if(T.array&&T.object){const x=(0,n._)`typeof ${g} != "object"`;S=T.null?x:(0,n._)`!${g} || ${x}`,delete T.null,delete T.array,delete T.object}else S=n.nil;T.number&&delete T.integer;for(const x in T)S=(0,n.and)(S,d(x,g,b,k));return S}st.checkDataTypes=f;const w={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:g})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${g}}`};function m(_){const g=y(_);(0,r.reportError)(g,w)}st.reportTypeError=m;function y(_){const{gen:g,data:b,schema:k}=_,S=(0,s.schemaRefOrVal)(_,k,"type");return{gen:g,keyword:"type",data:b,schema:k.type,schemaCode:S,schemaValue:S,parentSchema:k,params:{},it:_}}return st}var ds={},wd;function T_(){if(wd)return ds;wd=1,Object.defineProperty(ds,"__esModule",{value:!0}),ds.assignDefaults=void 0;const t=$e(),e=Oe();function r(s,o){const{properties:a,items:i}=s.schema;if(o==="object"&&a)for(const l in a)n(s,l,a[l].default);else o==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(s,c,l.default))}ds.assignDefaults=r;function n(s,o,a){const{gen:i,compositeRule:l,data:c,opts:u}=s;if(a===void 0)return;const p=(0,t._)`${c}${(0,t.getProperty)(o)}`;if(l){(0,e.checkStrictMode)(s,`default is ignored for: ${p}`);return}let h=(0,t._)`${p} === undefined`;u.useDefaults==="empty"&&(h=(0,t._)`${h} || ${p} === null || ${p} === ""`),i.if(h,(0,t._)`${p} = ${(0,t.stringify)(a)}`)}return ds}var Zt={},je={},bd;function Ft(){if(bd)return je;bd=1,Object.defineProperty(je,"__esModule",{value:!0}),je.validateUnion=je.validateArray=je.usePattern=je.callValidateCode=je.schemaProperties=je.allSchemaProperties=je.noPropertyInData=je.propertyInData=je.isOwnProperty=je.hasPropFunc=je.reportMissingProp=je.checkMissingProp=je.checkReportMissingProp=void 0;const t=$e(),e=Oe(),r=Nr(),n=Oe();function s(_,g){const{gen:b,data:k,it:S}=_;b.if(u(b,k,g,S.opts.ownProperties),()=>{_.setParams({missingProperty:(0,t._)`${g}`},!0),_.error()})}je.checkReportMissingProp=s;function o({gen:_,data:g,it:{opts:b}},k,S){return(0,t.or)(...k.map(T=>(0,t.and)(u(_,g,T,b.ownProperties),(0,t._)`${S} = ${T}`)))}je.checkMissingProp=o;function a(_,g){_.setParams({missingProperty:g},!0),_.error()}je.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}je.hasPropFunc=i;function l(_,g,b){return(0,t._)`${i(_)}.call(${g}, ${b})`}je.isOwnProperty=l;function c(_,g,b,k){const S=(0,t._)`${g}${(0,t.getProperty)(b)} !== undefined`;return k?(0,t._)`${S} && ${l(_,g,b)}`:S}je.propertyInData=c;function u(_,g,b,k){const S=(0,t._)`${g}${(0,t.getProperty)(b)} === undefined`;return k?(0,t.or)(S,(0,t.not)(l(_,g,b))):S}je.noPropertyInData=u;function p(_){return _?Object.keys(_).filter(g=>g!=="__proto__"):[]}je.allSchemaProperties=p;function h(_,g){return p(g).filter(b=>!(0,e.alwaysValidSchema)(_,g[b]))}je.schemaProperties=h;function d({schemaCode:_,data:g,it:{gen:b,topSchemaRef:k,schemaPath:S,errorPath:T},it:x},I,A,P){const D=P?(0,t._)`${_}, ${g}, ${k}${S}`:g,U=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,T)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&U.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const V=(0,t._)`${D}, ${b.object(...U)}`;return A!==t.nil?(0,t._)`${I}.call(${A}, ${V})`:(0,t._)`${I}(${V})`}je.callValidateCode=d;const f=(0,t._)`new RegExp`;function w({gen:_,it:{opts:g}},b){const k=g.unicodeRegExp?"u":"",{regExp:S}=g.code,T=S(b,k);return _.scopeValue("pattern",{key:T.toString(),ref:T,code:(0,t._)`${S.code==="new RegExp"?f:(0,n.useFunc)(_,S)}(${b}, ${k})`})}je.usePattern=w;function m(_){const{gen:g,data:b,keyword:k,it:S}=_,T=g.name("valid");if(S.allErrors){const I=g.let("valid",!0);return x(()=>g.assign(I,!1)),I}return g.var(T,!0),x(()=>g.break()),T;function x(I){const A=g.const("len",(0,t._)`${b}.length`);g.forRange("i",0,A,P=>{_.subschema({keyword:k,dataProp:P,dataPropType:e.Type.Num},T),g.if((0,t.not)(T),I)})}}je.validateArray=m;function y(_){const{gen:g,schema:b,keyword:k,it:S}=_;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(A=>(0,e.alwaysValidSchema)(S,A))&&!S.opts.unevaluated)return;const x=g.let("valid",!1),I=g.name("_valid");g.block(()=>b.forEach((A,P)=>{const D=_.subschema({keyword:k,schemaProp:P,compositeRule:!0},I);g.assign(x,(0,t._)`${x} || ${I}`),_.mergeValidEvaluated(D,I)||g.if((0,t.not)(x))})),_.result(x,()=>_.reset(),()=>_.error(!0))}return je.validateUnion=y,je}var kd;function C_(){if(kd)return Zt;kd=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.validateKeywordUsage=Zt.validSchemaType=Zt.funcKeywordCode=Zt.macroKeywordCode=void 0;const t=$e(),e=Nr(),r=Ft(),n=Io();function s(h,d){const{gen:f,keyword:w,schema:m,parentSchema:y,it:_}=h,g=d.macro.call(_.self,m,y,_),b=c(f,w,g);_.opts.validateSchema!==!1&&_.self.validateSchema(g,!0);const k=f.name("valid");h.subschema({schema:g,schemaPath:t.nil,errSchemaPath:`${_.errSchemaPath}/${w}`,topSchemaRef:b,compositeRule:!0},k),h.pass(k,()=>h.error(!0))}Zt.macroKeywordCode=s;function o(h,d){var f;const{gen:w,keyword:m,schema:y,parentSchema:_,$data:g,it:b}=h;l(b,d);const k=!g&&d.compile?d.compile.call(b.self,y,_,b):d.validate,S=c(w,m,k),T=w.let("valid");h.block$data(T,x),h.ok((f=d.valid)!==null&&f!==void 0?f:T);function x(){if(d.errors===!1)P(),d.modifying&&a(h),D(()=>h.error());else{const U=d.async?I():A();d.modifying&&a(h),D(()=>i(h,U))}}function I(){const U=w.let("ruleErrs",null);return w.try(()=>P((0,t._)`await `),V=>w.assign(T,!1).if((0,t._)`${V} instanceof ${b.ValidationError}`,()=>w.assign(U,(0,t._)`${V}.errors`),()=>w.throw(V))),U}function A(){const U=(0,t._)`${S}.errors`;return w.assign(U,null),P(t.nil),U}function P(U=d.async?(0,t._)`await `:t.nil){const V=b.opts.passContext?e.default.this:e.default.self,se=!("compile"in d&&!g||d.schema===!1);w.assign(T,(0,t._)`${U}${(0,r.callValidateCode)(h,S,V,se)}`,d.modifying)}function D(U){var V;w.if((0,t.not)((V=d.valid)!==null&&V!==void 0?V:T),U)}}Zt.funcKeywordCode=o;function a(h){const{gen:d,data:f,it:w}=h;d.if(w.parentData,()=>d.assign(f,(0,t._)`${w.parentData}[${w.parentDataProperty}]`))}function i(h,d){const{gen:f}=h;f.if((0,t._)`Array.isArray(${d})`,()=>{f.assign(e.default.vErrors,(0,t._)`${e.default.vErrors} === null ? ${d} : ${e.default.vErrors}.concat(${d})`).assign(e.default.errors,(0,t._)`${e.default.vErrors}.length`),(0,n.extendErrors)(h)},()=>h.error())}function l({schemaEnv:h},d){if(d.async&&!h.$async)throw new Error("async keyword in sync schema")}function c(h,d,f){if(f===void 0)throw new Error(`keyword "${d}" failed to compile`);return h.scopeValue("keyword",typeof f=="function"?{ref:f}:{ref:f,code:(0,t.stringify)(f)})}function u(h,d,f=!1){return!d.length||d.some(w=>w==="array"?Array.isArray(h):w==="object"?h&&typeof h=="object"&&!Array.isArray(h):typeof h==w||f&&typeof h>"u")}Zt.validSchemaType=u;function p({schema:h,opts:d,self:f,errSchemaPath:w},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");const _=m.dependencies;if(_?.some(g=>!Object.prototype.hasOwnProperty.call(h,g)))throw new Error(`parent schema must have dependencies of ${y}: ${_.join(",")}`);if(m.validateSchema&&!m.validateSchema(h[y])){const b=`keyword "${y}" value is invalid at path "${w}": `+f.errorsText(m.validateSchema.errors);if(d.validateSchema==="log")f.logger.error(b);else throw new Error(b)}}return Zt.validateKeywordUsage=p,Zt}var br={},Sd;function $_(){if(Sd)return br;Sd=1,Object.defineProperty(br,"__esModule",{value:!0}),br.extendSubschemaMode=br.extendSubschemaData=br.getSubschema=void 0;const t=$e(),e=Oe();function r(o,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:p}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const h=o.schema[a];return i===void 0?{schema:h,schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}`,errSchemaPath:`${o.errSchemaPath}/${a}`}:{schema:h[i],schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}${(0,t.getProperty)(i)}`,errSchemaPath:`${o.errSchemaPath}/${a}/${(0,e.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||p===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:p,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}br.getSubschema=r;function n(o,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:p}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=a;if(i!==void 0){const{errorPath:f,dataPathArr:w,opts:m}=a,y=h.let("data",(0,t._)`${a.data}${(0,t.getProperty)(i)}`,!0);d(y),o.errorPath=(0,t.str)`${f}${(0,e.getErrorPath)(i,l,m.jsPropertySyntax)}`,o.parentDataProperty=(0,t._)`${i}`,o.dataPathArr=[...w,o.parentDataProperty]}if(c!==void 0){const f=c instanceof t.Name?c:h.let("data",c,!0);d(f),p!==void 0&&(o.propertyName=p)}u&&(o.dataTypes=u);function d(f){o.data=f,o.dataLevel=a.dataLevel+1,o.dataTypes=[],a.definedProperties=new Set,o.parentData=a.data,o.dataNames=[...a.dataNames,f]}}br.extendSubschemaData=n;function s(o,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(o.compositeRule=l),c!==void 0&&(o.createErrors=c),u!==void 0&&(o.allErrors=u),o.jtdDiscriminator=a,o.jtdMetadata=i}return br.extendSubschemaMode=s,br}var pt={},Di,Td;function Cd(){return Td||(Td=1,Di=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var a=o[s];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}),Di}var Ui={exports:{}},$d;function E_(){if($d)return Ui.exports;$d=1;var t=Ui.exports=function(n,s,o){typeof s=="function"&&(o=s,s={}),o=s.cb||o;var a=typeof o=="function"?o:o.pre||function(){},i=o.post||function(){};e(s,a,i,n,"",n)};t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.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 e(n,s,o,a,i,l,c,u,p,h){if(a&&typeof a=="object"&&!Array.isArray(a)){s(a,i,l,c,u,p,h);for(var d in a){var f=a[d];if(Array.isArray(f)){if(d in t.arrayKeywords)for(var w=0;w<f.length;w++)e(n,s,o,f[w],i+"/"+d+"/"+w,l,i,d,a,w)}else if(d in t.propsKeywords){if(f&&typeof f=="object")for(var m in f)e(n,s,o,f[m],i+"/"+d+"/"+r(m),l,i,d,a,m)}else(d in t.keywords||n.allKeys&&!(d in t.skipKeywords))&&e(n,s,o,f,i+"/"+d,l,i,d,a)}o(a,i,l,c,u,p,h)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Ui.exports}var Ed;function Po(){if(Ed)return pt;Ed=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.getSchemaRefs=pt.resolveUrl=pt.normalizeId=pt._getFullPath=pt.getFullPath=pt.inlineRef=void 0;const t=Oe(),e=Cd(),r=E_(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s(w,m=!0){return typeof w=="boolean"?!0:m===!0?!a(w):m?i(w)<=m:!1}pt.inlineRef=s;const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(w){for(const m in w){if(o.has(m))return!0;const y=w[m];if(Array.isArray(y)&&y.some(a)||typeof y=="object"&&a(y))return!0}return!1}function i(w){let m=0;for(const y in w){if(y==="$ref")return 1/0;if(m++,!n.has(y)&&(typeof w[y]=="object"&&(0,t.eachItem)(w[y],_=>m+=i(_)),m===1/0))return 1/0}return m}function l(w,m="",y){y!==!1&&(m=p(m));const _=w.parse(m);return c(w,_)}pt.getFullPath=l;function c(w,m){return w.serialize(m).split("#")[0]+"#"}pt._getFullPath=c;const u=/#\/?$/;function p(w){return w?w.replace(u,""):""}pt.normalizeId=p;function h(w,m,y){return y=p(y),w.resolve(m,y)}pt.resolveUrl=h;const d=/^[a-z_][-a-z0-9._]*$/i;function f(w,m){if(typeof w=="boolean")return{};const{schemaId:y,uriResolver:_}=this.opts,g=p(w[y]||m),b={"":g},k=l(_,g,!1),S={},T=new Set;return r(w,{allKeys:!0},(A,P,D,U)=>{if(U===void 0)return;const V=k+P;let se=b[U];typeof A[y]=="string"&&(se=fe.call(this,A[y])),de.call(this,A.$anchor),de.call(this,A.$dynamicAnchor),b[P]=se;function fe(re){const _e=this.opts.uriResolver.resolve;if(re=p(se?_e(se,re):re),T.has(re))throw I(re);T.add(re);let H=this.refs[re];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?x(A,H.schema,re):re!==p(V)&&(re[0]==="#"?(x(A,S[re],re),S[re]=A):this.refs[re]=V),re}function de(re){if(typeof re=="string"){if(!d.test(re))throw new Error(`invalid anchor "${re}"`);fe.call(this,`#${re}`)}}}),S;function x(A,P,D){if(P!==void 0&&!e(A,P))throw I(D)}function I(A){return new Error(`reference "${A}" resolves to more than one schema`)}}return pt.getSchemaRefs=f,pt}var xd;function Oo(){if(xd)return yr;xd=1,Object.defineProperty(yr,"__esModule",{value:!0}),yr.getData=yr.KeywordCxt=yr.validateFunctionCode=void 0;const t=S_(),e=Ro(),r=_d(),n=Ro(),s=T_(),o=C_(),a=$_(),i=$e(),l=Nr(),c=Po(),u=Oe(),p=Io();function h(M){if(k(M)&&(T(M),b(M))){m(M);return}d(M,()=>(0,t.topBoolOrEmptySchema)(M))}yr.validateFunctionCode=h;function d({gen:M,validateName:Z,schema:G,schemaEnv:K,opts:X},ue){X.code.es5?M.func(Z,(0,i._)`${l.default.data}, ${l.default.valCxt}`,K.$async,()=>{M.code((0,i._)`"use strict"; ${_(G,X)}`),w(M,X),M.code(ue)}):M.func(Z,(0,i._)`${l.default.data}, ${f(X)}`,K.$async,()=>M.code(_(G,X)).code(ue))}function f(M){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${M.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function w(M,Z){M.if(l.default.valCxt,()=>{M.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),M.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),M.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),M.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),Z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{M.var(l.default.instancePath,(0,i._)`""`),M.var(l.default.parentData,(0,i._)`undefined`),M.var(l.default.parentDataProperty,(0,i._)`undefined`),M.var(l.default.rootData,l.default.data),Z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function m(M){const{schema:Z,opts:G,gen:K}=M;d(M,()=>{G.$comment&&Z.$comment&&U(M),A(M),K.let(l.default.vErrors,null),K.let(l.default.errors,0),G.unevaluated&&y(M),x(M),V(M)})}function y(M){const{gen:Z,validateName:G}=M;M.evaluated=Z.const("evaluated",(0,i._)`${G}.evaluated`),Z.if((0,i._)`${M.evaluated}.dynamicProps`,()=>Z.assign((0,i._)`${M.evaluated}.props`,(0,i._)`undefined`)),Z.if((0,i._)`${M.evaluated}.dynamicItems`,()=>Z.assign((0,i._)`${M.evaluated}.items`,(0,i._)`undefined`))}function _(M,Z){const G=typeof M=="object"&&M[Z.schemaId];return G&&(Z.code.source||Z.code.process)?(0,i._)`/*# sourceURL=${G} */`:i.nil}function g(M,Z){if(k(M)&&(T(M),b(M))){S(M,Z);return}(0,t.boolOrEmptySchema)(M,Z)}function b({schema:M,self:Z}){if(typeof M=="boolean")return!M;for(const G in M)if(Z.RULES.all[G])return!0;return!1}function k(M){return typeof M.schema!="boolean"}function S(M,Z){const{schema:G,gen:K,opts:X}=M;X.$comment&&G.$comment&&U(M),P(M),D(M);const ue=K.const("_errs",l.default.errors);x(M,ue),K.var(Z,(0,i._)`${ue} === ${l.default.errors}`)}function T(M){(0,u.checkUnknownRules)(M),I(M)}function x(M,Z){if(M.opts.jtd)return fe(M,[],!1,Z);const G=(0,e.getSchemaTypes)(M.schema),K=(0,e.coerceAndCheckDataType)(M,G);fe(M,G,!K,Z)}function I(M){const{schema:Z,errSchemaPath:G,opts:K,self:X}=M;Z.$ref&&K.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,X.RULES)&&X.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function A(M){const{schema:Z,opts:G}=M;Z.default!==void 0&&G.useDefaults&&G.strictSchema&&(0,u.checkStrictMode)(M,"default is ignored in the schema root")}function P(M){const Z=M.schema[M.opts.schemaId];Z&&(M.baseId=(0,c.resolveUrl)(M.opts.uriResolver,M.baseId,Z))}function D(M){if(M.schema.$async&&!M.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:M,schemaEnv:Z,schema:G,errSchemaPath:K,opts:X}){const ue=G.$comment;if(X.$comment===!0)M.code((0,i._)`${l.default.self}.logger.log(${ue})`);else if(typeof X.$comment=="function"){const he=(0,i.str)`${K}/$comment`,He=M.scopeValue("root",{ref:Z.root});M.code((0,i._)`${l.default.self}.opts.$comment(${ue}, ${he}, ${He}.schema)`)}}function V(M){const{gen:Z,schemaEnv:G,validateName:K,ValidationError:X,opts:ue}=M;G.$async?Z.if((0,i._)`${l.default.errors} === 0`,()=>Z.return(l.default.data),()=>Z.throw((0,i._)`new ${X}(${l.default.vErrors})`)):(Z.assign((0,i._)`${K}.errors`,l.default.vErrors),ue.unevaluated&&se(M),Z.return((0,i._)`${l.default.errors} === 0`))}function se({gen:M,evaluated:Z,props:G,items:K}){G instanceof i.Name&&M.assign((0,i._)`${Z}.props`,G),K instanceof i.Name&&M.assign((0,i._)`${Z}.items`,K)}function fe(M,Z,G,K){const{gen:X,schema:ue,data:he,allErrors:He,opts:Je,self:ee}=M,{RULES:be}=ee;if(ue.$ref&&(Je.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ue,be))){X.block(()=>B(M,"$ref",be.all.$ref.definition));return}Je.jtd||re(M,Z),X.block(()=>{for(const xe of be.rules)yt(xe);yt(be.post)});function yt(xe){(0,r.shouldUseGroup)(ue,xe)&&(xe.type?(X.if((0,n.checkDataType)(xe.type,he,Je.strictNumbers)),de(M,xe),Z.length===1&&Z[0]===xe.type&&G&&(X.else(),(0,n.reportTypeError)(M)),X.endIf()):de(M,xe),He||X.if((0,i._)`${l.default.errors} === ${K||0}`))}}function de(M,Z){const{gen:G,schema:K,opts:{useDefaults:X}}=M;X&&(0,s.assignDefaults)(M,Z.type),G.block(()=>{for(const ue of Z.rules)(0,r.shouldUseRule)(K,ue)&&B(M,ue.keyword,ue.definition,Z.type)})}function re(M,Z){M.schemaEnv.meta||!M.opts.strictTypes||(_e(M,Z),M.opts.allowUnionTypes||H(M,Z),O(M,M.dataTypes))}function _e(M,Z){if(Z.length){if(!M.dataTypes.length){M.dataTypes=Z;return}Z.forEach(G=>{q(M.dataTypes,G)||R(M,`type "${G}" not allowed by context "${M.dataTypes.join(",")}"`)}),E(M,Z)}}function H(M,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&R(M,"use allowUnionTypes to allow union type keyword")}function O(M,Z){const G=M.self.RULES.all;for(const K in G){const X=G[K];if(typeof X=="object"&&(0,r.shouldUseRule)(M.schema,X)){const{type:ue}=X.definition;ue.length&&!ue.some(he=>F(Z,he))&&R(M,`missing type "${ue.join(",")}" for keyword "${K}"`)}}}function F(M,Z){return M.includes(Z)||Z==="number"&&M.includes("integer")}function q(M,Z){return M.includes(Z)||Z==="integer"&&M.includes("number")}function E(M,Z){const G=[];for(const K of M.dataTypes)q(Z,K)?G.push(K):Z.includes("integer")&&K==="number"&&G.push("integer");M.dataTypes=G}function R(M,Z){const G=M.schemaEnv.baseId+M.errSchemaPath;Z+=` at "${G}" (strictTypes)`,(0,u.checkStrictMode)(M,Z,M.opts.strictTypes)}class ${constructor(Z,G,K){if((0,o.validateKeywordUsage)(Z,G,K),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=K,this.data=Z.data,this.schema=Z.schema[K],this.$data=G.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,K,this.$data),this.schemaType=G.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=G,this.$data)this.schemaCode=Z.gen.const("vSchema",pe(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,G.schemaType,G.allowUndefined))throw new Error(`${K} value must be ${JSON.stringify(G.schemaType)}`);("code"in G?G.trackErrors:G.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",l.default.errors))}result(Z,G,K){this.failResult((0,i.not)(Z),G,K)}failResult(Z,G,K){this.gen.if(Z),K?K():this.error(),G?(this.gen.else(),G(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,G){this.failResult((0,i.not)(Z),void 0,G)}fail(Z){if(Z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(Z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(Z){if(!this.$data)return this.fail(Z);const{schemaCode:G}=this;this.fail((0,i._)`${G} !== undefined && (${(0,i.or)(this.invalid$data(),Z)})`)}error(Z,G,K){if(G){this.setParams(G),this._error(Z,K),this.setParams({});return}this._error(Z,K)}_error(Z,G){(Z?p.reportExtraError:p.reportError)(this,this.def.error,G)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(Z){this.allErrors||this.gen.if(Z)}setParams(Z,G){G?Object.assign(this.params,Z):this.params=Z}block$data(Z,G,K=i.nil){this.gen.block(()=>{this.check$data(Z,K),G()})}check$data(Z=i.nil,G=i.nil){if(!this.$data)return;const{gen:K,schemaCode:X,schemaType:ue,def:he}=this;K.if((0,i.or)((0,i._)`${X} === undefined`,G)),Z!==i.nil&&K.assign(Z,!0),(ue.length||he.validateSchema)&&(K.elseIf(this.invalid$data()),this.$dataError(),Z!==i.nil&&K.assign(Z,!1)),K.else()}invalid$data(){const{gen:Z,schemaCode:G,schemaType:K,def:X,it:ue}=this;return(0,i.or)(he(),He());function he(){if(K.length){if(!(G instanceof i.Name))throw new Error("ajv implementation error");const Je=Array.isArray(K)?K:[K];return(0,i._)`${(0,n.checkDataTypes)(Je,G,ue.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function He(){if(X.validateSchema){const Je=Z.scopeValue("validate$data",{ref:X.validateSchema});return(0,i._)`!${Je}(${G})`}return i.nil}}subschema(Z,G){const K=(0,a.getSubschema)(this.it,Z);(0,a.extendSubschemaData)(K,this.it,Z),(0,a.extendSubschemaMode)(K,Z);const X={...this.it,...K,items:void 0,props:void 0};return g(X,G),X}mergeEvaluated(Z,G){const{it:K,gen:X}=this;K.opts.unevaluated&&(K.props!==!0&&Z.props!==void 0&&(K.props=u.mergeEvaluated.props(X,Z.props,K.props,G)),K.items!==!0&&Z.items!==void 0&&(K.items=u.mergeEvaluated.items(X,Z.items,K.items,G)))}mergeValidEvaluated(Z,G){const{it:K,gen:X}=this;if(K.opts.unevaluated&&(K.props!==!0||K.items!==!0))return X.if(G,()=>this.mergeEvaluated(Z,i.Name)),!0}}yr.KeywordCxt=$;function B(M,Z,G,K){const X=new $(M,G,Z);"code"in G?G.code(X,K):X.$data&&G.validate?(0,o.funcKeywordCode)(X,G):"macro"in G?(0,o.macroKeywordCode)(X,G):(G.compile||G.validate)&&(0,o.funcKeywordCode)(X,G)}const W=/^\/(?:[^~]|~0|~1)*$/,ye=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(M,{dataLevel:Z,dataNames:G,dataPathArr:K}){let X,ue;if(M==="")return l.default.rootData;if(M[0]==="/"){if(!W.test(M))throw new Error(`Invalid JSON-pointer: ${M}`);X=M,ue=l.default.rootData}else{const ee=ye.exec(M);if(!ee)throw new Error(`Invalid JSON-pointer: ${M}`);const be=+ee[1];if(X=ee[2],X==="#"){if(be>=Z)throw new Error(Je("property/index",be));return K[Z-be]}if(be>Z)throw new Error(Je("data",be));if(ue=G[Z-be],!X)return ue}let he=ue;const He=X.split("/");for(const ee of He)ee&&(ue=(0,i._)`${ue}${(0,i.getProperty)((0,u.unescapeJsonPointer)(ee))}`,he=(0,i._)`${he} && ${ue}`);return he;function Je(ee,be){return`Cannot access ${ee} ${be} levels up, current level is ${Z}`}}return yr.getData=pe,yr}var Ao={},Id;function Zi(){if(Id)return Ao;Id=1,Object.defineProperty(Ao,"__esModule",{value:!0});class t extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Ao.default=t,Ao}var Mo={},Rd;function No(){if(Rd)return Mo;Rd=1,Object.defineProperty(Mo,"__esModule",{value:!0});const t=Po();class e extends Error{constructor(n,s,o,a){super(a||`can't resolve reference ${o} from id ${s}`),this.missingRef=(0,t.resolveUrl)(n,s,o),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}}return Mo.default=e,Mo}var It={},Pd;function Fi(){if(Pd)return It;Pd=1,Object.defineProperty(It,"__esModule",{value:!0}),It.resolveSchema=It.getCompilingSchema=It.resolveRef=It.compileSchema=It.SchemaEnv=void 0;const t=$e(),e=Zi(),r=Nr(),n=Po(),s=Oe(),o=Oo();class a{constructor(y){var _;this.refs={},this.dynamicAnchors={};let g;typeof y.schema=="object"&&(g=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(_=y.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(g?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=g?.$async,this.refs={}}}It.SchemaEnv=a;function i(m){const y=u.call(this,m);if(y)return y;const _=(0,n.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:g,lines:b}=this.opts.code,{ownProperties:k}=this.opts,S=new t.CodeGen(this.scope,{es5:g,lines:b,ownProperties:k});let T;m.$async&&(T=S.scopeValue("Error",{ref:e.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));const x=S.scopeName("validate");m.validateName=x;const I={gen:S,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:S.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,t.stringify)(m.schema)}:{ref:m.schema}),validateName:x,ValidationError:T,schema:m.schema,schemaEnv:m,rootId:_,baseId:m.baseId||_,schemaPath:t.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this};let A;try{this._compilations.add(m),(0,o.validateFunctionCode)(I),S.optimize(this.opts.code.optimize);const P=S.toString();A=`${S.scopeRefs(r.default.scope)}return ${P}`,this.opts.code.process&&(A=this.opts.code.process(A,m));const U=new Function(`${r.default.self}`,`${r.default.scope}`,A)(this,this.scope.get());if(this.scope.value(x,{ref:U}),U.errors=null,U.schema=m.schema,U.schemaEnv=m,m.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:x,validateCode:P,scopeValues:S._values}),this.opts.unevaluated){const{props:V,items:se}=I;U.evaluated={props:V instanceof t.Name?void 0:V,items:se instanceof t.Name?void 0:se,dynamicProps:V instanceof t.Name,dynamicItems:se instanceof t.Name},U.source&&(U.source.evaluated=(0,t.stringify)(U.evaluated))}return m.validate=U,m}catch(P){throw delete m.validate,delete m.validateName,A&&this.logger.error("Error compiling schema, function code:",A),P}finally{this._compilations.delete(m)}}It.compileSchema=i;function l(m,y,_){var g;_=(0,n.resolveUrl)(this.opts.uriResolver,y,_);const b=m.refs[_];if(b)return b;let k=h.call(this,m,_);if(k===void 0){const S=(g=m.localRefs)===null||g===void 0?void 0:g[_],{schemaId:T}=this.opts;S&&(k=new a({schema:S,schemaId:T,root:m,baseId:y}))}if(k!==void 0)return m.refs[_]=c.call(this,k)}It.resolveRef=l;function c(m){return(0,n.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:i.call(this,m)}function u(m){for(const y of this._compilations)if(p(y,m))return y}It.getCompilingSchema=u;function p(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function h(m,y){let _;for(;typeof(_=this.refs[y])=="string";)y=_;return _||this.schemas[y]||d.call(this,m,y)}function d(m,y){const _=this.opts.uriResolver.parse(y),g=(0,n._getFullPath)(this.opts.uriResolver,_);let b=(0,n.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&g===b)return w.call(this,_,m);const k=(0,n.normalizeId)(g),S=this.refs[k]||this.schemas[k];if(typeof S=="string"){const T=d.call(this,m,S);return typeof T?.schema!="object"?void 0:w.call(this,_,T)}if(typeof S?.schema=="object"){if(S.validate||i.call(this,S),k===(0,n.normalizeId)(y)){const{schema:T}=S,{schemaId:x}=this.opts,I=T[x];return I&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,I)),new a({schema:T,schemaId:x,root:m,baseId:b})}return w.call(this,_,S)}}It.resolveSchema=d;const f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(m,{baseId:y,schema:_,root:g}){var b;if(((b=m.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const T of m.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const x=_[(0,s.unescapeFragment)(T)];if(x===void 0)return;_=x;const I=typeof _=="object"&&_[this.opts.schemaId];!f.has(T)&&I&&(y=(0,n.resolveUrl)(this.opts.uriResolver,y,I))}let k;if(typeof _!="boolean"&&_.$ref&&!(0,s.schemaHasRulesButRef)(_,this.RULES)){const T=(0,n.resolveUrl)(this.opts.uriResolver,y,_.$ref);k=d.call(this,g,T)}const{schemaId:S}=this.opts;if(k=k||new a({schema:_,schemaId:S,root:g,baseId:y}),k.schema!==k.root.schema)return k}return It}const x_={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Lo={},ps={exports:{}},Vi,Od;function Ad(){if(Od)return Vi;Od=1;const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),e=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(h){let d="",f=0,w=0;for(w=0;w<h.length;w++)if(f=h[w].charCodeAt(0),f!==48){if(!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[w];break}for(w+=1;w<h.length;w++){if(f=h[w].charCodeAt(0),!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[w]}return d}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(h){return h.length=0,!0}function o(h,d,f){if(h.length){const w=r(h);if(w!=="")d.push(w);else return f.error=!0,!1;h.length=0}return!0}function a(h){let d=0;const f={error:!1,address:"",zone:""},w=[],m=[];let y=!1,_=!1,g=o;for(let b=0;b<h.length;b++){const k=h[b];if(!(k==="["||k==="]"))if(k===":"){if(y===!0&&(_=!0),!g(m,w,f))break;if(++d>7){f.error=!0;break}b>0&&h[b-1]===":"&&(y=!0),w.push(":");continue}else if(k==="%"){if(!g(m,w,f))break;g=s}else{m.push(k);continue}}return m.length&&(g===s?f.zone=m.join(""):_?w.push(m.join("")):w.push(r(m))),f.address=w.join(""),f}function i(h){if(l(h,":")<2)return{host:h,isIPV6:!1};const d=a(h);if(d.error)return{host:h,isIPV6:!1};{let f=d.address,w=d.address;return d.zone&&(f+="%"+d.zone,w+="%25"+d.zone),{host:f,isIPV6:!0,escapedHost:w}}}function l(h,d){let f=0;for(let w=0;w<h.length;w++)h[w]===d&&f++;return f}function c(h){let d=h;const f=[];let w=-1,m=0;for(;m=d.length;){if(m===1){if(d===".")break;if(d==="/"){f.push("/");break}else{f.push(d);break}}else if(m===2){if(d[0]==="."){if(d[1]===".")break;if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&(d[1]==="."||d[1]==="/")){f.push("/");break}}else if(m===3&&d==="/.."){f.length!==0&&f.pop(),f.push("/");break}if(d[0]==="."){if(d[1]==="."){if(d[2]==="/"){d=d.slice(3);continue}}else if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&d[1]==="."){if(d[2]==="/"){d=d.slice(2);continue}else if(d[2]==="."&&d[3]==="/"){d=d.slice(3),f.length!==0&&f.pop();continue}}if((w=d.indexOf("/",1))===-1){f.push(d);break}else f.push(d.slice(0,w)),d=d.slice(w)}return f.join("")}function u(h,d){const f=d!==!0?escape:unescape;return h.scheme!==void 0&&(h.scheme=f(h.scheme)),h.userinfo!==void 0&&(h.userinfo=f(h.userinfo)),h.host!==void 0&&(h.host=f(h.host)),h.path!==void 0&&(h.path=f(h.path)),h.query!==void 0&&(h.query=f(h.query)),h.fragment!==void 0&&(h.fragment=f(h.fragment)),h}function p(h){const d=[];if(h.userinfo!==void 0&&(d.push(h.userinfo),d.push("@")),h.host!==void 0){let f=unescape(h.host);if(!e(f)){const w=i(f);w.isIPV6===!0?f=`[${w.escapedHost}]`:f=h.host}d.push(f)}return(typeof h.port=="number"||typeof h.port=="string")&&(d.push(":"),d.push(String(h.port))),d.length?d.join(""):void 0}return Vi={nonSimpleDomain:n,recomposeAuthority:p,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:e,isUUID:t,normalizeIPv6:i,stringArrayToHexStripped:r},Vi}var Hi,Md;function I_(){if(Md)return Hi;Md=1;const{isUUID:t}=Ad(),e=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function s(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function o(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const S=String(k.scheme).toLowerCase()==="https";return(k.port===(S?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=s(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function l(k){if((k.port===(s(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[S,T]=k.resourceName.split("?");k.path=S&&S!=="/"?S:void 0,k.query=T,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,S){if(!k.path)return k.error="URN can not be parsed",k;const T=k.path.match(e);if(T){const x=S.scheme||k.scheme||"urn";k.nid=T[1].toLowerCase(),k.nss=T[2];const I=`${x}:${S.nid||k.nid}`,A=b(I);k.path=void 0,A&&(k=A.parse(k,S))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,S){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const T=S.scheme||k.scheme||"urn",x=k.nid.toLowerCase(),I=`${T}:${S.nid||x}`,A=b(I);A&&(k=A.serialize(k,S));const P=k,D=k.nss;return P.path=`${x||S.nid}:${D}`,S.skipEscape=!0,P}function p(k,S){const T=k;return T.uuid=T.nss,T.nss=void 0,!S.tolerant&&(!T.uuid||!t(T.uuid))&&(T.error=T.error||"UUID is not valid."),T}function h(k){const S=k;return S.nss=(k.uuid||"").toLowerCase(),S}const d={scheme:"http",domainHost:!0,parse:o,serialize:a},f={scheme:"https",domainHost:d.domainHost,parse:o,serialize:a},w={scheme:"ws",domainHost:!0,parse:i,serialize:l},m={scheme:"wss",domainHost:w.domainHost,parse:w.parse,serialize:w.serialize},g={http:d,https:f,ws:w,wss:m,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:p,serialize:h,skipNormalize:!0}};Object.setPrototypeOf(g,null);function b(k){return k&&(g[k]||g[k.toLowerCase()])||void 0}return Hi={wsIsSecure:s,SCHEMES:g,isValidSchemeName:n,getSchemeHandler:b},Hi}var Nd;function R_(){if(Nd)return ps.exports;Nd=1;const{normalizeIPv6:t,removeDotSegments:e,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:s,nonSimpleDomain:o}=Ad(),{SCHEMES:a,getSchemeHandler:i}=I_();function l(m,y){return typeof m=="string"?m=h(f(m,y),y):typeof m=="object"&&(m=f(h(m,y),y)),m}function c(m,y,_){const g=_?Object.assign({scheme:"null"},_):{scheme:"null"},b=u(f(m,g),f(y,g),g,!0);return g.skipEscape=!0,h(b,g)}function u(m,y,_,g){const b={};return g||(m=f(h(m,_),_),y=f(h(y,_),_)),_=_||{},!_.tolerant&&y.scheme?(b.scheme=y.scheme,b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=e(y.path||""),b.query=y.query):(y.userinfo!==void 0||y.host!==void 0||y.port!==void 0?(b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=e(y.path||""),b.query=y.query):(y.path?(y.path[0]==="/"?b.path=e(y.path):((m.userinfo!==void 0||m.host!==void 0||m.port!==void 0)&&!m.path?b.path="/"+y.path:m.path?b.path=m.path.slice(0,m.path.lastIndexOf("/")+1)+y.path:b.path=y.path,b.path=e(b.path)),b.query=y.query):(b.path=m.path,y.query!==void 0?b.query=y.query:b.query=m.query),b.userinfo=m.userinfo,b.host=m.host,b.port=m.port),b.scheme=m.scheme),b.fragment=y.fragment,b}function p(m,y,_){return typeof m=="string"?(m=unescape(m),m=h(n(f(m,_),!0),{..._,skipEscape:!0})):typeof m=="object"&&(m=h(n(m,!0),{..._,skipEscape:!0})),typeof y=="string"?(y=unescape(y),y=h(n(f(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=h(n(y,!0),{..._,skipEscape:!0})),m.toLowerCase()===y.toLowerCase()}function h(m,y){const _={host:m.host,scheme:m.scheme,userinfo:m.userinfo,port:m.port,path:m.path,query:m.query,nid:m.nid,nss:m.nss,uuid:m.uuid,fragment:m.fragment,reference:m.reference,resourceName:m.resourceName,secure:m.secure,error:""},g=Object.assign({},y),b=[],k=i(g.scheme||_.scheme);k&&k.serialize&&k.serialize(_,g),_.path!==void 0&&(g.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),g.reference!=="suffix"&&_.scheme&&b.push(_.scheme,":");const S=r(_);if(S!==void 0&&(g.reference!=="suffix"&&b.push("//"),b.push(S),_.path&&_.path[0]!=="/"&&b.push("/")),_.path!==void 0){let T=_.path;!g.absolutePath&&(!k||!k.absolutePath)&&(T=e(T)),S===void 0&&T[0]==="/"&&T[1]==="/"&&(T="/%2F"+T.slice(2)),b.push(T)}return _.query!==void 0&&b.push("?",_.query),_.fragment!==void 0&&b.push("#",_.fragment),b.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f(m,y){const _=Object.assign({},y),g={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;_.reference==="suffix"&&(_.scheme?m=_.scheme+":"+m:m="//"+m);const k=m.match(d);if(k){if(g.scheme=k[1],g.userinfo=k[3],g.host=k[4],g.port=parseInt(k[5],10),g.path=k[6]||"",g.query=k[7],g.fragment=k[8],isNaN(g.port)&&(g.port=k[5]),g.host)if(s(g.host)===!1){const x=t(g.host);g.host=x.host.toLowerCase(),b=x.isIPV6}else b=!0;g.scheme===void 0&&g.userinfo===void 0&&g.host===void 0&&g.port===void 0&&g.query===void 0&&!g.path?g.reference="same-document":g.scheme===void 0?g.reference="relative":g.fragment===void 0?g.reference="absolute":g.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==g.reference&&(g.error=g.error||"URI is not a "+_.reference+" reference.");const S=i(_.scheme||g.scheme);if(!_.unicodeSupport&&(!S||!S.unicodeSupport)&&g.host&&(_.domainHost||S&&S.domainHost)&&b===!1&&o(g.host))try{g.host=URL.domainToASCII(g.host.toLowerCase())}catch(T){g.error=g.error||"Host's domain name can not be converted to ASCII: "+T}(!S||S&&!S.skipNormalize)&&(m.indexOf("%")!==-1&&(g.scheme!==void 0&&(g.scheme=unescape(g.scheme)),g.host!==void 0&&(g.host=unescape(g.host))),g.path&&(g.path=escape(unescape(g.path))),g.fragment&&(g.fragment=encodeURI(decodeURIComponent(g.fragment)))),S&&S.parse&&S.parse(g,_)}else g.error=g.error||"URI can not be parsed.";return g}const w={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:p,serialize:h,parse:f};return ps.exports=w,ps.exports.default=w,ps.exports.fastUri=w,ps.exports}var Ld;function P_(){if(Ld)return Lo;Ld=1,Object.defineProperty(Lo,"__esModule",{value:!0});const t=R_();return t.code='require("ajv/dist/runtime/uri").default',Lo.default=t,Lo}var jd;function O_(){return jd||(jd=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=Oo();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=$e();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Zi(),s=No(),o=gd(),a=Fi(),i=$e(),l=Po(),c=Ro(),u=Oe(),p=x_,h=P_(),d=(H,O)=>new RegExp(H,O);d.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],w=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function g(H){var O,F,q,E,R,$,B,W,ye,pe,M,Z,G,K,X,ue,he,He,Je,ee,be,yt,xe,Et,Pr;const xt=H.strict,it=(O=H.code)===null||O===void 0?void 0:O.optimize,Ut=it===!0||it===void 0?1:it||0,Xr=(q=(F=H.code)===null||F===void 0?void 0:F.regExp)!==null&&q!==void 0?q:d,en=(E=H.uriResolver)!==null&&E!==void 0?E:h.default;return{strictSchema:($=(R=H.strictSchema)!==null&&R!==void 0?R:xt)!==null&&$!==void 0?$:!0,strictNumbers:(W=(B=H.strictNumbers)!==null&&B!==void 0?B:xt)!==null&&W!==void 0?W:!0,strictTypes:(pe=(ye=H.strictTypes)!==null&&ye!==void 0?ye:xt)!==null&&pe!==void 0?pe:"log",strictTuples:(Z=(M=H.strictTuples)!==null&&M!==void 0?M:xt)!==null&&Z!==void 0?Z:"log",strictRequired:(K=(G=H.strictRequired)!==null&&G!==void 0?G:xt)!==null&&K!==void 0?K:!1,code:H.code?{...H.code,optimize:Ut,regExp:Xr}:{optimize:Ut,regExp:Xr},loopRequired:(X=H.loopRequired)!==null&&X!==void 0?X:_,loopEnum:(ue=H.loopEnum)!==null&&ue!==void 0?ue:_,meta:(he=H.meta)!==null&&he!==void 0?he:!0,messages:(He=H.messages)!==null&&He!==void 0?He:!0,inlineRefs:(Je=H.inlineRefs)!==null&&Je!==void 0?Je:!0,schemaId:(ee=H.schemaId)!==null&&ee!==void 0?ee:"$id",addUsedSchema:(be=H.addUsedSchema)!==null&&be!==void 0?be:!0,validateSchema:(yt=H.validateSchema)!==null&&yt!==void 0?yt:!0,validateFormats:(xe=H.validateFormats)!==null&&xe!==void 0?xe:!0,unicodeRegExp:(Et=H.unicodeRegExp)!==null&&Et!==void 0?Et:!0,int32range:(Pr=H.int32range)!==null&&Pr!==void 0?Pr:!0,uriResolver:en}}class b{constructor(O={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,O=this.opts={...O,...g(O)};const{es5:F,lines:q}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:w,es5:F,lines:q}),this.logger=D(O.logger);const E=O.validateFormats;O.validateFormats=!1,this.RULES=(0,o.getRules)(),k.call(this,m,O,"NOT SUPPORTED"),k.call(this,y,O,"DEPRECATED","warn"),this._metaOpts=A.call(this),O.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),O.keywords&&I.call(this,O.keywords),typeof O.meta=="object"&&this.addMetaSchema(O.meta),T.call(this),O.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:O,meta:F,schemaId:q}=this.opts;let E=p;q==="id"&&(E={...p},E.id=E.$id,delete E.$id),F&&O&&this.addMetaSchema(E,E[q],!1)}defaultMeta(){const{meta:O,schemaId:F}=this.opts;return this.opts.defaultMeta=typeof O=="object"?O[F]||O:void 0}validate(O,F){let q;if(typeof O=="string"){if(q=this.getSchema(O),!q)throw new Error(`no schema with key or ref "${O}"`)}else q=this.compile(O);const E=q(F);return"$async"in q||(this.errors=q.errors),E}compile(O,F){const q=this._addSchema(O,F);return q.validate||this._compileSchemaEnv(q)}compileAsync(O,F){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:q}=this.opts;return E.call(this,O,F);async function E(pe,M){await R.call(this,pe.$schema);const Z=this._addSchema(pe,M);return Z.validate||$.call(this,Z)}async function R(pe){pe&&!this.getSchema(pe)&&await E.call(this,{$ref:pe},!0)}async function $(pe){try{return this._compileSchemaEnv(pe)}catch(M){if(!(M instanceof s.default))throw M;return B.call(this,M),await W.call(this,M.missingSchema),$.call(this,pe)}}function B({missingSchema:pe,missingRef:M}){if(this.refs[pe])throw new Error(`AnySchema ${pe} is loaded but ${M} cannot be resolved`)}async function W(pe){const M=await ye.call(this,pe);this.refs[pe]||await R.call(this,M.$schema),this.refs[pe]||this.addSchema(M,pe,F)}async function ye(pe){const M=this._loading[pe];if(M)return M;try{return await(this._loading[pe]=q(pe))}finally{delete this._loading[pe]}}}addSchema(O,F,q,E=this.opts.validateSchema){if(Array.isArray(O)){for(const $ of O)this.addSchema($,void 0,q,E);return this}let R;if(typeof O=="object"){const{schemaId:$}=this.opts;if(R=O[$],R!==void 0&&typeof R!="string")throw new Error(`schema ${$} must be string`)}return F=(0,l.normalizeId)(F||R),this._checkUnique(F),this.schemas[F]=this._addSchema(O,q,F,E,!0),this}addMetaSchema(O,F,q=this.opts.validateSchema){return this.addSchema(O,F,!0,q),this}validateSchema(O,F){if(typeof O=="boolean")return!0;let q;if(q=O.$schema,q!==void 0&&typeof q!="string")throw new Error("$schema must be a string");if(q=q||this.opts.defaultMeta||this.defaultMeta(),!q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(q,O);if(!E&&F){const R="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(R);else throw new Error(R)}return E}getSchema(O){let F;for(;typeof(F=S.call(this,O))=="string";)O=F;if(F===void 0){const{schemaId:q}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:q});if(F=a.resolveSchema.call(this,E,O),!F)return;this.refs[O]=F}return F.validate||this._compileSchemaEnv(F)}removeSchema(O){if(O instanceof RegExp)return this._removeAllSchemas(this.schemas,O),this._removeAllSchemas(this.refs,O),this;switch(typeof O){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const F=S.call(this,O);return typeof F=="object"&&this._cache.delete(F.schema),delete this.schemas[O],delete this.refs[O],this}case"object":{const F=O;this._cache.delete(F);let q=O[this.opts.schemaId];return q&&(q=(0,l.normalizeId)(q),delete this.schemas[q],delete this.refs[q]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(O){for(const F of O)this.addKeyword(F);return this}addKeyword(O,F){let q;if(typeof O=="string")q=O,typeof F=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),F.keyword=q);else if(typeof O=="object"&&F===void 0){if(F=O,q=F.keyword,Array.isArray(q)&&!q.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(V.call(this,q,F),!F)return(0,u.eachItem)(q,R=>se.call(this,R)),this;de.call(this,F);const E={...F,type:(0,c.getJSONTypes)(F.type),schemaType:(0,c.getJSONTypes)(F.schemaType)};return(0,u.eachItem)(q,E.type.length===0?R=>se.call(this,R,E):R=>E.type.forEach($=>se.call(this,R,E,$))),this}getKeyword(O){const F=this.RULES.all[O];return typeof F=="object"?F.definition:!!F}removeKeyword(O){const{RULES:F}=this;delete F.keywords[O],delete F.all[O];for(const q of F.rules){const E=q.rules.findIndex(R=>R.keyword===O);E>=0&&q.rules.splice(E,1)}return this}addFormat(O,F){return typeof F=="string"&&(F=new RegExp(F)),this.formats[O]=F,this}errorsText(O=this.errors,{separator:F=", ",dataVar:q="data"}={}){return!O||O.length===0?"No errors":O.map(E=>`${q}${E.instancePath} ${E.message}`).reduce((E,R)=>E+F+R)}$dataMetaSchema(O,F){const q=this.RULES.all;O=JSON.parse(JSON.stringify(O));for(const E of F){const R=E.split("/").slice(1);let $=O;for(const B of R)$=$[B];for(const B in q){const W=q[B];if(typeof W!="object")continue;const{$data:ye}=W.definition,pe=$[B];ye&&pe&&($[B]=_e(pe))}}return O}_removeAllSchemas(O,F){for(const q in O){const E=O[q];(!F||F.test(q))&&(typeof E=="string"?delete O[q]:E&&!E.meta&&(this._cache.delete(E.schema),delete O[q]))}}_addSchema(O,F,q,E=this.opts.validateSchema,R=this.opts.addUsedSchema){let $;const{schemaId:B}=this.opts;if(typeof O=="object")$=O[B];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof O!="boolean")throw new Error("schema must be object or boolean")}let W=this._cache.get(O);if(W!==void 0)return W;q=(0,l.normalizeId)($||q);const ye=l.getSchemaRefs.call(this,O,q);return W=new a.SchemaEnv({schema:O,schemaId:B,meta:F,baseId:q,localRefs:ye}),this._cache.set(W.schema,W),R&&!q.startsWith("#")&&(q&&this._checkUnique(q),this.refs[q]=W),E&&this.validateSchema(O,!0),W}_checkUnique(O){if(this.schemas[O]||this.refs[O])throw new Error(`schema with key or id "${O}" already exists`)}_compileSchemaEnv(O){if(O.meta?this._compileMetaSchema(O):a.compileSchema.call(this,O),!O.validate)throw new Error("ajv implementation error");return O.validate}_compileMetaSchema(O){const F=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,O)}finally{this.opts=F}}}b.ValidationError=n.default,b.MissingRefError=s.default,t.default=b;function k(H,O,F,q="error"){for(const E in H){const R=E;R in O&&this.logger[q](`${F}: option ${E}. ${H[R]}`)}}function S(H){return H=(0,l.normalizeId)(H),this.schemas[H]||this.refs[H]}function T(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const O in H)this.addSchema(H[O],O)}function x(){for(const H in this.opts.formats){const O=this.opts.formats[H];O&&this.addFormat(H,O)}}function I(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const O in H){const F=H[O];F.keyword||(F.keyword=O),this.addKeyword(F)}}function A(){const H={...this.opts};for(const O of f)delete H[O];return H}const P={log(){},warn(){},error(){}};function D(H){if(H===!1)return P;if(H===void 0)return console;if(H.log&&H.warn&&H.error)return H;throw new Error("logger must implement log, warn and error methods")}const U=/^[a-z_$][a-z0-9_$:-]*$/i;function V(H,O){const{RULES:F}=this;if((0,u.eachItem)(H,q=>{if(F.keywords[q])throw new Error(`Keyword ${q} is already defined`);if(!U.test(q))throw new Error(`Keyword ${q} has invalid name`)}),!!O&&O.$data&&!("code"in O||"validate"in O))throw new Error('$data keyword must have "code" or "validate" function')}function se(H,O,F){var q;const E=O?.post;if(F&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:R}=this;let $=E?R.post:R.rules.find(({type:W})=>W===F);if($||($={type:F,rules:[]},R.rules.push($)),R.keywords[H]=!0,!O)return;const B={keyword:H,definition:{...O,type:(0,c.getJSONTypes)(O.type),schemaType:(0,c.getJSONTypes)(O.schemaType)}};O.before?fe.call(this,$,B,O.before):$.rules.push(B),R.all[H]=B,(q=O.implements)===null||q===void 0||q.forEach(W=>this.addKeyword(W))}function fe(H,O,F){const q=H.rules.findIndex(E=>E.keyword===F);q>=0?H.rules.splice(q,0,O):(H.rules.push(O),this.logger.warn(`rule ${F} is not defined`))}function de(H){let{metaSchema:O}=H;O!==void 0&&(H.$data&&this.opts.$data&&(O=_e(O)),H.validateSchema=this.compile(O,!0))}const re={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _e(H){return{anyOf:[H,re]}}})(Ni)),Ni}var jo={},qo={},zo={},qd;function A_(){if(qd)return zo;qd=1,Object.defineProperty(zo,"__esModule",{value:!0});const t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return zo.default=t,zo}var Lr={},zd;function M_(){if(zd)return Lr;zd=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.callRef=Lr.getValidate=void 0;const t=No(),e=Ft(),r=$e(),n=Nr(),s=Fi(),o=Oe(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:p,it:h}=c,{baseId:d,schemaEnv:f,validateName:w,opts:m,self:y}=h,{root:_}=f;if((p==="#"||p==="#/")&&d===_.baseId)return b();const g=s.resolveRef.call(y,_,d,p);if(g===void 0)throw new t.default(h.opts.uriResolver,d,p);if(g instanceof s.SchemaEnv)return k(g);return S(g);function b(){if(f===_)return l(c,w,f,f.$async);const T=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${T}.validate`,_,_.$async)}function k(T){const x=i(c,T);l(c,x,T,T.$async)}function S(T){const x=u.scopeValue("schema",m.code.source===!0?{ref:T,code:(0,r.stringify)(T)}:{ref:T}),I=u.name("valid"),A=c.subschema({schema:T,dataTypes:[],schemaPath:r.nil,topSchemaRef:x,errSchemaPath:p},I);c.mergeEvaluated(A),c.ok(I)}}};function i(c,u){const{gen:p}=c;return u.validate?p.scopeValue("validate",{ref:u.validate}):(0,r._)`${p.scopeValue("wrapper",{ref:u})}.validate`}Lr.getValidate=i;function l(c,u,p,h){const{gen:d,it:f}=c,{allErrors:w,schemaEnv:m,opts:y}=f,_=y.passContext?n.default.this:r.nil;h?g():b();function g(){if(!m.$async)throw new Error("async schema referenced by sync schema");const T=d.let("valid");d.try(()=>{d.code((0,r._)`await ${(0,e.callValidateCode)(c,u,_)}`),S(u),w||d.assign(T,!0)},x=>{d.if((0,r._)`!(${x} instanceof ${f.ValidationError})`,()=>d.throw(x)),k(x),w||d.assign(T,!1)}),c.ok(T)}function b(){c.result((0,e.callValidateCode)(c,u,_),()=>S(u),()=>k(u))}function k(T){const x=(0,r._)`${T}.errors`;d.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${x} : ${n.default.vErrors}.concat(${x})`),d.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function S(T){var x;if(!f.opts.unevaluated)return;const I=(x=p?.validate)===null||x===void 0?void 0:x.evaluated;if(f.props!==!0)if(I&&!I.dynamicProps)I.props!==void 0&&(f.props=o.mergeEvaluated.props(d,I.props,f.props));else{const A=d.var("props",(0,r._)`${T}.evaluated.props`);f.props=o.mergeEvaluated.props(d,A,f.props,r.Name)}if(f.items!==!0)if(I&&!I.dynamicItems)I.items!==void 0&&(f.items=o.mergeEvaluated.items(d,I.items,f.items));else{const A=d.var("items",(0,r._)`${T}.evaluated.items`);f.items=o.mergeEvaluated.items(d,A,f.items,r.Name)}}}return Lr.callRef=l,Lr.default=a,Lr}var Dd;function N_(){if(Dd)return qo;Dd=1,Object.defineProperty(qo,"__esModule",{value:!0});const t=A_(),e=M_(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,e.default];return qo.default=r,qo}var Do={},Uo={},Ud;function L_(){if(Ud)return Uo;Ud=1,Object.defineProperty(Uo,"__esModule",{value:!0});const t=$e(),e=t.operators,r={maximum:{okStr:"<=",ok:e.LTE,fail:e.GT},minimum:{okStr:">=",ok:e.GTE,fail:e.LT},exclusiveMaximum:{okStr:"<",ok:e.LT,fail:e.GTE},exclusiveMinimum:{okStr:">",ok:e.GT,fail:e.LTE}},n={message:({keyword:o,schemaCode:a})=>(0,t.str)`must be ${r[o].okStr} ${a}`,params:({keyword:o,schemaCode:a})=>(0,t._)`{comparison: ${r[o].okStr}, limit: ${a}}`},s={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(o){const{keyword:a,data:i,schemaCode:l}=o;o.fail$data((0,t._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return Uo.default=s,Uo}var Zo={},Zd;function j_(){if(Zd)return Zo;Zd=1,Object.defineProperty(Zo,"__esModule",{value:!0});const t=$e(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){const{gen:s,data:o,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=s.let("res"),u=l?(0,t._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,t._)`${c} !== parseInt(${c})`;n.fail$data((0,t._)`(${a} === 0 || (${c} = ${o}/${a}, ${u}))`)}};return Zo.default=r,Zo}var Fo={},Vo={},Fd;function q_(){if(Fd)return Vo;Fd=1,Object.defineProperty(Vo,"__esModule",{value:!0});function t(e){const r=e.length;let n=0,s=0,o;for(;s<r;)n++,o=e.charCodeAt(s++),o>=55296&&o<=56319&&s<r&&(o=e.charCodeAt(s),(o&64512)===56320&&s++);return n}return Vo.default=t,t.code='require("ajv/dist/runtime/ucs2length").default',Vo}var Vd;function z_(){if(Vd)return Fo;Vd=1,Object.defineProperty(Fo,"__esModule",{value:!0});const t=$e(),e=Oe(),r=q_(),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:o,schemaCode:a}){const i=o==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:o})=>(0,t._)`{limit: ${o}}`},code(o){const{keyword:a,data:i,schemaCode:l,it:c}=o,u=a==="maxLength"?t.operators.GT:t.operators.LT,p=c.opts.unicode===!1?(0,t._)`${i}.length`:(0,t._)`${(0,e.useFunc)(o.gen,r.default)}(${i})`;o.fail$data((0,t._)`${p} ${u} ${l}`)}};return Fo.default=s,Fo}var Ho={},Hd;function D_(){if(Hd)return Ho;Hd=1,Object.defineProperty(Ho,"__esModule",{value:!0});const t=Ft(),e=$e(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,e.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,e._)`{pattern: ${s}}`},code(s){const{data:o,$data:a,schema:i,schemaCode:l,it:c}=s,u=c.opts.unicodeRegExp?"u":"",p=a?(0,e._)`(new RegExp(${l}, ${u}))`:(0,t.usePattern)(s,i);s.fail$data((0,e._)`!${p}.test(${o})`)}};return Ho.default=n,Ho}var Bo={},Bd;function U_(){if(Bd)return Bo;Bd=1,Object.defineProperty(Bo,"__esModule",{value:!0});const t=$e(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${o}).length ${i} ${a}`)}};return Bo.default=r,Bo}var Jo={},Jd;function Z_(){if(Jd)return Jo;Jd=1,Object.defineProperty(Jo,"__esModule",{value:!0});const t=Ft(),e=$e(),r=Oe(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:o}})=>(0,e.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,e._)`{missingProperty: ${o}}`},code(o){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:p}=o,{opts:h}=p;if(!u&&i.length===0)return;const d=i.length>=h.loopRequired;if(p.allErrors?f():w(),h.strictRequired){const _=o.parentSchema.properties,{definedProperties:g}=o.it;for(const b of i)if(_?.[b]===void 0&&!g.has(b)){const k=p.schemaEnv.baseId+p.errSchemaPath,S=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(p,S,p.opts.strictRequired)}}function f(){if(d||u)o.block$data(e.nil,m);else for(const _ of i)(0,t.checkReportMissingProp)(o,_)}function w(){const _=a.let("missing");if(d||u){const g=a.let("valid",!0);o.block$data(g,()=>y(_,g)),o.ok(g)}else a.if((0,t.checkMissingProp)(o,i,_)),(0,t.reportMissingProp)(o,_),a.else()}function m(){a.forOf("prop",l,_=>{o.setParams({missingProperty:_}),a.if((0,t.noPropertyInData)(a,c,_,h.ownProperties),()=>o.error())})}function y(_,g){o.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(g,(0,t.propertyInData)(a,c,_,h.ownProperties)),a.if((0,e.not)(g),()=>{o.error(),a.break()})},e.nil)}}};return Jo.default=s,Jo}var Go={},Gd;function F_(){if(Gd)return Go;Gd=1,Object.defineProperty(Go,"__esModule",{value:!0});const t=$e(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${o}.length ${i} ${a}`)}};return Go.default=r,Go}var Wo={},Ko={},Wd;function Bi(){if(Wd)return Ko;Wd=1,Object.defineProperty(Ko,"__esModule",{value:!0});const t=Cd();return t.code='require("ajv/dist/runtime/equal").default',Ko.default=t,Ko}var Kd;function V_(){if(Kd)return Wo;Kd=1,Object.defineProperty(Wo,"__esModule",{value:!0});const t=Ro(),e=$e(),r=Oe(),n=Bi(),o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,e.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,e._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:p,schemaCode:h,it:d}=a;if(!c&&!u)return;const f=i.let("valid"),w=p.items?(0,t.getSchemaTypes)(p.items):[];a.block$data(f,m,(0,e._)`${h} === false`),a.ok(f);function m(){const b=i.let("i",(0,e._)`${l}.length`),k=i.let("j");a.setParams({i:b,j:k}),i.assign(f,!0),i.if((0,e._)`${b} > 1`,()=>(y()?_:g)(b,k))}function y(){return w.length>0&&!w.some(b=>b==="object"||b==="array")}function _(b,k){const S=i.name("item"),T=(0,t.checkDataTypes)(w,S,d.opts.strictNumbers,t.DataType.Wrong),x=i.const("indices",(0,e._)`{}`);i.for((0,e._)`;${b}--;`,()=>{i.let(S,(0,e._)`${l}[${b}]`),i.if(T,(0,e._)`continue`),w.length>1&&i.if((0,e._)`typeof ${S} == "string"`,(0,e._)`${S} += "_"`),i.if((0,e._)`typeof ${x}[${S}] == "number"`,()=>{i.assign(k,(0,e._)`${x}[${S}]`),a.error(),i.assign(f,!1).break()}).code((0,e._)`${x}[${S}] = ${b}`)})}function g(b,k){const S=(0,r.useFunc)(i,n.default),T=i.name("outer");i.label(T).for((0,e._)`;${b}--;`,()=>i.for((0,e._)`${k} = ${b}; ${k}--;`,()=>i.if((0,e._)`${S}(${l}[${b}], ${l}[${k}])`,()=>{a.error(),i.assign(f,!1).break(T)})))}}};return Wo.default=o,Wo}var Yo={},Yd;function H_(){if(Yd)return Yo;Yd=1,Object.defineProperty(Yo,"__esModule",{value:!0});const t=$e(),e=Oe(),r=Bi(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:o})=>(0,t._)`{allowedValue: ${o}}`},code(o){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=o;l||u&&typeof u=="object"?o.fail$data((0,t._)`!${(0,e.useFunc)(a,r.default)}(${i}, ${c})`):o.fail((0,t._)`${u} !== ${i}`)}};return Yo.default=s,Yo}var Qo={},Qd;function B_(){if(Qd)return Qo;Qd=1,Object.defineProperty(Qo,"__esModule",{value:!0});const t=$e(),e=Oe(),r=Bi(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,t._)`{allowedValues: ${o}}`},code(o){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:p}=o;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const h=c.length>=p.opts.loopEnum;let d;const f=()=>d??(d=(0,e.useFunc)(a,r.default));let w;if(h||l)w=a.let("valid"),o.block$data(w,m);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);w=(0,t.or)(...c.map((g,b)=>y(_,b)))}o.pass(w);function m(){a.assign(w,!1),a.forOf("v",u,_=>a.if((0,t._)`${f()}(${i}, ${_})`,()=>a.assign(w,!0).break()))}function y(_,g){const b=c[g];return typeof b=="object"&&b!==null?(0,t._)`${f()}(${i}, ${_}[${g}])`:(0,t._)`${i} === ${b}`}}};return Qo.default=s,Qo}var Xd;function J_(){if(Xd)return Do;Xd=1,Object.defineProperty(Do,"__esModule",{value:!0});const t=L_(),e=j_(),r=z_(),n=D_(),s=U_(),o=Z_(),a=F_(),i=V_(),l=H_(),c=B_(),u=[t.default,e.default,r.default,n.default,s.default,o.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return Do.default=u,Do}var Xo={},$n={},ep;function tp(){if(ep)return $n;ep=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.validateAdditionalItems=void 0;const t=$e(),e=Oe(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){const{parentSchema:a,it:i}=o,{items:l}=a;if(!Array.isArray(l)){(0,e.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}s(o,l)}};function s(o,a){const{gen:i,schema:l,data:c,keyword:u,it:p}=o;p.items=!0;const h=i.const("len",(0,t._)`${c}.length`);if(l===!1)o.setParams({len:a.length}),o.pass((0,t._)`${h} <= ${a.length}`);else if(typeof l=="object"&&!(0,e.alwaysValidSchema)(p,l)){const f=i.var("valid",(0,t._)`${h} <= ${a.length}`);i.if((0,t.not)(f),()=>d(f)),o.ok(f)}function d(f){i.forRange("i",a.length,h,w=>{o.subschema({keyword:u,dataProp:w,dataPropType:e.Type.Num},f),p.allErrors||i.if((0,t.not)(f),()=>i.break())})}}return $n.validateAdditionalItems=s,$n.default=n,$n}var ea={},En={},rp;function np(){if(rp)return En;rp=1,Object.defineProperty(En,"__esModule",{value:!0}),En.validateTuple=void 0;const t=$e(),e=Oe(),r=Ft(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){const{schema:a,it:i}=o;if(Array.isArray(a))return s(o,"additionalItems",a);i.items=!0,!(0,e.alwaysValidSchema)(i,a)&&o.ok((0,r.validateArray)(o))}};function s(o,a,i=o.schema){const{gen:l,parentSchema:c,data:u,keyword:p,it:h}=o;w(c),h.opts.unevaluated&&i.length&&h.items!==!0&&(h.items=e.mergeEvaluated.items(l,i.length,h.items));const d=l.name("valid"),f=l.const("len",(0,t._)`${u}.length`);i.forEach((m,y)=>{(0,e.alwaysValidSchema)(h,m)||(l.if((0,t._)`${f} > ${y}`,()=>o.subschema({keyword:p,schemaProp:y,dataProp:y},d)),o.ok(d))});function w(m){const{opts:y,errSchemaPath:_}=h,g=i.length,b=g===m.minItems&&(g===m.maxItems||m[a]===!1);if(y.strictTuples&&!b){const k=`"${p}" is ${g}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,e.checkStrictMode)(h,k,y.strictTuples)}}}return En.validateTuple=s,En.default=n,En}var sp;function G_(){if(sp)return ea;sp=1,Object.defineProperty(ea,"__esModule",{value:!0});const t=np(),e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,t.validateTuple)(r,"items")};return ea.default=e,ea}var ta={},op;function W_(){if(op)return ta;op=1,Object.defineProperty(ta,"__esModule",{value:!0});const t=$e(),e=Oe(),r=Ft(),n=tp(),o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,e.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return ta.default=o,ta}var ra={},ap;function K_(){if(ap)return ra;ap=1,Object.defineProperty(ra,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:s,max:o}})=>o===void 0?(0,t.str)`must contain at least ${s} valid item(s)`:(0,t.str)`must contain at least ${s} and no more than ${o} valid item(s)`,params:({params:{min:s,max:o}})=>o===void 0?(0,t._)`{minContains: ${s}}`:(0,t._)`{minContains: ${s}, maxContains: ${o}}`},code(s){const{gen:o,schema:a,parentSchema:i,data:l,it:c}=s;let u,p;const{minContains:h,maxContains:d}=i;c.opts.next?(u=h===void 0?1:h,p=d):u=1;const f=o.const("len",(0,t._)`${l}.length`);if(s.setParams({min:u,max:p}),p===void 0&&u===0){(0,e.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(p!==void 0&&u>p){(0,e.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),s.fail();return}if((0,e.alwaysValidSchema)(c,a)){let g=(0,t._)`${f} >= ${u}`;p!==void 0&&(g=(0,t._)`${g} && ${f} <= ${p}`),s.pass(g);return}c.items=!0;const w=o.name("valid");p===void 0&&u===1?y(w,()=>o.if(w,()=>o.break())):u===0?(o.let(w,!0),p!==void 0&&o.if((0,t._)`${l}.length > 0`,m)):(o.let(w,!1),m()),s.result(w,()=>s.reset());function m(){const g=o.name("_valid"),b=o.let("count",0);y(g,()=>o.if(g,()=>_(b)))}function y(g,b){o.forRange("i",0,f,k=>{s.subschema({keyword:"contains",dataProp:k,dataPropType:e.Type.Num,compositeRule:!0},g),b()})}function _(g){o.code((0,t._)`${g}++`),p===void 0?o.if((0,t._)`${g} >= ${u}`,()=>o.assign(w,!0).break()):(o.if((0,t._)`${g} > ${p}`,()=>o.assign(w,!1).break()),u===1?o.assign(w,!0):o.if((0,t._)`${g} >= ${u}`,()=>o.assign(w,!0)))}}};return ra.default=n,ra}var Ji={},ip;function Y_(){return ip||(ip=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=$e(),r=Oe(),n=Ft();t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const p=c===1?"property":"properties";return(0,e.str)`must have ${p} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:p}})=>(0,e._)`{property: ${l},
5
+ || ${x} === "boolean" || ${S} === null`).assign(I,(0,n._)`[${S}]`)}}}function h({gen:_,parentData:g,parentDataProperty:b},k){_.if((0,n._)`${g} !== undefined`,()=>_.assign((0,n._)`${g}[${b}]`,k))}function d(_,g,b,k=o.Correct){const S=k===o.Correct?n.operators.EQ:n.operators.NEQ;let T;switch(_){case"null":return(0,n._)`${g} ${S} null`;case"array":T=(0,n._)`Array.isArray(${g})`;break;case"object":T=(0,n._)`${g} && typeof ${g} == "object" && !Array.isArray(${g})`;break;case"integer":T=x((0,n._)`!(${g} % 1) && !isNaN(${g})`);break;case"number":T=x();break;default:return(0,n._)`typeof ${g} ${S} ${_}`}return k===o.Correct?T:(0,n.not)(T);function x(I=n.nil){return(0,n.and)((0,n._)`typeof ${g} == "number"`,I,b?(0,n._)`isFinite(${g})`:n.nil)}}st.checkDataType=d;function f(_,g,b,k){if(_.length===1)return d(_[0],g,b,k);let S;const T=(0,s.toHash)(_);if(T.array&&T.object){const x=(0,n._)`typeof ${g} != "object"`;S=T.null?x:(0,n._)`!${g} || ${x}`,delete T.null,delete T.array,delete T.object}else S=n.nil;T.number&&delete T.integer;for(const x in T)S=(0,n.and)(S,d(x,g,b,k));return S}st.checkDataTypes=f;const w={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:g})=>typeof _=="string"?(0,n._)`{type: ${_}}`:(0,n._)`{type: ${g}}`};function m(_){const g=y(_);(0,r.reportError)(g,w)}st.reportTypeError=m;function y(_){const{gen:g,data:b,schema:k}=_,S=(0,s.schemaRefOrVal)(_,k,"type");return{gen:g,keyword:"type",data:b,schema:k.type,schemaCode:S,schemaValue:S,parentSchema:k,params:{},it:_}}return st}var ds={},yd;function T_(){if(yd)return ds;yd=1,Object.defineProperty(ds,"__esModule",{value:!0}),ds.assignDefaults=void 0;const t=$e(),e=Oe();function r(s,o){const{properties:a,items:i}=s.schema;if(o==="object"&&a)for(const l in a)n(s,l,a[l].default);else o==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(s,c,l.default))}ds.assignDefaults=r;function n(s,o,a){const{gen:i,compositeRule:l,data:c,opts:u}=s;if(a===void 0)return;const p=(0,t._)`${c}${(0,t.getProperty)(o)}`;if(l){(0,e.checkStrictMode)(s,`default is ignored for: ${p}`);return}let h=(0,t._)`${p} === undefined`;u.useDefaults==="empty"&&(h=(0,t._)`${h} || ${p} === null || ${p} === ""`),i.if(h,(0,t._)`${p} = ${(0,t.stringify)(a)}`)}return ds}var Zt={},je={},wd;function Ft(){if(wd)return je;wd=1,Object.defineProperty(je,"__esModule",{value:!0}),je.validateUnion=je.validateArray=je.usePattern=je.callValidateCode=je.schemaProperties=je.allSchemaProperties=je.noPropertyInData=je.propertyInData=je.isOwnProperty=je.hasPropFunc=je.reportMissingProp=je.checkMissingProp=je.checkReportMissingProp=void 0;const t=$e(),e=Oe(),r=Nr(),n=Oe();function s(_,g){const{gen:b,data:k,it:S}=_;b.if(u(b,k,g,S.opts.ownProperties),()=>{_.setParams({missingProperty:(0,t._)`${g}`},!0),_.error()})}je.checkReportMissingProp=s;function o({gen:_,data:g,it:{opts:b}},k,S){return(0,t.or)(...k.map(T=>(0,t.and)(u(_,g,T,b.ownProperties),(0,t._)`${S} = ${T}`)))}je.checkMissingProp=o;function a(_,g){_.setParams({missingProperty:g},!0),_.error()}je.reportMissingProp=a;function i(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}je.hasPropFunc=i;function l(_,g,b){return(0,t._)`${i(_)}.call(${g}, ${b})`}je.isOwnProperty=l;function c(_,g,b,k){const S=(0,t._)`${g}${(0,t.getProperty)(b)} !== undefined`;return k?(0,t._)`${S} && ${l(_,g,b)}`:S}je.propertyInData=c;function u(_,g,b,k){const S=(0,t._)`${g}${(0,t.getProperty)(b)} === undefined`;return k?(0,t.or)(S,(0,t.not)(l(_,g,b))):S}je.noPropertyInData=u;function p(_){return _?Object.keys(_).filter(g=>g!=="__proto__"):[]}je.allSchemaProperties=p;function h(_,g){return p(g).filter(b=>!(0,e.alwaysValidSchema)(_,g[b]))}je.schemaProperties=h;function d({schemaCode:_,data:g,it:{gen:b,topSchemaRef:k,schemaPath:S,errorPath:T},it:x},I,A,P){const D=P?(0,t._)`${_}, ${g}, ${k}${S}`:g,U=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,T)],[r.default.parentData,x.parentData],[r.default.parentDataProperty,x.parentDataProperty],[r.default.rootData,r.default.rootData]];x.opts.dynamicRef&&U.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const V=(0,t._)`${D}, ${b.object(...U)}`;return A!==t.nil?(0,t._)`${I}.call(${A}, ${V})`:(0,t._)`${I}(${V})`}je.callValidateCode=d;const f=(0,t._)`new RegExp`;function w({gen:_,it:{opts:g}},b){const k=g.unicodeRegExp?"u":"",{regExp:S}=g.code,T=S(b,k);return _.scopeValue("pattern",{key:T.toString(),ref:T,code:(0,t._)`${S.code==="new RegExp"?f:(0,n.useFunc)(_,S)}(${b}, ${k})`})}je.usePattern=w;function m(_){const{gen:g,data:b,keyword:k,it:S}=_,T=g.name("valid");if(S.allErrors){const I=g.let("valid",!0);return x(()=>g.assign(I,!1)),I}return g.var(T,!0),x(()=>g.break()),T;function x(I){const A=g.const("len",(0,t._)`${b}.length`);g.forRange("i",0,A,P=>{_.subschema({keyword:k,dataProp:P,dataPropType:e.Type.Num},T),g.if((0,t.not)(T),I)})}}je.validateArray=m;function y(_){const{gen:g,schema:b,keyword:k,it:S}=_;if(!Array.isArray(b))throw new Error("ajv implementation error");if(b.some(A=>(0,e.alwaysValidSchema)(S,A))&&!S.opts.unevaluated)return;const x=g.let("valid",!1),I=g.name("_valid");g.block(()=>b.forEach((A,P)=>{const D=_.subschema({keyword:k,schemaProp:P,compositeRule:!0},I);g.assign(x,(0,t._)`${x} || ${I}`),_.mergeValidEvaluated(D,I)||g.if((0,t.not)(x))})),_.result(x,()=>_.reset(),()=>_.error(!0))}return je.validateUnion=y,je}var bd;function C_(){if(bd)return Zt;bd=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.validateKeywordUsage=Zt.validSchemaType=Zt.funcKeywordCode=Zt.macroKeywordCode=void 0;const t=$e(),e=Nr(),r=Ft(),n=Io();function s(h,d){const{gen:f,keyword:w,schema:m,parentSchema:y,it:_}=h,g=d.macro.call(_.self,m,y,_),b=c(f,w,g);_.opts.validateSchema!==!1&&_.self.validateSchema(g,!0);const k=f.name("valid");h.subschema({schema:g,schemaPath:t.nil,errSchemaPath:`${_.errSchemaPath}/${w}`,topSchemaRef:b,compositeRule:!0},k),h.pass(k,()=>h.error(!0))}Zt.macroKeywordCode=s;function o(h,d){var f;const{gen:w,keyword:m,schema:y,parentSchema:_,$data:g,it:b}=h;l(b,d);const k=!g&&d.compile?d.compile.call(b.self,y,_,b):d.validate,S=c(w,m,k),T=w.let("valid");h.block$data(T,x),h.ok((f=d.valid)!==null&&f!==void 0?f:T);function x(){if(d.errors===!1)P(),d.modifying&&a(h),D(()=>h.error());else{const U=d.async?I():A();d.modifying&&a(h),D(()=>i(h,U))}}function I(){const U=w.let("ruleErrs",null);return w.try(()=>P((0,t._)`await `),V=>w.assign(T,!1).if((0,t._)`${V} instanceof ${b.ValidationError}`,()=>w.assign(U,(0,t._)`${V}.errors`),()=>w.throw(V))),U}function A(){const U=(0,t._)`${S}.errors`;return w.assign(U,null),P(t.nil),U}function P(U=d.async?(0,t._)`await `:t.nil){const V=b.opts.passContext?e.default.this:e.default.self,se=!("compile"in d&&!g||d.schema===!1);w.assign(T,(0,t._)`${U}${(0,r.callValidateCode)(h,S,V,se)}`,d.modifying)}function D(U){var V;w.if((0,t.not)((V=d.valid)!==null&&V!==void 0?V:T),U)}}Zt.funcKeywordCode=o;function a(h){const{gen:d,data:f,it:w}=h;d.if(w.parentData,()=>d.assign(f,(0,t._)`${w.parentData}[${w.parentDataProperty}]`))}function i(h,d){const{gen:f}=h;f.if((0,t._)`Array.isArray(${d})`,()=>{f.assign(e.default.vErrors,(0,t._)`${e.default.vErrors} === null ? ${d} : ${e.default.vErrors}.concat(${d})`).assign(e.default.errors,(0,t._)`${e.default.vErrors}.length`),(0,n.extendErrors)(h)},()=>h.error())}function l({schemaEnv:h},d){if(d.async&&!h.$async)throw new Error("async keyword in sync schema")}function c(h,d,f){if(f===void 0)throw new Error(`keyword "${d}" failed to compile`);return h.scopeValue("keyword",typeof f=="function"?{ref:f}:{ref:f,code:(0,t.stringify)(f)})}function u(h,d,f=!1){return!d.length||d.some(w=>w==="array"?Array.isArray(h):w==="object"?h&&typeof h=="object"&&!Array.isArray(h):typeof h==w||f&&typeof h>"u")}Zt.validSchemaType=u;function p({schema:h,opts:d,self:f,errSchemaPath:w},m,y){if(Array.isArray(m.keyword)?!m.keyword.includes(y):m.keyword!==y)throw new Error("ajv implementation error");const _=m.dependencies;if(_?.some(g=>!Object.prototype.hasOwnProperty.call(h,g)))throw new Error(`parent schema must have dependencies of ${y}: ${_.join(",")}`);if(m.validateSchema&&!m.validateSchema(h[y])){const b=`keyword "${y}" value is invalid at path "${w}": `+f.errorsText(m.validateSchema.errors);if(d.validateSchema==="log")f.logger.error(b);else throw new Error(b)}}return Zt.validateKeywordUsage=p,Zt}var br={},kd;function $_(){if(kd)return br;kd=1,Object.defineProperty(br,"__esModule",{value:!0}),br.extendSubschemaMode=br.extendSubschemaData=br.getSubschema=void 0;const t=$e(),e=Oe();function r(o,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:p}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const h=o.schema[a];return i===void 0?{schema:h,schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}`,errSchemaPath:`${o.errSchemaPath}/${a}`}:{schema:h[i],schemaPath:(0,t._)`${o.schemaPath}${(0,t.getProperty)(a)}${(0,t.getProperty)(i)}`,errSchemaPath:`${o.errSchemaPath}/${a}/${(0,e.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||p===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:p,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}br.getSubschema=r;function n(o,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:p}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:h}=a;if(i!==void 0){const{errorPath:f,dataPathArr:w,opts:m}=a,y=h.let("data",(0,t._)`${a.data}${(0,t.getProperty)(i)}`,!0);d(y),o.errorPath=(0,t.str)`${f}${(0,e.getErrorPath)(i,l,m.jsPropertySyntax)}`,o.parentDataProperty=(0,t._)`${i}`,o.dataPathArr=[...w,o.parentDataProperty]}if(c!==void 0){const f=c instanceof t.Name?c:h.let("data",c,!0);d(f),p!==void 0&&(o.propertyName=p)}u&&(o.dataTypes=u);function d(f){o.data=f,o.dataLevel=a.dataLevel+1,o.dataTypes=[],a.definedProperties=new Set,o.parentData=a.data,o.dataNames=[...a.dataNames,f]}}br.extendSubschemaData=n;function s(o,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(o.compositeRule=l),c!==void 0&&(o.createErrors=c),u!==void 0&&(o.allErrors=u),o.jtdDiscriminator=a,o.jtdMetadata=i}return br.extendSubschemaMode=s,br}var pt={},Di,Sd;function Td(){return Sd||(Sd=1,Di=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var a=o[s];if(!t(e[a],r[a]))return!1}return!0}return e!==e&&r!==r}),Di}var Ui={exports:{}},Cd;function E_(){if(Cd)return Ui.exports;Cd=1;var t=Ui.exports=function(n,s,o){typeof s=="function"&&(o=s,s={}),o=s.cb||o;var a=typeof o=="function"?o:o.pre||function(){},i=o.post||function(){};e(s,a,i,n,"",n)};t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.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 e(n,s,o,a,i,l,c,u,p,h){if(a&&typeof a=="object"&&!Array.isArray(a)){s(a,i,l,c,u,p,h);for(var d in a){var f=a[d];if(Array.isArray(f)){if(d in t.arrayKeywords)for(var w=0;w<f.length;w++)e(n,s,o,f[w],i+"/"+d+"/"+w,l,i,d,a,w)}else if(d in t.propsKeywords){if(f&&typeof f=="object")for(var m in f)e(n,s,o,f[m],i+"/"+d+"/"+r(m),l,i,d,a,m)}else(d in t.keywords||n.allKeys&&!(d in t.skipKeywords))&&e(n,s,o,f,i+"/"+d,l,i,d,a)}o(a,i,l,c,u,p,h)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return Ui.exports}var $d;function Po(){if($d)return pt;$d=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.getSchemaRefs=pt.resolveUrl=pt.normalizeId=pt._getFullPath=pt.getFullPath=pt.inlineRef=void 0;const t=Oe(),e=Td(),r=E_(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s(w,m=!0){return typeof w=="boolean"?!0:m===!0?!a(w):m?i(w)<=m:!1}pt.inlineRef=s;const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(w){for(const m in w){if(o.has(m))return!0;const y=w[m];if(Array.isArray(y)&&y.some(a)||typeof y=="object"&&a(y))return!0}return!1}function i(w){let m=0;for(const y in w){if(y==="$ref")return 1/0;if(m++,!n.has(y)&&(typeof w[y]=="object"&&(0,t.eachItem)(w[y],_=>m+=i(_)),m===1/0))return 1/0}return m}function l(w,m="",y){y!==!1&&(m=p(m));const _=w.parse(m);return c(w,_)}pt.getFullPath=l;function c(w,m){return w.serialize(m).split("#")[0]+"#"}pt._getFullPath=c;const u=/#\/?$/;function p(w){return w?w.replace(u,""):""}pt.normalizeId=p;function h(w,m,y){return y=p(y),w.resolve(m,y)}pt.resolveUrl=h;const d=/^[a-z_][-a-z0-9._]*$/i;function f(w,m){if(typeof w=="boolean")return{};const{schemaId:y,uriResolver:_}=this.opts,g=p(w[y]||m),b={"":g},k=l(_,g,!1),S={},T=new Set;return r(w,{allKeys:!0},(A,P,D,U)=>{if(U===void 0)return;const V=k+P;let se=b[U];typeof A[y]=="string"&&(se=fe.call(this,A[y])),de.call(this,A.$anchor),de.call(this,A.$dynamicAnchor),b[P]=se;function fe(re){const _e=this.opts.uriResolver.resolve;if(re=p(se?_e(se,re):re),T.has(re))throw I(re);T.add(re);let H=this.refs[re];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?x(A,H.schema,re):re!==p(V)&&(re[0]==="#"?(x(A,S[re],re),S[re]=A):this.refs[re]=V),re}function de(re){if(typeof re=="string"){if(!d.test(re))throw new Error(`invalid anchor "${re}"`);fe.call(this,`#${re}`)}}}),S;function x(A,P,D){if(P!==void 0&&!e(A,P))throw I(D)}function I(A){return new Error(`reference "${A}" resolves to more than one schema`)}}return pt.getSchemaRefs=f,pt}var Ed;function Oo(){if(Ed)return yr;Ed=1,Object.defineProperty(yr,"__esModule",{value:!0}),yr.getData=yr.KeywordCxt=yr.validateFunctionCode=void 0;const t=S_(),e=Ro(),r=vd(),n=Ro(),s=T_(),o=C_(),a=$_(),i=$e(),l=Nr(),c=Po(),u=Oe(),p=Io();function h(M){if(k(M)&&(T(M),b(M))){m(M);return}d(M,()=>(0,t.topBoolOrEmptySchema)(M))}yr.validateFunctionCode=h;function d({gen:M,validateName:Z,schema:G,schemaEnv:K,opts:X},ue){X.code.es5?M.func(Z,(0,i._)`${l.default.data}, ${l.default.valCxt}`,K.$async,()=>{M.code((0,i._)`"use strict"; ${_(G,X)}`),w(M,X),M.code(ue)}):M.func(Z,(0,i._)`${l.default.data}, ${f(X)}`,K.$async,()=>M.code(_(G,X)).code(ue))}function f(M){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${M.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function w(M,Z){M.if(l.default.valCxt,()=>{M.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),M.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),M.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),M.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),Z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{M.var(l.default.instancePath,(0,i._)`""`),M.var(l.default.parentData,(0,i._)`undefined`),M.var(l.default.parentDataProperty,(0,i._)`undefined`),M.var(l.default.rootData,l.default.data),Z.dynamicRef&&M.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function m(M){const{schema:Z,opts:G,gen:K}=M;d(M,()=>{G.$comment&&Z.$comment&&U(M),A(M),K.let(l.default.vErrors,null),K.let(l.default.errors,0),G.unevaluated&&y(M),x(M),V(M)})}function y(M){const{gen:Z,validateName:G}=M;M.evaluated=Z.const("evaluated",(0,i._)`${G}.evaluated`),Z.if((0,i._)`${M.evaluated}.dynamicProps`,()=>Z.assign((0,i._)`${M.evaluated}.props`,(0,i._)`undefined`)),Z.if((0,i._)`${M.evaluated}.dynamicItems`,()=>Z.assign((0,i._)`${M.evaluated}.items`,(0,i._)`undefined`))}function _(M,Z){const G=typeof M=="object"&&M[Z.schemaId];return G&&(Z.code.source||Z.code.process)?(0,i._)`/*# sourceURL=${G} */`:i.nil}function g(M,Z){if(k(M)&&(T(M),b(M))){S(M,Z);return}(0,t.boolOrEmptySchema)(M,Z)}function b({schema:M,self:Z}){if(typeof M=="boolean")return!M;for(const G in M)if(Z.RULES.all[G])return!0;return!1}function k(M){return typeof M.schema!="boolean"}function S(M,Z){const{schema:G,gen:K,opts:X}=M;X.$comment&&G.$comment&&U(M),P(M),D(M);const ue=K.const("_errs",l.default.errors);x(M,ue),K.var(Z,(0,i._)`${ue} === ${l.default.errors}`)}function T(M){(0,u.checkUnknownRules)(M),I(M)}function x(M,Z){if(M.opts.jtd)return fe(M,[],!1,Z);const G=(0,e.getSchemaTypes)(M.schema),K=(0,e.coerceAndCheckDataType)(M,G);fe(M,G,!K,Z)}function I(M){const{schema:Z,errSchemaPath:G,opts:K,self:X}=M;Z.$ref&&K.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(Z,X.RULES)&&X.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function A(M){const{schema:Z,opts:G}=M;Z.default!==void 0&&G.useDefaults&&G.strictSchema&&(0,u.checkStrictMode)(M,"default is ignored in the schema root")}function P(M){const Z=M.schema[M.opts.schemaId];Z&&(M.baseId=(0,c.resolveUrl)(M.opts.uriResolver,M.baseId,Z))}function D(M){if(M.schema.$async&&!M.schemaEnv.$async)throw new Error("async schema in sync schema")}function U({gen:M,schemaEnv:Z,schema:G,errSchemaPath:K,opts:X}){const ue=G.$comment;if(X.$comment===!0)M.code((0,i._)`${l.default.self}.logger.log(${ue})`);else if(typeof X.$comment=="function"){const he=(0,i.str)`${K}/$comment`,He=M.scopeValue("root",{ref:Z.root});M.code((0,i._)`${l.default.self}.opts.$comment(${ue}, ${he}, ${He}.schema)`)}}function V(M){const{gen:Z,schemaEnv:G,validateName:K,ValidationError:X,opts:ue}=M;G.$async?Z.if((0,i._)`${l.default.errors} === 0`,()=>Z.return(l.default.data),()=>Z.throw((0,i._)`new ${X}(${l.default.vErrors})`)):(Z.assign((0,i._)`${K}.errors`,l.default.vErrors),ue.unevaluated&&se(M),Z.return((0,i._)`${l.default.errors} === 0`))}function se({gen:M,evaluated:Z,props:G,items:K}){G instanceof i.Name&&M.assign((0,i._)`${Z}.props`,G),K instanceof i.Name&&M.assign((0,i._)`${Z}.items`,K)}function fe(M,Z,G,K){const{gen:X,schema:ue,data:he,allErrors:He,opts:Je,self:ee}=M,{RULES:be}=ee;if(ue.$ref&&(Je.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(ue,be))){X.block(()=>B(M,"$ref",be.all.$ref.definition));return}Je.jtd||re(M,Z),X.block(()=>{for(const xe of be.rules)yt(xe);yt(be.post)});function yt(xe){(0,r.shouldUseGroup)(ue,xe)&&(xe.type?(X.if((0,n.checkDataType)(xe.type,he,Je.strictNumbers)),de(M,xe),Z.length===1&&Z[0]===xe.type&&G&&(X.else(),(0,n.reportTypeError)(M)),X.endIf()):de(M,xe),He||X.if((0,i._)`${l.default.errors} === ${K||0}`))}}function de(M,Z){const{gen:G,schema:K,opts:{useDefaults:X}}=M;X&&(0,s.assignDefaults)(M,Z.type),G.block(()=>{for(const ue of Z.rules)(0,r.shouldUseRule)(K,ue)&&B(M,ue.keyword,ue.definition,Z.type)})}function re(M,Z){M.schemaEnv.meta||!M.opts.strictTypes||(_e(M,Z),M.opts.allowUnionTypes||H(M,Z),O(M,M.dataTypes))}function _e(M,Z){if(Z.length){if(!M.dataTypes.length){M.dataTypes=Z;return}Z.forEach(G=>{q(M.dataTypes,G)||R(M,`type "${G}" not allowed by context "${M.dataTypes.join(",")}"`)}),E(M,Z)}}function H(M,Z){Z.length>1&&!(Z.length===2&&Z.includes("null"))&&R(M,"use allowUnionTypes to allow union type keyword")}function O(M,Z){const G=M.self.RULES.all;for(const K in G){const X=G[K];if(typeof X=="object"&&(0,r.shouldUseRule)(M.schema,X)){const{type:ue}=X.definition;ue.length&&!ue.some(he=>F(Z,he))&&R(M,`missing type "${ue.join(",")}" for keyword "${K}"`)}}}function F(M,Z){return M.includes(Z)||Z==="number"&&M.includes("integer")}function q(M,Z){return M.includes(Z)||Z==="integer"&&M.includes("number")}function E(M,Z){const G=[];for(const K of M.dataTypes)q(Z,K)?G.push(K):Z.includes("integer")&&K==="number"&&G.push("integer");M.dataTypes=G}function R(M,Z){const G=M.schemaEnv.baseId+M.errSchemaPath;Z+=` at "${G}" (strictTypes)`,(0,u.checkStrictMode)(M,Z,M.opts.strictTypes)}class ${constructor(Z,G,K){if((0,o.validateKeywordUsage)(Z,G,K),this.gen=Z.gen,this.allErrors=Z.allErrors,this.keyword=K,this.data=Z.data,this.schema=Z.schema[K],this.$data=G.$data&&Z.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(Z,this.schema,K,this.$data),this.schemaType=G.schemaType,this.parentSchema=Z.schema,this.params={},this.it=Z,this.def=G,this.$data)this.schemaCode=Z.gen.const("vSchema",pe(this.$data,Z));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,G.schemaType,G.allowUndefined))throw new Error(`${K} value must be ${JSON.stringify(G.schemaType)}`);("code"in G?G.trackErrors:G.errors!==!1)&&(this.errsCount=Z.gen.const("_errs",l.default.errors))}result(Z,G,K){this.failResult((0,i.not)(Z),G,K)}failResult(Z,G,K){this.gen.if(Z),K?K():this.error(),G?(this.gen.else(),G(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(Z,G){this.failResult((0,i.not)(Z),void 0,G)}fail(Z){if(Z===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(Z),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(Z){if(!this.$data)return this.fail(Z);const{schemaCode:G}=this;this.fail((0,i._)`${G} !== undefined && (${(0,i.or)(this.invalid$data(),Z)})`)}error(Z,G,K){if(G){this.setParams(G),this._error(Z,K),this.setParams({});return}this._error(Z,K)}_error(Z,G){(Z?p.reportExtraError:p.reportError)(this,this.def.error,G)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(Z){this.allErrors||this.gen.if(Z)}setParams(Z,G){G?Object.assign(this.params,Z):this.params=Z}block$data(Z,G,K=i.nil){this.gen.block(()=>{this.check$data(Z,K),G()})}check$data(Z=i.nil,G=i.nil){if(!this.$data)return;const{gen:K,schemaCode:X,schemaType:ue,def:he}=this;K.if((0,i.or)((0,i._)`${X} === undefined`,G)),Z!==i.nil&&K.assign(Z,!0),(ue.length||he.validateSchema)&&(K.elseIf(this.invalid$data()),this.$dataError(),Z!==i.nil&&K.assign(Z,!1)),K.else()}invalid$data(){const{gen:Z,schemaCode:G,schemaType:K,def:X,it:ue}=this;return(0,i.or)(he(),He());function he(){if(K.length){if(!(G instanceof i.Name))throw new Error("ajv implementation error");const Je=Array.isArray(K)?K:[K];return(0,i._)`${(0,n.checkDataTypes)(Je,G,ue.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function He(){if(X.validateSchema){const Je=Z.scopeValue("validate$data",{ref:X.validateSchema});return(0,i._)`!${Je}(${G})`}return i.nil}}subschema(Z,G){const K=(0,a.getSubschema)(this.it,Z);(0,a.extendSubschemaData)(K,this.it,Z),(0,a.extendSubschemaMode)(K,Z);const X={...this.it,...K,items:void 0,props:void 0};return g(X,G),X}mergeEvaluated(Z,G){const{it:K,gen:X}=this;K.opts.unevaluated&&(K.props!==!0&&Z.props!==void 0&&(K.props=u.mergeEvaluated.props(X,Z.props,K.props,G)),K.items!==!0&&Z.items!==void 0&&(K.items=u.mergeEvaluated.items(X,Z.items,K.items,G)))}mergeValidEvaluated(Z,G){const{it:K,gen:X}=this;if(K.opts.unevaluated&&(K.props!==!0||K.items!==!0))return X.if(G,()=>this.mergeEvaluated(Z,i.Name)),!0}}yr.KeywordCxt=$;function B(M,Z,G,K){const X=new $(M,G,Z);"code"in G?G.code(X,K):X.$data&&G.validate?(0,o.funcKeywordCode)(X,G):"macro"in G?(0,o.macroKeywordCode)(X,G):(G.compile||G.validate)&&(0,o.funcKeywordCode)(X,G)}const W=/^\/(?:[^~]|~0|~1)*$/,ye=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(M,{dataLevel:Z,dataNames:G,dataPathArr:K}){let X,ue;if(M==="")return l.default.rootData;if(M[0]==="/"){if(!W.test(M))throw new Error(`Invalid JSON-pointer: ${M}`);X=M,ue=l.default.rootData}else{const ee=ye.exec(M);if(!ee)throw new Error(`Invalid JSON-pointer: ${M}`);const be=+ee[1];if(X=ee[2],X==="#"){if(be>=Z)throw new Error(Je("property/index",be));return K[Z-be]}if(be>Z)throw new Error(Je("data",be));if(ue=G[Z-be],!X)return ue}let he=ue;const He=X.split("/");for(const ee of He)ee&&(ue=(0,i._)`${ue}${(0,i.getProperty)((0,u.unescapeJsonPointer)(ee))}`,he=(0,i._)`${he} && ${ue}`);return he;function Je(ee,be){return`Cannot access ${ee} ${be} levels up, current level is ${Z}`}}return yr.getData=pe,yr}var Ao={},xd;function Zi(){if(xd)return Ao;xd=1,Object.defineProperty(Ao,"__esModule",{value:!0});class t extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Ao.default=t,Ao}var Mo={},Id;function No(){if(Id)return Mo;Id=1,Object.defineProperty(Mo,"__esModule",{value:!0});const t=Po();class e extends Error{constructor(n,s,o,a){super(a||`can't resolve reference ${o} from id ${s}`),this.missingRef=(0,t.resolveUrl)(n,s,o),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}}return Mo.default=e,Mo}var It={},Rd;function Fi(){if(Rd)return It;Rd=1,Object.defineProperty(It,"__esModule",{value:!0}),It.resolveSchema=It.getCompilingSchema=It.resolveRef=It.compileSchema=It.SchemaEnv=void 0;const t=$e(),e=Zi(),r=Nr(),n=Po(),s=Oe(),o=Oo();class a{constructor(y){var _;this.refs={},this.dynamicAnchors={};let g;typeof y.schema=="object"&&(g=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(_=y.baseId)!==null&&_!==void 0?_:(0,n.normalizeId)(g?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=g?.$async,this.refs={}}}It.SchemaEnv=a;function i(m){const y=u.call(this,m);if(y)return y;const _=(0,n.getFullPath)(this.opts.uriResolver,m.root.baseId),{es5:g,lines:b}=this.opts.code,{ownProperties:k}=this.opts,S=new t.CodeGen(this.scope,{es5:g,lines:b,ownProperties:k});let T;m.$async&&(T=S.scopeValue("Error",{ref:e.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));const x=S.scopeName("validate");m.validateName=x;const I={gen:S,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:S.scopeValue("schema",this.opts.code.source===!0?{ref:m.schema,code:(0,t.stringify)(m.schema)}:{ref:m.schema}),validateName:x,ValidationError:T,schema:m.schema,schemaEnv:m,rootId:_,baseId:m.baseId||_,schemaPath:t.nil,errSchemaPath:m.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this};let A;try{this._compilations.add(m),(0,o.validateFunctionCode)(I),S.optimize(this.opts.code.optimize);const P=S.toString();A=`${S.scopeRefs(r.default.scope)}return ${P}`,this.opts.code.process&&(A=this.opts.code.process(A,m));const U=new Function(`${r.default.self}`,`${r.default.scope}`,A)(this,this.scope.get());if(this.scope.value(x,{ref:U}),U.errors=null,U.schema=m.schema,U.schemaEnv=m,m.$async&&(U.$async=!0),this.opts.code.source===!0&&(U.source={validateName:x,validateCode:P,scopeValues:S._values}),this.opts.unevaluated){const{props:V,items:se}=I;U.evaluated={props:V instanceof t.Name?void 0:V,items:se instanceof t.Name?void 0:se,dynamicProps:V instanceof t.Name,dynamicItems:se instanceof t.Name},U.source&&(U.source.evaluated=(0,t.stringify)(U.evaluated))}return m.validate=U,m}catch(P){throw delete m.validate,delete m.validateName,A&&this.logger.error("Error compiling schema, function code:",A),P}finally{this._compilations.delete(m)}}It.compileSchema=i;function l(m,y,_){var g;_=(0,n.resolveUrl)(this.opts.uriResolver,y,_);const b=m.refs[_];if(b)return b;let k=h.call(this,m,_);if(k===void 0){const S=(g=m.localRefs)===null||g===void 0?void 0:g[_],{schemaId:T}=this.opts;S&&(k=new a({schema:S,schemaId:T,root:m,baseId:y}))}if(k!==void 0)return m.refs[_]=c.call(this,k)}It.resolveRef=l;function c(m){return(0,n.inlineRef)(m.schema,this.opts.inlineRefs)?m.schema:m.validate?m:i.call(this,m)}function u(m){for(const y of this._compilations)if(p(y,m))return y}It.getCompilingSchema=u;function p(m,y){return m.schema===y.schema&&m.root===y.root&&m.baseId===y.baseId}function h(m,y){let _;for(;typeof(_=this.refs[y])=="string";)y=_;return _||this.schemas[y]||d.call(this,m,y)}function d(m,y){const _=this.opts.uriResolver.parse(y),g=(0,n._getFullPath)(this.opts.uriResolver,_);let b=(0,n.getFullPath)(this.opts.uriResolver,m.baseId,void 0);if(Object.keys(m.schema).length>0&&g===b)return w.call(this,_,m);const k=(0,n.normalizeId)(g),S=this.refs[k]||this.schemas[k];if(typeof S=="string"){const T=d.call(this,m,S);return typeof T?.schema!="object"?void 0:w.call(this,_,T)}if(typeof S?.schema=="object"){if(S.validate||i.call(this,S),k===(0,n.normalizeId)(y)){const{schema:T}=S,{schemaId:x}=this.opts,I=T[x];return I&&(b=(0,n.resolveUrl)(this.opts.uriResolver,b,I)),new a({schema:T,schemaId:x,root:m,baseId:b})}return w.call(this,_,S)}}It.resolveSchema=d;const f=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(m,{baseId:y,schema:_,root:g}){var b;if(((b=m.fragment)===null||b===void 0?void 0:b[0])!=="/")return;for(const T of m.fragment.slice(1).split("/")){if(typeof _=="boolean")return;const x=_[(0,s.unescapeFragment)(T)];if(x===void 0)return;_=x;const I=typeof _=="object"&&_[this.opts.schemaId];!f.has(T)&&I&&(y=(0,n.resolveUrl)(this.opts.uriResolver,y,I))}let k;if(typeof _!="boolean"&&_.$ref&&!(0,s.schemaHasRulesButRef)(_,this.RULES)){const T=(0,n.resolveUrl)(this.opts.uriResolver,y,_.$ref);k=d.call(this,g,T)}const{schemaId:S}=this.opts;if(k=k||new a({schema:_,schemaId:S,root:g,baseId:y}),k.schema!==k.root.schema)return k}return It}const x_={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Lo={},ps={exports:{}},Vi,Pd;function Od(){if(Pd)return Vi;Pd=1;const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),e=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(h){let d="",f=0,w=0;for(w=0;w<h.length;w++)if(f=h[w].charCodeAt(0),f!==48){if(!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[w];break}for(w+=1;w<h.length;w++){if(f=h[w].charCodeAt(0),!(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";d+=h[w]}return d}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(h){return h.length=0,!0}function o(h,d,f){if(h.length){const w=r(h);if(w!=="")d.push(w);else return f.error=!0,!1;h.length=0}return!0}function a(h){let d=0;const f={error:!1,address:"",zone:""},w=[],m=[];let y=!1,_=!1,g=o;for(let b=0;b<h.length;b++){const k=h[b];if(!(k==="["||k==="]"))if(k===":"){if(y===!0&&(_=!0),!g(m,w,f))break;if(++d>7){f.error=!0;break}b>0&&h[b-1]===":"&&(y=!0),w.push(":");continue}else if(k==="%"){if(!g(m,w,f))break;g=s}else{m.push(k);continue}}return m.length&&(g===s?f.zone=m.join(""):_?w.push(m.join("")):w.push(r(m))),f.address=w.join(""),f}function i(h){if(l(h,":")<2)return{host:h,isIPV6:!1};const d=a(h);if(d.error)return{host:h,isIPV6:!1};{let f=d.address,w=d.address;return d.zone&&(f+="%"+d.zone,w+="%25"+d.zone),{host:f,isIPV6:!0,escapedHost:w}}}function l(h,d){let f=0;for(let w=0;w<h.length;w++)h[w]===d&&f++;return f}function c(h){let d=h;const f=[];let w=-1,m=0;for(;m=d.length;){if(m===1){if(d===".")break;if(d==="/"){f.push("/");break}else{f.push(d);break}}else if(m===2){if(d[0]==="."){if(d[1]===".")break;if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&(d[1]==="."||d[1]==="/")){f.push("/");break}}else if(m===3&&d==="/.."){f.length!==0&&f.pop(),f.push("/");break}if(d[0]==="."){if(d[1]==="."){if(d[2]==="/"){d=d.slice(3);continue}}else if(d[1]==="/"){d=d.slice(2);continue}}else if(d[0]==="/"&&d[1]==="."){if(d[2]==="/"){d=d.slice(2);continue}else if(d[2]==="."&&d[3]==="/"){d=d.slice(3),f.length!==0&&f.pop();continue}}if((w=d.indexOf("/",1))===-1){f.push(d);break}else f.push(d.slice(0,w)),d=d.slice(w)}return f.join("")}function u(h,d){const f=d!==!0?escape:unescape;return h.scheme!==void 0&&(h.scheme=f(h.scheme)),h.userinfo!==void 0&&(h.userinfo=f(h.userinfo)),h.host!==void 0&&(h.host=f(h.host)),h.path!==void 0&&(h.path=f(h.path)),h.query!==void 0&&(h.query=f(h.query)),h.fragment!==void 0&&(h.fragment=f(h.fragment)),h}function p(h){const d=[];if(h.userinfo!==void 0&&(d.push(h.userinfo),d.push("@")),h.host!==void 0){let f=unescape(h.host);if(!e(f)){const w=i(f);w.isIPV6===!0?f=`[${w.escapedHost}]`:f=h.host}d.push(f)}return(typeof h.port=="number"||typeof h.port=="string")&&(d.push(":"),d.push(String(h.port))),d.length?d.join(""):void 0}return Vi={nonSimpleDomain:n,recomposeAuthority:p,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:e,isUUID:t,normalizeIPv6:i,stringArrayToHexStripped:r},Vi}var Hi,Ad;function I_(){if(Ad)return Hi;Ad=1;const{isUUID:t}=Od(),e=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(k){return r.indexOf(k)!==-1}function s(k){return k.secure===!0?!0:k.secure===!1?!1:k.scheme?k.scheme.length===3&&(k.scheme[0]==="w"||k.scheme[0]==="W")&&(k.scheme[1]==="s"||k.scheme[1]==="S")&&(k.scheme[2]==="s"||k.scheme[2]==="S"):!1}function o(k){return k.host||(k.error=k.error||"HTTP URIs must have a host."),k}function a(k){const S=String(k.scheme).toLowerCase()==="https";return(k.port===(S?443:80)||k.port==="")&&(k.port=void 0),k.path||(k.path="/"),k}function i(k){return k.secure=s(k),k.resourceName=(k.path||"/")+(k.query?"?"+k.query:""),k.path=void 0,k.query=void 0,k}function l(k){if((k.port===(s(k)?443:80)||k.port==="")&&(k.port=void 0),typeof k.secure=="boolean"&&(k.scheme=k.secure?"wss":"ws",k.secure=void 0),k.resourceName){const[S,T]=k.resourceName.split("?");k.path=S&&S!=="/"?S:void 0,k.query=T,k.resourceName=void 0}return k.fragment=void 0,k}function c(k,S){if(!k.path)return k.error="URN can not be parsed",k;const T=k.path.match(e);if(T){const x=S.scheme||k.scheme||"urn";k.nid=T[1].toLowerCase(),k.nss=T[2];const I=`${x}:${S.nid||k.nid}`,A=b(I);k.path=void 0,A&&(k=A.parse(k,S))}else k.error=k.error||"URN can not be parsed.";return k}function u(k,S){if(k.nid===void 0)throw new Error("URN without nid cannot be serialized");const T=S.scheme||k.scheme||"urn",x=k.nid.toLowerCase(),I=`${T}:${S.nid||x}`,A=b(I);A&&(k=A.serialize(k,S));const P=k,D=k.nss;return P.path=`${x||S.nid}:${D}`,S.skipEscape=!0,P}function p(k,S){const T=k;return T.uuid=T.nss,T.nss=void 0,!S.tolerant&&(!T.uuid||!t(T.uuid))&&(T.error=T.error||"UUID is not valid."),T}function h(k){const S=k;return S.nss=(k.uuid||"").toLowerCase(),S}const d={scheme:"http",domainHost:!0,parse:o,serialize:a},f={scheme:"https",domainHost:d.domainHost,parse:o,serialize:a},w={scheme:"ws",domainHost:!0,parse:i,serialize:l},m={scheme:"wss",domainHost:w.domainHost,parse:w.parse,serialize:w.serialize},g={http:d,https:f,ws:w,wss:m,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:p,serialize:h,skipNormalize:!0}};Object.setPrototypeOf(g,null);function b(k){return k&&(g[k]||g[k.toLowerCase()])||void 0}return Hi={wsIsSecure:s,SCHEMES:g,isValidSchemeName:n,getSchemeHandler:b},Hi}var Md;function R_(){if(Md)return ps.exports;Md=1;const{normalizeIPv6:t,removeDotSegments:e,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:s,nonSimpleDomain:o}=Od(),{SCHEMES:a,getSchemeHandler:i}=I_();function l(m,y){return typeof m=="string"?m=h(f(m,y),y):typeof m=="object"&&(m=f(h(m,y),y)),m}function c(m,y,_){const g=_?Object.assign({scheme:"null"},_):{scheme:"null"},b=u(f(m,g),f(y,g),g,!0);return g.skipEscape=!0,h(b,g)}function u(m,y,_,g){const b={};return g||(m=f(h(m,_),_),y=f(h(y,_),_)),_=_||{},!_.tolerant&&y.scheme?(b.scheme=y.scheme,b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=e(y.path||""),b.query=y.query):(y.userinfo!==void 0||y.host!==void 0||y.port!==void 0?(b.userinfo=y.userinfo,b.host=y.host,b.port=y.port,b.path=e(y.path||""),b.query=y.query):(y.path?(y.path[0]==="/"?b.path=e(y.path):((m.userinfo!==void 0||m.host!==void 0||m.port!==void 0)&&!m.path?b.path="/"+y.path:m.path?b.path=m.path.slice(0,m.path.lastIndexOf("/")+1)+y.path:b.path=y.path,b.path=e(b.path)),b.query=y.query):(b.path=m.path,y.query!==void 0?b.query=y.query:b.query=m.query),b.userinfo=m.userinfo,b.host=m.host,b.port=m.port),b.scheme=m.scheme),b.fragment=y.fragment,b}function p(m,y,_){return typeof m=="string"?(m=unescape(m),m=h(n(f(m,_),!0),{..._,skipEscape:!0})):typeof m=="object"&&(m=h(n(m,!0),{..._,skipEscape:!0})),typeof y=="string"?(y=unescape(y),y=h(n(f(y,_),!0),{..._,skipEscape:!0})):typeof y=="object"&&(y=h(n(y,!0),{..._,skipEscape:!0})),m.toLowerCase()===y.toLowerCase()}function h(m,y){const _={host:m.host,scheme:m.scheme,userinfo:m.userinfo,port:m.port,path:m.path,query:m.query,nid:m.nid,nss:m.nss,uuid:m.uuid,fragment:m.fragment,reference:m.reference,resourceName:m.resourceName,secure:m.secure,error:""},g=Object.assign({},y),b=[],k=i(g.scheme||_.scheme);k&&k.serialize&&k.serialize(_,g),_.path!==void 0&&(g.skipEscape?_.path=unescape(_.path):(_.path=escape(_.path),_.scheme!==void 0&&(_.path=_.path.split("%3A").join(":")))),g.reference!=="suffix"&&_.scheme&&b.push(_.scheme,":");const S=r(_);if(S!==void 0&&(g.reference!=="suffix"&&b.push("//"),b.push(S),_.path&&_.path[0]!=="/"&&b.push("/")),_.path!==void 0){let T=_.path;!g.absolutePath&&(!k||!k.absolutePath)&&(T=e(T)),S===void 0&&T[0]==="/"&&T[1]==="/"&&(T="/%2F"+T.slice(2)),b.push(T)}return _.query!==void 0&&b.push("?",_.query),_.fragment!==void 0&&b.push("#",_.fragment),b.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f(m,y){const _=Object.assign({},y),g={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let b=!1;_.reference==="suffix"&&(_.scheme?m=_.scheme+":"+m:m="//"+m);const k=m.match(d);if(k){if(g.scheme=k[1],g.userinfo=k[3],g.host=k[4],g.port=parseInt(k[5],10),g.path=k[6]||"",g.query=k[7],g.fragment=k[8],isNaN(g.port)&&(g.port=k[5]),g.host)if(s(g.host)===!1){const x=t(g.host);g.host=x.host.toLowerCase(),b=x.isIPV6}else b=!0;g.scheme===void 0&&g.userinfo===void 0&&g.host===void 0&&g.port===void 0&&g.query===void 0&&!g.path?g.reference="same-document":g.scheme===void 0?g.reference="relative":g.fragment===void 0?g.reference="absolute":g.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==g.reference&&(g.error=g.error||"URI is not a "+_.reference+" reference.");const S=i(_.scheme||g.scheme);if(!_.unicodeSupport&&(!S||!S.unicodeSupport)&&g.host&&(_.domainHost||S&&S.domainHost)&&b===!1&&o(g.host))try{g.host=URL.domainToASCII(g.host.toLowerCase())}catch(T){g.error=g.error||"Host's domain name can not be converted to ASCII: "+T}(!S||S&&!S.skipNormalize)&&(m.indexOf("%")!==-1&&(g.scheme!==void 0&&(g.scheme=unescape(g.scheme)),g.host!==void 0&&(g.host=unescape(g.host))),g.path&&(g.path=escape(unescape(g.path))),g.fragment&&(g.fragment=encodeURI(decodeURIComponent(g.fragment)))),S&&S.parse&&S.parse(g,_)}else g.error=g.error||"URI can not be parsed.";return g}const w={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:p,serialize:h,parse:f};return ps.exports=w,ps.exports.default=w,ps.exports.fastUri=w,ps.exports}var Nd;function P_(){if(Nd)return Lo;Nd=1,Object.defineProperty(Lo,"__esModule",{value:!0});const t=R_();return t.code='require("ajv/dist/runtime/uri").default',Lo.default=t,Lo}var Ld;function O_(){return Ld||(Ld=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=Oo();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=$e();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=Zi(),s=No(),o=md(),a=Fi(),i=$e(),l=Po(),c=Ro(),u=Oe(),p=x_,h=P_(),d=(H,O)=>new RegExp(H,O);d.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],w=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function g(H){var O,F,q,E,R,$,B,W,ye,pe,M,Z,G,K,X,ue,he,He,Je,ee,be,yt,xe,Et,Pr;const xt=H.strict,it=(O=H.code)===null||O===void 0?void 0:O.optimize,Ut=it===!0||it===void 0?1:it||0,Xr=(q=(F=H.code)===null||F===void 0?void 0:F.regExp)!==null&&q!==void 0?q:d,en=(E=H.uriResolver)!==null&&E!==void 0?E:h.default;return{strictSchema:($=(R=H.strictSchema)!==null&&R!==void 0?R:xt)!==null&&$!==void 0?$:!0,strictNumbers:(W=(B=H.strictNumbers)!==null&&B!==void 0?B:xt)!==null&&W!==void 0?W:!0,strictTypes:(pe=(ye=H.strictTypes)!==null&&ye!==void 0?ye:xt)!==null&&pe!==void 0?pe:"log",strictTuples:(Z=(M=H.strictTuples)!==null&&M!==void 0?M:xt)!==null&&Z!==void 0?Z:"log",strictRequired:(K=(G=H.strictRequired)!==null&&G!==void 0?G:xt)!==null&&K!==void 0?K:!1,code:H.code?{...H.code,optimize:Ut,regExp:Xr}:{optimize:Ut,regExp:Xr},loopRequired:(X=H.loopRequired)!==null&&X!==void 0?X:_,loopEnum:(ue=H.loopEnum)!==null&&ue!==void 0?ue:_,meta:(he=H.meta)!==null&&he!==void 0?he:!0,messages:(He=H.messages)!==null&&He!==void 0?He:!0,inlineRefs:(Je=H.inlineRefs)!==null&&Je!==void 0?Je:!0,schemaId:(ee=H.schemaId)!==null&&ee!==void 0?ee:"$id",addUsedSchema:(be=H.addUsedSchema)!==null&&be!==void 0?be:!0,validateSchema:(yt=H.validateSchema)!==null&&yt!==void 0?yt:!0,validateFormats:(xe=H.validateFormats)!==null&&xe!==void 0?xe:!0,unicodeRegExp:(Et=H.unicodeRegExp)!==null&&Et!==void 0?Et:!0,int32range:(Pr=H.int32range)!==null&&Pr!==void 0?Pr:!0,uriResolver:en}}class b{constructor(O={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,O=this.opts={...O,...g(O)};const{es5:F,lines:q}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:w,es5:F,lines:q}),this.logger=D(O.logger);const E=O.validateFormats;O.validateFormats=!1,this.RULES=(0,o.getRules)(),k.call(this,m,O,"NOT SUPPORTED"),k.call(this,y,O,"DEPRECATED","warn"),this._metaOpts=A.call(this),O.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),O.keywords&&I.call(this,O.keywords),typeof O.meta=="object"&&this.addMetaSchema(O.meta),T.call(this),O.validateFormats=E}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:O,meta:F,schemaId:q}=this.opts;let E=p;q==="id"&&(E={...p},E.id=E.$id,delete E.$id),F&&O&&this.addMetaSchema(E,E[q],!1)}defaultMeta(){const{meta:O,schemaId:F}=this.opts;return this.opts.defaultMeta=typeof O=="object"?O[F]||O:void 0}validate(O,F){let q;if(typeof O=="string"){if(q=this.getSchema(O),!q)throw new Error(`no schema with key or ref "${O}"`)}else q=this.compile(O);const E=q(F);return"$async"in q||(this.errors=q.errors),E}compile(O,F){const q=this._addSchema(O,F);return q.validate||this._compileSchemaEnv(q)}compileAsync(O,F){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:q}=this.opts;return E.call(this,O,F);async function E(pe,M){await R.call(this,pe.$schema);const Z=this._addSchema(pe,M);return Z.validate||$.call(this,Z)}async function R(pe){pe&&!this.getSchema(pe)&&await E.call(this,{$ref:pe},!0)}async function $(pe){try{return this._compileSchemaEnv(pe)}catch(M){if(!(M instanceof s.default))throw M;return B.call(this,M),await W.call(this,M.missingSchema),$.call(this,pe)}}function B({missingSchema:pe,missingRef:M}){if(this.refs[pe])throw new Error(`AnySchema ${pe} is loaded but ${M} cannot be resolved`)}async function W(pe){const M=await ye.call(this,pe);this.refs[pe]||await R.call(this,M.$schema),this.refs[pe]||this.addSchema(M,pe,F)}async function ye(pe){const M=this._loading[pe];if(M)return M;try{return await(this._loading[pe]=q(pe))}finally{delete this._loading[pe]}}}addSchema(O,F,q,E=this.opts.validateSchema){if(Array.isArray(O)){for(const $ of O)this.addSchema($,void 0,q,E);return this}let R;if(typeof O=="object"){const{schemaId:$}=this.opts;if(R=O[$],R!==void 0&&typeof R!="string")throw new Error(`schema ${$} must be string`)}return F=(0,l.normalizeId)(F||R),this._checkUnique(F),this.schemas[F]=this._addSchema(O,q,F,E,!0),this}addMetaSchema(O,F,q=this.opts.validateSchema){return this.addSchema(O,F,!0,q),this}validateSchema(O,F){if(typeof O=="boolean")return!0;let q;if(q=O.$schema,q!==void 0&&typeof q!="string")throw new Error("$schema must be a string");if(q=q||this.opts.defaultMeta||this.defaultMeta(),!q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const E=this.validate(q,O);if(!E&&F){const R="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(R);else throw new Error(R)}return E}getSchema(O){let F;for(;typeof(F=S.call(this,O))=="string";)O=F;if(F===void 0){const{schemaId:q}=this.opts,E=new a.SchemaEnv({schema:{},schemaId:q});if(F=a.resolveSchema.call(this,E,O),!F)return;this.refs[O]=F}return F.validate||this._compileSchemaEnv(F)}removeSchema(O){if(O instanceof RegExp)return this._removeAllSchemas(this.schemas,O),this._removeAllSchemas(this.refs,O),this;switch(typeof O){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const F=S.call(this,O);return typeof F=="object"&&this._cache.delete(F.schema),delete this.schemas[O],delete this.refs[O],this}case"object":{const F=O;this._cache.delete(F);let q=O[this.opts.schemaId];return q&&(q=(0,l.normalizeId)(q),delete this.schemas[q],delete this.refs[q]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(O){for(const F of O)this.addKeyword(F);return this}addKeyword(O,F){let q;if(typeof O=="string")q=O,typeof F=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),F.keyword=q);else if(typeof O=="object"&&F===void 0){if(F=O,q=F.keyword,Array.isArray(q)&&!q.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(V.call(this,q,F),!F)return(0,u.eachItem)(q,R=>se.call(this,R)),this;de.call(this,F);const E={...F,type:(0,c.getJSONTypes)(F.type),schemaType:(0,c.getJSONTypes)(F.schemaType)};return(0,u.eachItem)(q,E.type.length===0?R=>se.call(this,R,E):R=>E.type.forEach($=>se.call(this,R,E,$))),this}getKeyword(O){const F=this.RULES.all[O];return typeof F=="object"?F.definition:!!F}removeKeyword(O){const{RULES:F}=this;delete F.keywords[O],delete F.all[O];for(const q of F.rules){const E=q.rules.findIndex(R=>R.keyword===O);E>=0&&q.rules.splice(E,1)}return this}addFormat(O,F){return typeof F=="string"&&(F=new RegExp(F)),this.formats[O]=F,this}errorsText(O=this.errors,{separator:F=", ",dataVar:q="data"}={}){return!O||O.length===0?"No errors":O.map(E=>`${q}${E.instancePath} ${E.message}`).reduce((E,R)=>E+F+R)}$dataMetaSchema(O,F){const q=this.RULES.all;O=JSON.parse(JSON.stringify(O));for(const E of F){const R=E.split("/").slice(1);let $=O;for(const B of R)$=$[B];for(const B in q){const W=q[B];if(typeof W!="object")continue;const{$data:ye}=W.definition,pe=$[B];ye&&pe&&($[B]=_e(pe))}}return O}_removeAllSchemas(O,F){for(const q in O){const E=O[q];(!F||F.test(q))&&(typeof E=="string"?delete O[q]:E&&!E.meta&&(this._cache.delete(E.schema),delete O[q]))}}_addSchema(O,F,q,E=this.opts.validateSchema,R=this.opts.addUsedSchema){let $;const{schemaId:B}=this.opts;if(typeof O=="object")$=O[B];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof O!="boolean")throw new Error("schema must be object or boolean")}let W=this._cache.get(O);if(W!==void 0)return W;q=(0,l.normalizeId)($||q);const ye=l.getSchemaRefs.call(this,O,q);return W=new a.SchemaEnv({schema:O,schemaId:B,meta:F,baseId:q,localRefs:ye}),this._cache.set(W.schema,W),R&&!q.startsWith("#")&&(q&&this._checkUnique(q),this.refs[q]=W),E&&this.validateSchema(O,!0),W}_checkUnique(O){if(this.schemas[O]||this.refs[O])throw new Error(`schema with key or id "${O}" already exists`)}_compileSchemaEnv(O){if(O.meta?this._compileMetaSchema(O):a.compileSchema.call(this,O),!O.validate)throw new Error("ajv implementation error");return O.validate}_compileMetaSchema(O){const F=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,O)}finally{this.opts=F}}}b.ValidationError=n.default,b.MissingRefError=s.default,t.default=b;function k(H,O,F,q="error"){for(const E in H){const R=E;R in O&&this.logger[q](`${F}: option ${E}. ${H[R]}`)}}function S(H){return H=(0,l.normalizeId)(H),this.schemas[H]||this.refs[H]}function T(){const H=this.opts.schemas;if(H)if(Array.isArray(H))this.addSchema(H);else for(const O in H)this.addSchema(H[O],O)}function x(){for(const H in this.opts.formats){const O=this.opts.formats[H];O&&this.addFormat(H,O)}}function I(H){if(Array.isArray(H)){this.addVocabulary(H);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const O in H){const F=H[O];F.keyword||(F.keyword=O),this.addKeyword(F)}}function A(){const H={...this.opts};for(const O of f)delete H[O];return H}const P={log(){},warn(){},error(){}};function D(H){if(H===!1)return P;if(H===void 0)return console;if(H.log&&H.warn&&H.error)return H;throw new Error("logger must implement log, warn and error methods")}const U=/^[a-z_$][a-z0-9_$:-]*$/i;function V(H,O){const{RULES:F}=this;if((0,u.eachItem)(H,q=>{if(F.keywords[q])throw new Error(`Keyword ${q} is already defined`);if(!U.test(q))throw new Error(`Keyword ${q} has invalid name`)}),!!O&&O.$data&&!("code"in O||"validate"in O))throw new Error('$data keyword must have "code" or "validate" function')}function se(H,O,F){var q;const E=O?.post;if(F&&E)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:R}=this;let $=E?R.post:R.rules.find(({type:W})=>W===F);if($||($={type:F,rules:[]},R.rules.push($)),R.keywords[H]=!0,!O)return;const B={keyword:H,definition:{...O,type:(0,c.getJSONTypes)(O.type),schemaType:(0,c.getJSONTypes)(O.schemaType)}};O.before?fe.call(this,$,B,O.before):$.rules.push(B),R.all[H]=B,(q=O.implements)===null||q===void 0||q.forEach(W=>this.addKeyword(W))}function fe(H,O,F){const q=H.rules.findIndex(E=>E.keyword===F);q>=0?H.rules.splice(q,0,O):(H.rules.push(O),this.logger.warn(`rule ${F} is not defined`))}function de(H){let{metaSchema:O}=H;O!==void 0&&(H.$data&&this.opts.$data&&(O=_e(O)),H.validateSchema=this.compile(O,!0))}const re={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _e(H){return{anyOf:[H,re]}}})(Ni)),Ni}var jo={},qo={},zo={},jd;function A_(){if(jd)return zo;jd=1,Object.defineProperty(zo,"__esModule",{value:!0});const t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return zo.default=t,zo}var Lr={},qd;function M_(){if(qd)return Lr;qd=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.callRef=Lr.getValidate=void 0;const t=No(),e=Ft(),r=$e(),n=Nr(),s=Fi(),o=Oe(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:p,it:h}=c,{baseId:d,schemaEnv:f,validateName:w,opts:m,self:y}=h,{root:_}=f;if((p==="#"||p==="#/")&&d===_.baseId)return b();const g=s.resolveRef.call(y,_,d,p);if(g===void 0)throw new t.default(h.opts.uriResolver,d,p);if(g instanceof s.SchemaEnv)return k(g);return S(g);function b(){if(f===_)return l(c,w,f,f.$async);const T=u.scopeValue("root",{ref:_});return l(c,(0,r._)`${T}.validate`,_,_.$async)}function k(T){const x=i(c,T);l(c,x,T,T.$async)}function S(T){const x=u.scopeValue("schema",m.code.source===!0?{ref:T,code:(0,r.stringify)(T)}:{ref:T}),I=u.name("valid"),A=c.subschema({schema:T,dataTypes:[],schemaPath:r.nil,topSchemaRef:x,errSchemaPath:p},I);c.mergeEvaluated(A),c.ok(I)}}};function i(c,u){const{gen:p}=c;return u.validate?p.scopeValue("validate",{ref:u.validate}):(0,r._)`${p.scopeValue("wrapper",{ref:u})}.validate`}Lr.getValidate=i;function l(c,u,p,h){const{gen:d,it:f}=c,{allErrors:w,schemaEnv:m,opts:y}=f,_=y.passContext?n.default.this:r.nil;h?g():b();function g(){if(!m.$async)throw new Error("async schema referenced by sync schema");const T=d.let("valid");d.try(()=>{d.code((0,r._)`await ${(0,e.callValidateCode)(c,u,_)}`),S(u),w||d.assign(T,!0)},x=>{d.if((0,r._)`!(${x} instanceof ${f.ValidationError})`,()=>d.throw(x)),k(x),w||d.assign(T,!1)}),c.ok(T)}function b(){c.result((0,e.callValidateCode)(c,u,_),()=>S(u),()=>k(u))}function k(T){const x=(0,r._)`${T}.errors`;d.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${x} : ${n.default.vErrors}.concat(${x})`),d.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function S(T){var x;if(!f.opts.unevaluated)return;const I=(x=p?.validate)===null||x===void 0?void 0:x.evaluated;if(f.props!==!0)if(I&&!I.dynamicProps)I.props!==void 0&&(f.props=o.mergeEvaluated.props(d,I.props,f.props));else{const A=d.var("props",(0,r._)`${T}.evaluated.props`);f.props=o.mergeEvaluated.props(d,A,f.props,r.Name)}if(f.items!==!0)if(I&&!I.dynamicItems)I.items!==void 0&&(f.items=o.mergeEvaluated.items(d,I.items,f.items));else{const A=d.var("items",(0,r._)`${T}.evaluated.items`);f.items=o.mergeEvaluated.items(d,A,f.items,r.Name)}}}return Lr.callRef=l,Lr.default=a,Lr}var zd;function N_(){if(zd)return qo;zd=1,Object.defineProperty(qo,"__esModule",{value:!0});const t=A_(),e=M_(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,e.default];return qo.default=r,qo}var Do={},Uo={},Dd;function L_(){if(Dd)return Uo;Dd=1,Object.defineProperty(Uo,"__esModule",{value:!0});const t=$e(),e=t.operators,r={maximum:{okStr:"<=",ok:e.LTE,fail:e.GT},minimum:{okStr:">=",ok:e.GTE,fail:e.LT},exclusiveMaximum:{okStr:"<",ok:e.LT,fail:e.GTE},exclusiveMinimum:{okStr:">",ok:e.GT,fail:e.LTE}},n={message:({keyword:o,schemaCode:a})=>(0,t.str)`must be ${r[o].okStr} ${a}`,params:({keyword:o,schemaCode:a})=>(0,t._)`{comparison: ${r[o].okStr}, limit: ${a}}`},s={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(o){const{keyword:a,data:i,schemaCode:l}=o;o.fail$data((0,t._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return Uo.default=s,Uo}var Zo={},Ud;function j_(){if(Ud)return Zo;Ud=1,Object.defineProperty(Zo,"__esModule",{value:!0});const t=$e(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){const{gen:s,data:o,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=s.let("res"),u=l?(0,t._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,t._)`${c} !== parseInt(${c})`;n.fail$data((0,t._)`(${a} === 0 || (${c} = ${o}/${a}, ${u}))`)}};return Zo.default=r,Zo}var Fo={},Vo={},Zd;function q_(){if(Zd)return Vo;Zd=1,Object.defineProperty(Vo,"__esModule",{value:!0});function t(e){const r=e.length;let n=0,s=0,o;for(;s<r;)n++,o=e.charCodeAt(s++),o>=55296&&o<=56319&&s<r&&(o=e.charCodeAt(s),(o&64512)===56320&&s++);return n}return Vo.default=t,t.code='require("ajv/dist/runtime/ucs2length").default',Vo}var Fd;function z_(){if(Fd)return Fo;Fd=1,Object.defineProperty(Fo,"__esModule",{value:!0});const t=$e(),e=Oe(),r=q_(),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:o,schemaCode:a}){const i=o==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:o})=>(0,t._)`{limit: ${o}}`},code(o){const{keyword:a,data:i,schemaCode:l,it:c}=o,u=a==="maxLength"?t.operators.GT:t.operators.LT,p=c.opts.unicode===!1?(0,t._)`${i}.length`:(0,t._)`${(0,e.useFunc)(o.gen,r.default)}(${i})`;o.fail$data((0,t._)`${p} ${u} ${l}`)}};return Fo.default=s,Fo}var Ho={},Vd;function D_(){if(Vd)return Ho;Vd=1,Object.defineProperty(Ho,"__esModule",{value:!0});const t=Ft(),e=$e(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,e.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,e._)`{pattern: ${s}}`},code(s){const{data:o,$data:a,schema:i,schemaCode:l,it:c}=s,u=c.opts.unicodeRegExp?"u":"",p=a?(0,e._)`(new RegExp(${l}, ${u}))`:(0,t.usePattern)(s,i);s.fail$data((0,e._)`!${p}.test(${o})`)}};return Ho.default=n,Ho}var Bo={},Hd;function U_(){if(Hd)return Bo;Hd=1,Object.defineProperty(Bo,"__esModule",{value:!0});const t=$e(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${o}).length ${i} ${a}`)}};return Bo.default=r,Bo}var Jo={},Bd;function Z_(){if(Bd)return Jo;Bd=1,Object.defineProperty(Jo,"__esModule",{value:!0});const t=Ft(),e=$e(),r=Oe(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:o}})=>(0,e.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,e._)`{missingProperty: ${o}}`},code(o){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:p}=o,{opts:h}=p;if(!u&&i.length===0)return;const d=i.length>=h.loopRequired;if(p.allErrors?f():w(),h.strictRequired){const _=o.parentSchema.properties,{definedProperties:g}=o.it;for(const b of i)if(_?.[b]===void 0&&!g.has(b)){const k=p.schemaEnv.baseId+p.errSchemaPath,S=`required property "${b}" is not defined at "${k}" (strictRequired)`;(0,r.checkStrictMode)(p,S,p.opts.strictRequired)}}function f(){if(d||u)o.block$data(e.nil,m);else for(const _ of i)(0,t.checkReportMissingProp)(o,_)}function w(){const _=a.let("missing");if(d||u){const g=a.let("valid",!0);o.block$data(g,()=>y(_,g)),o.ok(g)}else a.if((0,t.checkMissingProp)(o,i,_)),(0,t.reportMissingProp)(o,_),a.else()}function m(){a.forOf("prop",l,_=>{o.setParams({missingProperty:_}),a.if((0,t.noPropertyInData)(a,c,_,h.ownProperties),()=>o.error())})}function y(_,g){o.setParams({missingProperty:_}),a.forOf(_,l,()=>{a.assign(g,(0,t.propertyInData)(a,c,_,h.ownProperties)),a.if((0,e.not)(g),()=>{o.error(),a.break()})},e.nil)}}};return Jo.default=s,Jo}var Go={},Jd;function F_(){if(Jd)return Go;Jd=1,Object.defineProperty(Go,"__esModule",{value:!0});const t=$e(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:s}){const o=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${o} than ${s} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){const{keyword:s,data:o,schemaCode:a}=n,i=s==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${o}.length ${i} ${a}`)}};return Go.default=r,Go}var Wo={},Ko={},Gd;function Bi(){if(Gd)return Ko;Gd=1,Object.defineProperty(Ko,"__esModule",{value:!0});const t=Td();return t.code='require("ajv/dist/runtime/equal").default',Ko.default=t,Ko}var Wd;function V_(){if(Wd)return Wo;Wd=1,Object.defineProperty(Wo,"__esModule",{value:!0});const t=Ro(),e=$e(),r=Oe(),n=Bi(),o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,e.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,e._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:p,schemaCode:h,it:d}=a;if(!c&&!u)return;const f=i.let("valid"),w=p.items?(0,t.getSchemaTypes)(p.items):[];a.block$data(f,m,(0,e._)`${h} === false`),a.ok(f);function m(){const b=i.let("i",(0,e._)`${l}.length`),k=i.let("j");a.setParams({i:b,j:k}),i.assign(f,!0),i.if((0,e._)`${b} > 1`,()=>(y()?_:g)(b,k))}function y(){return w.length>0&&!w.some(b=>b==="object"||b==="array")}function _(b,k){const S=i.name("item"),T=(0,t.checkDataTypes)(w,S,d.opts.strictNumbers,t.DataType.Wrong),x=i.const("indices",(0,e._)`{}`);i.for((0,e._)`;${b}--;`,()=>{i.let(S,(0,e._)`${l}[${b}]`),i.if(T,(0,e._)`continue`),w.length>1&&i.if((0,e._)`typeof ${S} == "string"`,(0,e._)`${S} += "_"`),i.if((0,e._)`typeof ${x}[${S}] == "number"`,()=>{i.assign(k,(0,e._)`${x}[${S}]`),a.error(),i.assign(f,!1).break()}).code((0,e._)`${x}[${S}] = ${b}`)})}function g(b,k){const S=(0,r.useFunc)(i,n.default),T=i.name("outer");i.label(T).for((0,e._)`;${b}--;`,()=>i.for((0,e._)`${k} = ${b}; ${k}--;`,()=>i.if((0,e._)`${S}(${l}[${b}], ${l}[${k}])`,()=>{a.error(),i.assign(f,!1).break(T)})))}}};return Wo.default=o,Wo}var Yo={},Kd;function H_(){if(Kd)return Yo;Kd=1,Object.defineProperty(Yo,"__esModule",{value:!0});const t=$e(),e=Oe(),r=Bi(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:o})=>(0,t._)`{allowedValue: ${o}}`},code(o){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=o;l||u&&typeof u=="object"?o.fail$data((0,t._)`!${(0,e.useFunc)(a,r.default)}(${i}, ${c})`):o.fail((0,t._)`${u} !== ${i}`)}};return Yo.default=s,Yo}var Qo={},Yd;function B_(){if(Yd)return Qo;Yd=1,Object.defineProperty(Qo,"__esModule",{value:!0});const t=$e(),e=Oe(),r=Bi(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,t._)`{allowedValues: ${o}}`},code(o){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:p}=o;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const h=c.length>=p.opts.loopEnum;let d;const f=()=>d??(d=(0,e.useFunc)(a,r.default));let w;if(h||l)w=a.let("valid"),o.block$data(w,m);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const _=a.const("vSchema",u);w=(0,t.or)(...c.map((g,b)=>y(_,b)))}o.pass(w);function m(){a.assign(w,!1),a.forOf("v",u,_=>a.if((0,t._)`${f()}(${i}, ${_})`,()=>a.assign(w,!0).break()))}function y(_,g){const b=c[g];return typeof b=="object"&&b!==null?(0,t._)`${f()}(${i}, ${_}[${g}])`:(0,t._)`${i} === ${b}`}}};return Qo.default=s,Qo}var Qd;function J_(){if(Qd)return Do;Qd=1,Object.defineProperty(Do,"__esModule",{value:!0});const t=L_(),e=j_(),r=z_(),n=D_(),s=U_(),o=Z_(),a=F_(),i=V_(),l=H_(),c=B_(),u=[t.default,e.default,r.default,n.default,s.default,o.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return Do.default=u,Do}var Xo={},$n={},Xd;function ep(){if(Xd)return $n;Xd=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.validateAdditionalItems=void 0;const t=$e(),e=Oe(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){const{parentSchema:a,it:i}=o,{items:l}=a;if(!Array.isArray(l)){(0,e.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}s(o,l)}};function s(o,a){const{gen:i,schema:l,data:c,keyword:u,it:p}=o;p.items=!0;const h=i.const("len",(0,t._)`${c}.length`);if(l===!1)o.setParams({len:a.length}),o.pass((0,t._)`${h} <= ${a.length}`);else if(typeof l=="object"&&!(0,e.alwaysValidSchema)(p,l)){const f=i.var("valid",(0,t._)`${h} <= ${a.length}`);i.if((0,t.not)(f),()=>d(f)),o.ok(f)}function d(f){i.forRange("i",a.length,h,w=>{o.subschema({keyword:u,dataProp:w,dataPropType:e.Type.Num},f),p.allErrors||i.if((0,t.not)(f),()=>i.break())})}}return $n.validateAdditionalItems=s,$n.default=n,$n}var ea={},En={},tp;function rp(){if(tp)return En;tp=1,Object.defineProperty(En,"__esModule",{value:!0}),En.validateTuple=void 0;const t=$e(),e=Oe(),r=Ft(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){const{schema:a,it:i}=o;if(Array.isArray(a))return s(o,"additionalItems",a);i.items=!0,!(0,e.alwaysValidSchema)(i,a)&&o.ok((0,r.validateArray)(o))}};function s(o,a,i=o.schema){const{gen:l,parentSchema:c,data:u,keyword:p,it:h}=o;w(c),h.opts.unevaluated&&i.length&&h.items!==!0&&(h.items=e.mergeEvaluated.items(l,i.length,h.items));const d=l.name("valid"),f=l.const("len",(0,t._)`${u}.length`);i.forEach((m,y)=>{(0,e.alwaysValidSchema)(h,m)||(l.if((0,t._)`${f} > ${y}`,()=>o.subschema({keyword:p,schemaProp:y,dataProp:y},d)),o.ok(d))});function w(m){const{opts:y,errSchemaPath:_}=h,g=i.length,b=g===m.minItems&&(g===m.maxItems||m[a]===!1);if(y.strictTuples&&!b){const k=`"${p}" is ${g}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,e.checkStrictMode)(h,k,y.strictTuples)}}}return En.validateTuple=s,En.default=n,En}var np;function G_(){if(np)return ea;np=1,Object.defineProperty(ea,"__esModule",{value:!0});const t=rp(),e={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,t.validateTuple)(r,"items")};return ea.default=e,ea}var ta={},sp;function W_(){if(sp)return ta;sp=1,Object.defineProperty(ta,"__esModule",{value:!0});const t=$e(),e=Oe(),r=Ft(),n=ep(),o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,e.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return ta.default=o,ta}var ra={},op;function K_(){if(op)return ra;op=1,Object.defineProperty(ra,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:s,max:o}})=>o===void 0?(0,t.str)`must contain at least ${s} valid item(s)`:(0,t.str)`must contain at least ${s} and no more than ${o} valid item(s)`,params:({params:{min:s,max:o}})=>o===void 0?(0,t._)`{minContains: ${s}}`:(0,t._)`{minContains: ${s}, maxContains: ${o}}`},code(s){const{gen:o,schema:a,parentSchema:i,data:l,it:c}=s;let u,p;const{minContains:h,maxContains:d}=i;c.opts.next?(u=h===void 0?1:h,p=d):u=1;const f=o.const("len",(0,t._)`${l}.length`);if(s.setParams({min:u,max:p}),p===void 0&&u===0){(0,e.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(p!==void 0&&u>p){(0,e.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),s.fail();return}if((0,e.alwaysValidSchema)(c,a)){let g=(0,t._)`${f} >= ${u}`;p!==void 0&&(g=(0,t._)`${g} && ${f} <= ${p}`),s.pass(g);return}c.items=!0;const w=o.name("valid");p===void 0&&u===1?y(w,()=>o.if(w,()=>o.break())):u===0?(o.let(w,!0),p!==void 0&&o.if((0,t._)`${l}.length > 0`,m)):(o.let(w,!1),m()),s.result(w,()=>s.reset());function m(){const g=o.name("_valid"),b=o.let("count",0);y(g,()=>o.if(g,()=>_(b)))}function y(g,b){o.forRange("i",0,f,k=>{s.subschema({keyword:"contains",dataProp:k,dataPropType:e.Type.Num,compositeRule:!0},g),b()})}function _(g){o.code((0,t._)`${g}++`),p===void 0?o.if((0,t._)`${g} >= ${u}`,()=>o.assign(w,!0).break()):(o.if((0,t._)`${g} > ${p}`,()=>o.assign(w,!1).break()),u===1?o.assign(w,!0):o.if((0,t._)`${g} >= ${u}`,()=>o.assign(w,!0)))}}};return ra.default=n,ra}var Ji={},ap;function Y_(){return ap||(ap=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=$e(),r=Oe(),n=Ft();t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const p=c===1?"property":"properties";return(0,e.str)`must have ${p} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:p}})=>(0,e._)`{property: ${l},
6
6
  missingProperty: ${p},
7
7
  depsCount: ${c},
8
- deps: ${u}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){const[c,u]=o(l);a(l,c),i(l,u)}};function o({schema:l}){const c={},u={};for(const p in l){if(p==="__proto__")continue;const h=Array.isArray(l[p])?c:u;h[p]=l[p]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:p,it:h}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const f in c){const w=c[f];if(w.length===0)continue;const m=(0,n.propertyInData)(u,p,f,h.opts.ownProperties);l.setParams({property:f,depsCount:w.length,deps:w.join(", ")}),h.allErrors?u.if(m,()=>{for(const y of w)(0,n.checkReportMissingProp)(l,y)}):(u.if((0,e._)`${m} && (${(0,n.checkMissingProp)(l,w,d)})`),(0,n.reportMissingProp)(l,d),u.else())}}t.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:p,keyword:h,it:d}=l,f=u.name("valid");for(const w in c)(0,r.alwaysValidSchema)(d,c[w])||(u.if((0,n.propertyInData)(u,p,w,d.opts.ownProperties),()=>{const m=l.subschema({keyword:h,schemaProp:w},f);l.mergeValidEvaluated(m,f)},()=>u.var(f,!0)),l.ok(f))}t.validateSchemaDeps=i,t.default=s})(Ji)),Ji}var na={},lp;function Q_(){if(lp)return na;lp=1,Object.defineProperty(na,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:s})=>(0,t._)`{propertyName: ${s.propertyName}}`},code(s){const{gen:o,schema:a,data:i,it:l}=s;if((0,e.alwaysValidSchema)(l,a))return;const c=o.name("valid");o.forIn("key",i,u=>{s.setParams({propertyName:u}),s.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),o.if((0,t.not)(c),()=>{s.error(!0),l.allErrors||o.break()})}),s.ok(c)}};return na.default=n,na}var sa={},cp;function up(){if(cp)return sa;cp=1,Object.defineProperty(sa,"__esModule",{value:!0});const t=Ft(),e=$e(),r=Nr(),n=Oe(),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,e._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:p,it:h}=a;if(!p)throw new Error("ajv implementation error");const{allErrors:d,opts:f}=h;if(h.props=!0,f.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(h,l))return;const w=(0,t.allSchemaProperties)(c.properties),m=(0,t.allSchemaProperties)(c.patternProperties);y(),a.ok((0,e._)`${p} === ${r.default.errors}`);function y(){i.forIn("key",u,S=>{!w.length&&!m.length?b(S):i.if(_(S),()=>b(S))})}function _(S){let T;if(w.length>8){const x=(0,n.schemaRefOrVal)(h,c.properties,"properties");T=(0,t.isOwnProperty)(i,x,S)}else w.length?T=(0,e.or)(...w.map(x=>(0,e._)`${S} === ${x}`)):T=e.nil;return m.length&&(T=(0,e.or)(T,...m.map(x=>(0,e._)`${(0,t.usePattern)(a,x)}.test(${S})`))),(0,e.not)(T)}function g(S){i.code((0,e._)`delete ${u}[${S}]`)}function b(S){if(f.removeAdditional==="all"||f.removeAdditional&&l===!1){g(S);return}if(l===!1){a.setParams({additionalProperty:S}),a.error(),d||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(h,l)){const T=i.name("valid");f.removeAdditional==="failing"?(k(S,T,!1),i.if((0,e.not)(T),()=>{a.reset(),g(S)})):(k(S,T),d||i.if((0,e.not)(T),()=>i.break()))}}function k(S,T,x){const I={keyword:"additionalProperties",dataProp:S,dataPropType:n.Type.Str};x===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,T)}}};return sa.default=o,sa}var oa={},dp;function X_(){if(dp)return oa;dp=1,Object.defineProperty(oa,"__esModule",{value:!0});const t=Oo(),e=Ft(),r=Oe(),n=up(),s={keyword:"properties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=o;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new t.KeywordCxt(u,n.default,"additionalProperties"));const p=(0,e.allSchemaProperties)(i);for(const m of p)u.definedProperties.add(m);u.opts.unevaluated&&p.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(p),u.props));const h=p.filter(m=>!(0,r.alwaysValidSchema)(u,i[m]));if(h.length===0)return;const d=a.name("valid");for(const m of h)f(m)?w(m):(a.if((0,e.propertyInData)(a,c,m,u.opts.ownProperties)),w(m),u.allErrors||a.else().var(d,!0),a.endIf()),o.it.definedProperties.add(m),o.ok(d);function f(m){return u.opts.useDefaults&&!u.compositeRule&&i[m].default!==void 0}function w(m){o.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}}};return oa.default=s,oa}var aa={},pp;function ey(){if(pp)return aa;pp=1,Object.defineProperty(aa,"__esModule",{value:!0});const t=Ft(),e=$e(),r=Oe(),n=Oe(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=o,{opts:p}=u,h=(0,t.allSchemaProperties)(i),d=h.filter(b=>(0,r.alwaysValidSchema)(u,i[b]));if(h.length===0||d.length===h.length&&(!u.opts.unevaluated||u.props===!0))return;const f=p.strictSchema&&!p.allowMatchingProperties&&c.properties,w=a.name("valid");u.props!==!0&&!(u.props instanceof e.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:m}=u;y();function y(){for(const b of h)f&&_(b),u.allErrors?g(b):(a.var(w,!0),g(b),a.if(w))}function _(b){for(const k in f)new RegExp(b).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function g(b){a.forIn("key",l,k=>{a.if((0,e._)`${(0,t.usePattern)(o,b)}.test(${k})`,()=>{const S=d.includes(b);S||o.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:n.Type.Str},w),u.opts.unevaluated&&m!==!0?a.assign((0,e._)`${m}[${k}]`,!0):!S&&!u.allErrors&&a.if((0,e.not)(w),()=>a.break())})})}}};return aa.default=s,aa}var ia={},fp;function ty(){if(fp)return ia;fp=1,Object.defineProperty(ia,"__esModule",{value:!0});const t=Oe(),e={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:s,it:o}=r;if((0,t.alwaysValidSchema)(o,s)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return ia.default=e,ia}var la={},hp;function ry(){if(hp)return la;hp=1,Object.defineProperty(la,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ft().validateUnion,error:{message:"must match a schema in anyOf"}};return la.default=e,la}var ca={},mp;function ny(){if(mp)return ca;mp=1,Object.defineProperty(ca,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:s})=>(0,t._)`{passingSchemas: ${s.passing}}`},code(s){const{gen:o,schema:a,parentSchema:i,it:l}=s;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=o.let("valid",!1),p=o.let("passing",null),h=o.name("_valid");s.setParams({passing:p}),o.block(d),s.result(u,()=>s.reset(),()=>s.error(!0));function d(){c.forEach((f,w)=>{let m;(0,e.alwaysValidSchema)(l,f)?o.var(h,!0):m=s.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},h),w>0&&o.if((0,t._)`${h} && ${u}`).assign(u,!1).assign(p,(0,t._)`[${p}, ${w}]`).else(),o.if(h,()=>{o.assign(u,!0),o.assign(p,w),m&&s.mergeEvaluated(m,t.Name)})})}}};return ca.default=n,ca}var ua={},gp;function sy(){if(gp)return ua;gp=1,Object.defineProperty(ua,"__esModule",{value:!0});const t=Oe(),e={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:s,it:o}=r;if(!Array.isArray(s))throw new Error("ajv implementation error");const a=n.name("valid");s.forEach((i,l)=>{if((0,t.alwaysValidSchema)(o,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return ua.default=e,ua}var da={},vp;function oy(){if(vp)return da;vp=1,Object.defineProperty(da,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:o})=>(0,t.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,t._)`{failingKeyword: ${o.ifClause}}`},code(o){const{gen:a,parentSchema:i,it:l}=o;i.then===void 0&&i.else===void 0&&(0,e.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=s(l,"then"),u=s(l,"else");if(!c&&!u)return;const p=a.let("valid",!0),h=a.name("_valid");if(d(),o.reset(),c&&u){const w=a.let("ifClause");o.setParams({ifClause:w}),a.if(h,f("then",w),f("else",w))}else c?a.if(h,f("then")):a.if((0,t.not)(h),f("else"));o.pass(p,()=>o.error(!0));function d(){const w=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},h);o.mergeEvaluated(w)}function f(w,m){return()=>{const y=o.subschema({keyword:w},h);a.assign(p,h),o.mergeValidEvaluated(y,p),m?a.assign(m,(0,t._)`${w}`):o.setParams({ifClause:w})}}}};function s(o,a){const i=o.schema[a];return i!==void 0&&!(0,e.alwaysValidSchema)(o,i)}return da.default=n,da}var pa={},_p;function ay(){if(_p)return pa;_p=1,Object.defineProperty(pa,"__esModule",{value:!0});const t=Oe(),e={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:s}){n.if===void 0&&(0,t.checkStrictMode)(s,`"${r}" without "if" is ignored`)}};return pa.default=e,pa}var yp;function iy(){if(yp)return Xo;yp=1,Object.defineProperty(Xo,"__esModule",{value:!0});const t=tp(),e=G_(),r=np(),n=W_(),s=K_(),o=Y_(),a=Q_(),i=up(),l=X_(),c=ey(),u=ty(),p=ry(),h=ny(),d=sy(),f=oy(),w=ay();function m(y=!1){const _=[u.default,p.default,h.default,d.default,f.default,w.default,a.default,i.default,o.default,l.default,c.default];return y?_.push(e.default,n.default):_.push(t.default,r.default),_.push(s.default),_}return Xo.default=m,Xo}var fa={},ha={},wp;function ly(){if(wp)return ha;wp=1,Object.defineProperty(ha,"__esModule",{value:!0});const t=$e(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,s){const{gen:o,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:p,errSchemaPath:h,schemaEnv:d,self:f}=u;if(!p.validateFormats)return;i?w():m();function w(){const y=o.scopeValue("formats",{ref:f.formats,code:p.code.formats}),_=o.const("fDef",(0,t._)`${y}[${c}]`),g=o.let("fType"),b=o.let("format");o.if((0,t._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>o.assign(g,(0,t._)`${_}.type || "string"`).assign(b,(0,t._)`${_}.validate`),()=>o.assign(g,(0,t._)`"string"`).assign(b,_)),n.fail$data((0,t.or)(k(),S()));function k(){return p.strictSchema===!1?t.nil:(0,t._)`${c} && !${b}`}function S(){const T=d.$async?(0,t._)`(${_}.async ? await ${b}(${a}) : ${b}(${a}))`:(0,t._)`${b}(${a})`,x=(0,t._)`(typeof ${b} == "function" ? ${T} : ${b}.test(${a}))`;return(0,t._)`${b} && ${b} !== true && ${g} === ${s} && !${x}`}}function m(){const y=f.formats[l];if(!y){k();return}if(y===!0)return;const[_,g,b]=S(y);_===s&&n.pass(T());function k(){if(p.strictSchema===!1){f.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${l}" ignored in schema at path "${h}"`}}function S(x){const I=x instanceof RegExp?(0,t.regexpCode)(x):p.code.formats?(0,t._)`${p.code.formats}${(0,t.getProperty)(l)}`:void 0,A=o.scopeValue("formats",{key:l,ref:x,code:I});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,t._)`${A}.validate`]:["string",x,A]}function T(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,t._)`await ${b}(${a})`}return typeof g=="function"?(0,t._)`${b}(${a})`:(0,t._)`${b}.test(${a})`}}}};return ha.default=r,ha}var bp;function cy(){if(bp)return fa;bp=1,Object.defineProperty(fa,"__esModule",{value:!0});const e=[ly().default];return fa.default=e,fa}var sn={},kp;function uy(){return kp||(kp=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.contentVocabulary=sn.metadataVocabulary=void 0,sn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],sn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),sn}var Sp;function dy(){if(Sp)return jo;Sp=1,Object.defineProperty(jo,"__esModule",{value:!0});const t=N_(),e=J_(),r=iy(),n=cy(),s=uy(),o=[t.default,e.default,(0,r.default)(),n.default,s.metadataVocabulary,s.contentVocabulary];return jo.default=o,jo}var ma={},fs={},Tp;function py(){if(Tp)return fs;Tp=1,Object.defineProperty(fs,"__esModule",{value:!0}),fs.DiscrError=void 0;var t;return(function(e){e.Tag="tag",e.Mapping="mapping"})(t||(fs.DiscrError=t={})),fs}var Cp;function fy(){if(Cp)return ma;Cp=1,Object.defineProperty(ma,"__esModule",{value:!0});const t=$e(),e=py(),r=Fi(),n=No(),s=Oe(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===e.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,t._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:p,it:h}=i,{oneOf:d}=p;if(!h.opts.discriminator)throw new Error("discriminator: requires discriminator option");const f=u.propertyName;if(typeof f!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const w=l.let("valid",!1),m=l.const("tag",(0,t._)`${c}${(0,t.getProperty)(f)}`);l.if((0,t._)`typeof ${m} == "string"`,()=>y(),()=>i.error(!1,{discrError:e.DiscrError.Tag,tag:m,tagName:f})),i.ok(w);function y(){const b=g();l.if(!1);for(const k in b)l.elseIf((0,t._)`${m} === ${k}`),l.assign(w,_(b[k]));l.else(),i.error(!1,{discrError:e.DiscrError.Mapping,tag:m,tagName:f}),l.endIf()}function _(b){const k=l.name("valid"),S=i.subschema({keyword:"oneOf",schemaProp:b},k);return i.mergeEvaluated(S,t.Name),k}function g(){var b;const k={},S=x(p);let T=!0;for(let P=0;P<d.length;P++){let D=d[P];if(D?.$ref&&!(0,s.schemaHasRulesButRef)(D,h.self.RULES)){const V=D.$ref;if(D=r.resolveRef.call(h.self,h.schemaEnv.root,h.baseId,V),D instanceof r.SchemaEnv&&(D=D.schema),D===void 0)throw new n.default(h.opts.uriResolver,h.baseId,V)}const U=(b=D?.properties)===null||b===void 0?void 0:b[f];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);T=T&&(S||x(D)),I(U,P)}if(!T)throw new Error(`discriminator: "${f}" must be required`);return k;function x({required:P}){return Array.isArray(P)&&P.includes(f)}function I(P,D){if(P.const)A(P.const,D);else if(P.enum)for(const U of P.enum)A(U,D);else throw new Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function A(P,D){if(typeof P!="string"||P in k)throw new Error(`discriminator: "${f}" values must be unique strings`);k[P]=D}}}};return ma.default=a,ma}const hy={$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 $p;function Ep(){return $p||($p=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const r=O_(),n=dy(),s=fy(),o=hy,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(o,a):o;this.addMetaSchema(f,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=Oo();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=$e();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var p=Zi();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var h=No();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})($o,$o.exports)),$o.exports}var xp=Ep();const my=tn(xp);var Re;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},t.getValidEnumValues=s=>{const o=t.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(const i of o)a[i]=s[i];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},t.find=(s,o)=>{for(const a of s)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Re||(Re={}));var Gi;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Gi||(Gi={}));const oe=Re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kr=t=>{switch(typeof t){case"undefined":return oe.undefined;case"string":return oe.string;case"number":return Number.isNaN(t)?oe.nan:oe.number;case"boolean":return oe.boolean;case"function":return oe.function;case"bigint":return oe.bigint;case"symbol":return oe.symbol;case"object":return Array.isArray(t)?oe.array:t===null?oe.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?oe.promise:typeof Map<"u"&&t instanceof Map?oe.map:typeof Set<"u"&&t instanceof Set?oe.set:typeof Date<"u"&&t instanceof Date?oe.date:oe.object;default:return oe.unknown}},Y=Re.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"]),gy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class Rt extends Error{get errors(){return this.issues}constructor(e){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=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof Rt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Rt.create=t=>new Rt(t);const xn=(t,e)=>{let r;switch(t.code){case Y.invalid_type:t.received===oe.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Re.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:r=`Unrecognized key(s) in object: ${Re.joinValues(t.keys,", ")}`;break;case Y.invalid_union:r="Invalid input";break;case Y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Re.joinValues(t.options)}`;break;case Y.invalid_enum_value:r=`Invalid enum value. Expected ${Re.joinValues(t.options)}, received '${t.received}'`;break;case Y.invalid_arguments:r="Invalid function arguments";break;case Y.invalid_return_type:r="Invalid function return type";break;case Y.invalid_date:r="Invalid date";break;case Y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Re.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Y.custom:r="Invalid input";break;case Y.invalid_intersection_types:r="Intersection results could not be merged";break;case Y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Y.not_finite:r="Number must be finite";break;default:r=e.defaultError,Re.assertNever(t)}return{message:r}};let Ip=xn;function vy(t){Ip=t}function ga(){return Ip}const va=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:e,defaultError:i}).message;return{...s,path:o,message:i}},_y=[];function te(t,e){const r=ga(),n=va({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===xn?void 0:xn].filter(s=>!!s)});t.common.issues.push(n)}class ct{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return me;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return ct.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return me;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const me=Object.freeze({status:"aborted"}),In=t=>({status:"dirty",value:t}),ft=t=>({status:"valid",value:t}),Wi=t=>t.status==="aborted",Ki=t=>t.status==="dirty",on=t=>t.status==="valid",hs=t=>typeof Promise<"u"&&t instanceof Promise;var le;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(le||(le={}));class sr{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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 Rp=(t,e)=>{if(on(e))return{success:!0,data:e.value};if(!t.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 Rt(t.common.issues);return this._error=r,this._error}}};function ke(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{const{message:l}=t;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:s}}let Te=class{get description(){return this._def.description}_getType(e){return kr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ct,ctx:{common:e.parent.common,data:e.data,parsedType:kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(hs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Rp(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kr(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return on(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:e,path:[],parent:r}).then(n=>on(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(hs(s)?s:Promise.resolve(s));return Rp(n,o)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{const a=e(s),i=()=>o.addIssue({code:Y.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Vt({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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 ar.create(this,this._def)}nullable(){return qr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return cn.create(this)}promise(){return Mn.create(this,this._def)}or(e){return ys.create([this,e],this._def)}and(e){return ws.create(this,e,this._def)}transform(e){return new Vt({...ke(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Cs({...ke(this._def),innerType:this,defaultValue:r,typeName:z.ZodDefault})}brand(){return new Xi({typeName:z.ZodBranded,type:this,...ke(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new $s({...ke(this._def),innerType:this,catchValue:r,typeName:z.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Es.create(this,e)}readonly(){return xs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const yy=/^c[^\s-]{8,}$/i,wy=/^[0-9a-z]+$/,by=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ky=/^[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,Sy=/^[a-z0-9_-]{21}$/i,Ty=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cy=/^[-+]?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)?)??$/,$y=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ey="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Yi;const xy=/^(?:(?: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])$/,Iy=/^(?:(?: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])$/,Ry=/^(([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]))$/,Py=/^(([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])$/,Oy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ay=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pp="((\\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])))",My=new RegExp(`^${Pp}$`);function Op(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Ny(t){return new RegExp(`^${Op(t)}$`)}function Ap(t){let e=`${Pp}T${Op(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ly(t,e){return!!((e==="v4"||!e)&&xy.test(t)||(e==="v6"||!e)&&Ry.test(t))}function jy(t,e){if(!Ty.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function qy(t,e){return!!((e==="v4"||!e)&&Iy.test(t)||(e==="v6"||!e)&&Py.test(t))}let Rn=class Co extends Te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==oe.string){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_type,expected:oe.string,received:o.parsedType}),me}const n=new ct;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,i=e.data.length<o.value;(a||i)&&(s=this._getOrReturnCtx(e,s),a?te(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&te(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")$y.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"email",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Yi||(Yi=new RegExp(Ey,"u")),Yi.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"emoji",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ky.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"uuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Sy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"nanoid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")yy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")wy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cuid2",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")by.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"ulid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),te(s,{validation:"url",code:Y.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"regex",code:Y.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Ap(o).test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?My.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Ny(o).test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Cy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"duration",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Ly(e.data,o.version)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"ip",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?jy(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"jwt",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?qy(e.data,o.version)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cidr",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Oy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"base64",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Ay.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"base64url",code:Y.invalid_string,message:o.message}),n.dirty()):Re.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:Y.invalid_string,...le.errToObj(n)})}_addCheck(e){return new Co({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...le.errToObj(e)})}url(e){return this._addCheck({kind:"url",...le.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...le.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...le.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...le.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...le.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...le.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...le.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...le.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...le.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...le.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...le.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...le.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...le.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...le.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...le.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...le.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...le.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...le.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...le.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...le.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...le.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...le.errToObj(r)})}nonempty(e){return this.min(1,le.errToObj(e))}trim(){return new Co({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Co({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Co({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rn.create=t=>new Rn({checks:[],typeName:z.ZodString,coerce:t?.coerce??!1,...ke(t)});function zy(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}let ms=class nd extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==oe.number){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_type,expected:oe.number,received:o.parsedType}),me}let n;const s=new ct;for(const o of this._def.checks)o.kind==="int"?Re.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:Y.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?zy(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:Y.not_finite,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,le.toString(r))}gt(e,r){return this.setLimit("min",e,!1,le.toString(r))}lte(e,r){return this.setLimit("max",e,!0,le.toString(r))}lt(e,r){return this.setLimit("max",e,!1,le.toString(r))}setLimit(e,r,n,s){return new nd({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:le.toString(s)}]})}_addCheck(e){return new nd({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:le.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:le.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:le.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:le.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:le.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:le.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:le.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:le.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:le.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Re.isInteger(e.value))}get isFinite(){let e=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"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};ms.create=t=>new ms({checks:[],typeName:z.ZodNumber,coerce:t?.coerce||!1,...ke(t)});class jr extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==oe.bigint)return this._getInvalidInput(e);let n;const s=new ct;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return te(r,{code:Y.invalid_type,expected:oe.bigint,received:r.parsedType}),me}gte(e,r){return this.setLimit("min",e,!0,le.toString(r))}gt(e,r){return this.setLimit("min",e,!1,le.toString(r))}lte(e,r){return this.setLimit("max",e,!0,le.toString(r))}lt(e,r){return this.setLimit("max",e,!1,le.toString(r))}setLimit(e,r,n,s){return new jr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:le.toString(s)}]})}_addCheck(e){return new jr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:le.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:le.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:le.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:le.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:le.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}jr.create=t=>new jr({checks:[],typeName:z.ZodBigInt,coerce:t?.coerce??!1,...ke(t)});let gs=class extends Te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==oe.boolean){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.boolean,received:n.parsedType}),me}return ft(e.data)}};gs.create=t=>new gs({typeName:z.ZodBoolean,coerce:t?.coerce||!1,...ke(t)});class an extends Te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==oe.date){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_type,expected:oe.date,received:o.parsedType}),me}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_date}),me}const n=new ct;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Re.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new an({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:le.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:le.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}an.create=t=>new an({checks:[],coerce:t?.coerce||!1,typeName:z.ZodDate,...ke(t)});class _a extends Te{_parse(e){if(this._getType(e)!==oe.symbol){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.symbol,received:n.parsedType}),me}return ft(e.data)}}_a.create=t=>new _a({typeName:z.ZodSymbol,...ke(t)});class vs extends Te{_parse(e){if(this._getType(e)!==oe.undefined){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.undefined,received:n.parsedType}),me}return ft(e.data)}}vs.create=t=>new vs({typeName:z.ZodUndefined,...ke(t)});let _s=class extends Te{_parse(e){if(this._getType(e)!==oe.null){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.null,received:n.parsedType}),me}return ft(e.data)}};_s.create=t=>new _s({typeName:z.ZodNull,...ke(t)});let Pn=class extends Te{constructor(){super(...arguments),this._any=!0}_parse(e){return ft(e.data)}};Pn.create=t=>new Pn({typeName:z.ZodAny,...ke(t)});let ln=class extends Te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ft(e.data)}};ln.create=t=>new ln({typeName:z.ZodUnknown,...ke(t)});let Sr=class extends Te{_parse(e){const r=this._getOrReturnCtx(e);return te(r,{code:Y.invalid_type,expected:oe.never,received:r.parsedType}),me}};Sr.create=t=>new Sr({typeName:z.ZodNever,...ke(t)});class ya extends Te{_parse(e){if(this._getType(e)!==oe.undefined){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.void,received:n.parsedType}),me}return ft(e.data)}}ya.create=t=>new ya({typeName:z.ZodVoid,...ke(t)});let cn=class Mi extends Te{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==oe.array)return te(r,{code:Y.invalid_type,expected:oe.array,received:r.parsedType}),me;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,i=r.data.length<s.exactLength.value;(a||i)&&(te(r,{code:a?Y.too_big:Y.too_small,minimum:i?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(te(r,{code:Y.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(te(r,{code:Y.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>s.type._parseAsync(new sr(r,a,r.path,i)))).then(a=>ct.mergeArray(n,a));const o=[...r.data].map((a,i)=>s.type._parseSync(new sr(r,a,r.path,i)));return ct.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new Mi({...this._def,minLength:{value:e,message:le.toString(r)}})}max(e,r){return new Mi({...this._def,maxLength:{value:e,message:le.toString(r)}})}length(e,r){return new Mi({...this._def,exactLength:{value:e,message:le.toString(r)}})}nonempty(e){return this.min(1,e)}};cn.create=(t,e)=>new cn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...ke(e)});function On(t){if(t instanceof Lt){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ar.create(On(n))}return new Lt({...t._def,shape:()=>e})}else return t instanceof cn?new cn({...t._def,type:On(t.element)}):t instanceof ar?ar.create(On(t.unwrap())):t instanceof qr?qr.create(On(t.unwrap())):t instanceof or?or.create(t.items.map(e=>On(e))):t}let Lt=class nr extends Te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Re.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==oe.object){const c=this._getOrReturnCtx(e);return te(c,{code:Y.invalid_type,expected:oe.object,received:c.parsedType}),me}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Sr&&this._def.unknownKeys==="strip"))for(const c in s.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=o[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new sr(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Sr){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")i.length>0&&(te(s,{code:Y.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const p=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new sr(s,p,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const p=await u.key,h=await u.value;c.push({key:p,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>ct.mergeObjectSync(n,c)):ct.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return le.errToObj,new nr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:le.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new nr({...this._def,unknownKeys:"strip"})}passthrough(){return new nr({...this._def,unknownKeys:"passthrough"})}extend(e){return new nr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new nr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:z.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new nr({...this._def,catchall:e})}pick(e){const r={};for(const n of Re.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new nr({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Re.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new nr({...this._def,shape:()=>r})}deepPartial(){return On(this)}partial(e){const r={};for(const n of Re.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new nr({...this._def,shape:()=>r})}required(e){const r={};for(const n of Re.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ar;)o=o._def.innerType;r[n]=o}return new nr({...this._def,shape:()=>r})}keyof(){return Lp(Re.objectKeys(this.shape))}};Lt.create=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strip",catchall:Sr.create(),typeName:z.ZodObject,...ke(e)}),Lt.strictCreate=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strict",catchall:Sr.create(),typeName:z.ZodObject,...ke(e)}),Lt.lazycreate=(t,e)=>new Lt({shape:t,unknownKeys:"strip",catchall:Sr.create(),typeName:z.ZodObject,...ke(e)});let ys=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(i=>new Rt(i.ctx.common.issues));return te(r,{code:Y.invalid_union,unionErrors:a}),me}if(r.common.async)return Promise.all(n.map(async o=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(l=>new Rt(l));return te(r,{code:Y.invalid_union,unionErrors:i}),me}}get options(){return this._def.options}};ys.create=(t,e)=>new ys({options:t,typeName:z.ZodUnion,...ke(e)});const Tr=t=>t instanceof bs?Tr(t.schema):t instanceof Vt?Tr(t.innerType()):t instanceof ks?[t.value]:t instanceof Ss?t.options:t instanceof Ts?Re.objectValues(t.enum):t instanceof Cs?Tr(t._def.innerType):t instanceof vs?[void 0]:t instanceof _s?[null]:t instanceof ar?[void 0,...Tr(t.unwrap())]:t instanceof qr?[null,...Tr(t.unwrap())]:t instanceof Xi||t instanceof xs?Tr(t.unwrap()):t instanceof $s?Tr(t._def.innerType):[];let Mp=class y_ extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.object)return te(r,{code:Y.invalid_type,expected:oe.object,received:r.parsedType}),me;const n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(te(r,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),me)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const o of r){const a=Tr(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of a){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,o)}}return new y_({typeName:z.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...ke(n)})}};function Qi(t,e){const r=kr(t),n=kr(e);if(t===e)return{valid:!0,data:t};if(r===oe.object&&n===oe.object){const s=Re.objectKeys(e),o=Re.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(const i of o){const l=Qi(t[i],e[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===oe.array&&n===oe.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<t.length;o++){const a=t[o],i=e[o],l=Qi(a,i);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return r===oe.date&&n===oe.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let ws=class extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Wi(o)||Wi(a))return me;const i=Qi(o.value,a.value);return i.valid?((Ki(o)||Ki(a))&&r.dirty(),{status:r.value,value:i.data}):(te(n,{code:Y.invalid_intersection_types}),me)};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(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ws.create=(t,e,r)=>new ws({left:t,right:e,typeName:z.ZodIntersection,...ke(r)});class or extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.array)return te(n,{code:Y.invalid_type,expected:oe.array,received:n.parsedType}),me;if(n.data.length<this._def.items.length)return te(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),me;!this._def.rest&&n.data.length>this._def.items.length&&(te(n,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new sr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ct.mergeArray(r,a)):ct.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new or({...this._def,rest:e})}}or.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new or({items:t,typeName:z.ZodTuple,rest:null,...ke(e)})};let Np=class sd extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.object)return te(n,{code:Y.invalid_type,expected:oe.object,received:n.parsedType}),me;const s=[],o=this._def.keyType,a=this._def.valueType;for(const i in n.data)s.push({key:o._parse(new sr(n,i,n.path,i)),value:a._parse(new sr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?ct.mergeObjectAsync(r,s):ct.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Te?new sd({keyType:e,valueType:r,typeName:z.ZodRecord,...ke(n)}):new sd({keyType:Rn.create(),valueType:e,typeName:z.ZodRecord,...ke(r)})}};class wa extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.map)return te(n,{code:Y.invalid_type,expected:oe.map,received:n.parsedType}),me;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:s._parse(new sr(n,i,n.path,[c,"key"])),value:o._parse(new sr(n,l,n.path,[c,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return me;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of a){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return me;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}wa.create=(t,e,r)=>new wa({valueType:e,keyType:t,typeName:z.ZodMap,...ke(r)});class un extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.set)return te(n,{code:Y.invalid_type,expected:oe.set,received:n.parsedType}),me;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(te(n,{code:Y.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(te(n,{code:Y.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const o=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return me;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>o._parse(new sr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(e,r){return new un({...this._def,minSize:{value:e,message:le.toString(r)}})}max(e,r){return new un({...this._def,maxSize:{value:e,message:le.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}un.create=(t,e)=>new un({valueType:t,minSize:null,maxSize:null,typeName:z.ZodSet,...ke(e)});class An extends Te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.function)return te(r,{code:Y.invalid_type,expected:oe.function,received:r.parsedType}),me;function n(i,l){return va({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ga(),xn].filter(c=>!!c),issueData:{code:Y.invalid_arguments,argumentsError:l}})}function s(i,l){return va({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ga(),xn].filter(c=>!!c),issueData:{code:Y.invalid_return_type,returnTypeError:l}})}const o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Mn){const i=this;return ft(async function(...l){const c=new Rt([]),u=await i._def.args.parseAsync(l,o).catch(d=>{throw c.addIssue(n(l,d)),c}),p=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(p,o).catch(d=>{throw c.addIssue(s(p,d)),c})})}else{const i=this;return ft(function(...l){const c=i._def.args.safeParse(l,o);if(!c.success)throw new Rt([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),p=i._def.returns.safeParse(u,o);if(!p.success)throw new Rt([s(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new An({...this._def,args:or.create(e).rest(ln.create())})}returns(e){return new An({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new An({args:e||or.create([]).rest(ln.create()),returns:r||ln.create(),typeName:z.ZodFunction,...ke(n)})}}let bs=class extends Te{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};bs.create=(t,e)=>new bs({getter:t,typeName:z.ZodLazy,...ke(e)});let ks=class extends Te{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return te(r,{received:r.data,code:Y.invalid_literal,expected:this._def.value}),me}return{status:"valid",value:e.data}}get value(){return this._def.value}};ks.create=(t,e)=>new ks({value:t,typeName:z.ZodLiteral,...ke(e)});function Lp(t,e){return new Ss({values:t,typeName:z.ZodEnum,...ke(e)})}let Ss=class od extends Te{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{expected:Re.joinValues(n),received:r.parsedType,code:Y.invalid_type}),me}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{received:r.data,code:Y.invalid_enum_value,options:n}),me}return ft(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return od.create(e,{...this._def,...r})}exclude(e,r=this._def){return od.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ss.create=Lp;class Ts extends Te{_parse(e){const r=Re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==oe.string&&n.parsedType!==oe.number){const s=Re.objectValues(r);return te(n,{expected:Re.joinValues(s),received:n.parsedType,code:Y.invalid_type}),me}if(this._cache||(this._cache=new Set(Re.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Re.objectValues(r);return te(n,{received:n.data,code:Y.invalid_enum_value,options:s}),me}return ft(e.data)}get enum(){return this._def.values}}Ts.create=(t,e)=>new Ts({values:t,typeName:z.ZodNativeEnum,...ke(e)});class Mn extends Te{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.promise&&r.common.async===!1)return te(r,{code:Y.invalid_type,expected:oe.promise,received:r.parsedType}),me;const n=r.parsedType===oe.promise?r.data:Promise.resolve(r.data);return ft(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Mn.create=(t,e)=>new Mn({type:t,typeName:z.ZodPromise,...ke(e)});class Vt extends Te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{te(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return me;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?me:l.status==="dirty"||r.value==="dirty"?In(l.value):l});{if(r.value==="aborted")return me;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?me:i.status==="dirty"||r.value==="dirty"?In(i.value):i}}if(s.type==="refinement"){const a=i=>{const l=s.refinement(i,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?me:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?me:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!on(a))return me;const i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>on(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:r.value,value:i})):me);Re.assertNever(s)}}Vt.create=(t,e,r)=>new Vt({schema:t,typeName:z.ZodEffects,effect:e,...ke(r)}),Vt.createWithPreprocess=(t,e,r)=>new Vt({schema:e,effect:{type:"preprocess",transform:t},typeName:z.ZodEffects,...ke(r)});let ar=class extends Te{_parse(e){return this._getType(e)===oe.undefined?ft(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ar.create=(t,e)=>new ar({innerType:t,typeName:z.ZodOptional,...ke(e)});let qr=class extends Te{_parse(e){return this._getType(e)===oe.null?ft(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qr.create=(t,e)=>new qr({innerType:t,typeName:z.ZodNullable,...ke(e)});let Cs=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===oe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Cs.create=(t,e)=>new Cs({innerType:t,typeName:z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ke(e)});let $s=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return hs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Rt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Rt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};$s.create=(t,e)=>new $s({innerType:t,typeName:z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ke(e)});class ba extends Te{_parse(e){if(this._getType(e)!==oe.nan){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.nan,received:n.parsedType}),me}return{status:"valid",value:e.data}}}ba.create=t=>new ba({typeName:z.ZodNaN,...ke(t)});const Dy=Symbol("zod_brand");class Xi extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Es extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?me:o.status==="dirty"?(r.dirty(),In(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?me:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Es({in:e,out:r,typeName:z.ZodPipeline})}}let xs=class extends Te{_parse(e){const r=this._def.innerType._parse(e),n=s=>(on(s)&&(s.value=Object.freeze(s.value)),s);return hs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};xs.create=(t,e)=>new xs({innerType:t,typeName:z.ZodReadonly,...ke(e)});function jp(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function qp(t,e={},r){return t?Pn.create().superRefine((n,s)=>{const o=t(n);if(o instanceof Promise)return o.then(a=>{if(!a){const i=jp(e,n),l=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:l})}});if(!o){const a=jp(e,n),i=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:i})}}):Pn.create()}const Uy={object:Lt.lazycreate};var z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(z||(z={}));const Zy=(t,e={message:`Input not instance of ${t.name}`})=>qp(r=>r instanceof t,e),zp=Rn.create,Dp=ms.create,Fy=ba.create,Vy=jr.create,Up=gs.create,Hy=an.create,By=_a.create,Jy=vs.create,Gy=_s.create,Wy=Pn.create,Ky=ln.create,Yy=Sr.create,Qy=ya.create,Xy=cn.create,Zp=Lt.create,e1=Lt.strictCreate,t1=ys.create,r1=Mp.create,n1=ws.create,s1=or.create,o1=Np.create,a1=wa.create,i1=un.create,l1=An.create,c1=bs.create,u1=ks.create,d1=Ss.create,p1=Ts.create,f1=Mn.create,Fp=Vt.create,h1=ar.create,m1=qr.create,g1=Vt.createWithPreprocess,v1=Es.create,_1=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Dy,DIRTY:In,EMPTY_PATH:_y,INVALID:me,NEVER:me,OK:ft,ParseStatus:ct,Schema:Te,ZodAny:Pn,ZodArray:cn,ZodBigInt:jr,ZodBoolean:gs,ZodBranded:Xi,ZodCatch:$s,ZodDate:an,ZodDefault:Cs,ZodDiscriminatedUnion:Mp,ZodEffects:Vt,ZodEnum:Ss,ZodError:Rt,get ZodFirstPartyTypeKind(){return z},ZodFunction:An,ZodIntersection:ws,ZodIssueCode:Y,ZodLazy:bs,ZodLiteral:ks,ZodMap:wa,ZodNaN:ba,ZodNativeEnum:Ts,ZodNever:Sr,ZodNull:_s,ZodNullable:qr,ZodNumber:ms,ZodObject:Lt,ZodOptional:ar,ZodParsedType:oe,ZodPipeline:Es,ZodPromise:Mn,ZodReadonly:xs,ZodRecord:Np,ZodSchema:Te,ZodSet:un,ZodString:Rn,ZodSymbol:_a,ZodTransformer:Vt,ZodTuple:or,ZodType:Te,ZodUndefined:vs,ZodUnion:ys,ZodUnknown:ln,ZodVoid:ya,addIssueToContext:te,any:Wy,array:Xy,bigint:Vy,boolean:Up,coerce:{string:(t=>Rn.create({...t,coerce:!0})),number:(t=>ms.create({...t,coerce:!0})),boolean:(t=>gs.create({...t,coerce:!0})),bigint:(t=>jr.create({...t,coerce:!0})),date:(t=>an.create({...t,coerce:!0}))},custom:qp,date:Hy,datetimeRegex:Ap,defaultErrorMap:xn,discriminatedUnion:r1,effect:Fp,enum:d1,function:l1,getErrorMap:ga,getParsedType:kr,instanceof:Zy,intersection:n1,isAborted:Wi,isAsync:hs,isDirty:Ki,isValid:on,late:Uy,lazy:c1,literal:u1,makeIssue:va,map:a1,nan:Fy,nativeEnum:p1,never:Yy,null:Gy,nullable:m1,number:Dp,object:Zp,get objectUtil(){return Gi},oboolean:()=>Up().optional(),onumber:()=>Dp().optional(),optional:h1,ostring:()=>zp().optional(),pipeline:v1,preprocess:g1,promise:f1,quotelessJson:gy,record:o1,set:i1,setErrorMap:vy,strictObject:e1,string:zp,symbol:By,transformer:Fp,tuple:s1,undefined:Jy,union:t1,unknown:Ky,get util(){return Re},void:Qy},Symbol.toStringTag,{value:"Module"})),Vp=Object.freeze({status:"aborted"});function J(t,e,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(t),e(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function a(i){var l;const c=r?.Parent?new o:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}class Is extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Hp={};function zr(t){return Hp}function Bp(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function y1(t,e){return typeof e=="bigint"?e.toString():e}function el(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function tl(t){return t==null}function rl(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function w1(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}function Ae(t,e,r){Object.defineProperty(t,e,{get(){{const n=r();return t[e]=n,n}},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Rs(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ps(t){return JSON.stringify(t)}const Jp=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ka(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const b1=el(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Sa(t){if(ka(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(ka(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const k1=new Set(["string","number","symbol"]);function Os(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dr(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ie(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function S1(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const T1={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 C1(t,e){const r={},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return Dr(t,{...t._zod.def,shape:r,checks:[]})}function $1(t,e){const r={...t._zod.def.shape},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return Dr(t,{...t._zod.def,shape:r,checks:[]})}function E1(t,e){if(!Sa(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const n={...t._zod.def.shape,...e};return Rs(this,"shape",n),n},checks:[]};return Dr(t,r)}function x1(t,e){return Dr(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Rs(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function I1(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(const o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return Dr(e,{...e._zod.def,shape:s,checks:[]})}function R1(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(const o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return Dr(e,{...e._zod.def,shape:s,checks:[]})}function As(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function dn(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ta(t){return typeof t=="string"?t:t?.message}function Ur(t,e,r){const n={...t,path:t.path??[]};if(!t.message){const s=Ta(t.inst?._zod.def?.error?.(t))??Ta(e?.error?.(t))??Ta(r.customError?.(t))??Ta(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function nl(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ms(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const Gp=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,y1,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Wp=J("$ZodError",Gp),Ca=J("$ZodError",Gp,{Parent:Error});function P1(t,e=r=>r.message){const r={},n=[];for(const s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function O1(t,e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return s(t),n}const Kp=t=>(e,r,n,s)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Is;if(a.issues.length){const i=new(s?.Err??t)(a.issues.map(l=>Ur(l,o,zr())));throw Jp(i,s?.callee),i}return a.value},A1=Kp(Ca),Yp=t=>async(e,r,n,s)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(s?.Err??t)(a.issues.map(l=>Ur(l,o,zr())));throw Jp(i,s?.callee),i}return a.value},M1=Yp(Ca),Qp=t=>(e,r,n)=>{const s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Is;return o.issues.length?{success:!1,error:new(t??Wp)(o.issues.map(a=>Ur(a,s,zr())))}:{success:!0,data:o.value}},sl=Qp(Ca),Xp=t=>async(e,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>Ur(a,s,zr())))}:{success:!0,data:o.value}},ol=Xp(Ca),N1=/^[cC][^\s-]{8,}$/,L1=/^[0-9a-z]+$/,j1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,q1=/^[0-9a-vA-V]{20}$/,z1=/^[A-Za-z0-9]{27}$/,D1=/^[a-zA-Z0-9_-]{21}$/,U1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Z1=/^([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})$/,ef=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,F1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,V1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function H1(){return new RegExp(V1,"u")}const B1=/^(?:(?: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])$/,J1=/^(([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})$/,G1=/^((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])$/,W1=/^(([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])$/,K1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,tf=/^[A-Za-z0-9_-]*$/,Y1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Q1=/^\+(?:[0-9]){6,14}[0-9]$/,rf="(?:(?:\\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])))",X1=new RegExp(`^${rf}$`);function nf(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ew(t){return new RegExp(`^${nf(t)}$`)}function tw(t){const e=nf({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${e}(?:${r.join("|")})`;return new RegExp(`^${rf}T(?:${n})$`)}const rw=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},nw=/^\d+$/,sw=/^-?\d+(?:\.\d+)?/i,ow=/true|false/i,aw=/null/i,iw=/^[^A-Z]*$/,lw=/^[^a-z]*$/,bt=J("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),sf={number:"number",bigint:"bigint",object:"date"},of=J("$ZodCheckLessThan",(t,e)=>{bt.init(t,e);const r=sf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),af=J("$ZodCheckGreaterThan",(t,e)=>{bt.init(t,e);const r=sf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),cw=J("$ZodCheckMultipleOf",(t,e)=>{bt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):w1(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),uw=J("$ZodCheckNumberFormat",(t,e)=>{bt.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),n=r?"int":"number",[s,o]=T1[e.format];t._zod.onattach.push(a=>{const i=a._zod.bag;i.format=e.format,i.minimum=s,i.maximum=o,r&&(i.pattern=nw)}),t._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}i<s&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inst:t})}}),dw=J("$ZodCheckMaxLength",(t,e)=>{var r;bt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!tl(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{const s=n.value;if(s.length<=e.maximum)return;const a=nl(s);n.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),pw=J("$ZodCheckMinLength",(t,e)=>{var r;bt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!tl(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{const s=n.value;if(s.length>=e.minimum)return;const a=nl(s);n.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),fw=J("$ZodCheckLengthEquals",(t,e)=>{var r;bt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!tl(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{const s=n.value,o=s.length;if(o===e.length)return;const a=nl(s),i=o>e.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),$a=J("$ZodCheckStringFormat",(t,e)=>{var r,n;bt.init(t,e),t._zod.onattach.push(s=>{const o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),hw=J("$ZodCheckRegex",(t,e)=>{$a.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),mw=J("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=iw),$a.init(t,e)}),gw=J("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=lw),$a.init(t,e)}),vw=J("$ZodCheckIncludes",(t,e)=>{bt.init(t,e);const r=Os(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),_w=J("$ZodCheckStartsWith",(t,e)=>{bt.init(t,e);const r=new RegExp(`^${Os(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),yw=J("$ZodCheckEndsWith",(t,e)=>{bt.init(t,e);const r=new RegExp(`.*${Os(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),ww=J("$ZodCheckOverwrite",(t,e)=>{bt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class bw{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(`
8
+ deps: ${u}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){const[c,u]=o(l);a(l,c),i(l,u)}};function o({schema:l}){const c={},u={};for(const p in l){if(p==="__proto__")continue;const h=Array.isArray(l[p])?c:u;h[p]=l[p]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:p,it:h}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const f in c){const w=c[f];if(w.length===0)continue;const m=(0,n.propertyInData)(u,p,f,h.opts.ownProperties);l.setParams({property:f,depsCount:w.length,deps:w.join(", ")}),h.allErrors?u.if(m,()=>{for(const y of w)(0,n.checkReportMissingProp)(l,y)}):(u.if((0,e._)`${m} && (${(0,n.checkMissingProp)(l,w,d)})`),(0,n.reportMissingProp)(l,d),u.else())}}t.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:p,keyword:h,it:d}=l,f=u.name("valid");for(const w in c)(0,r.alwaysValidSchema)(d,c[w])||(u.if((0,n.propertyInData)(u,p,w,d.opts.ownProperties),()=>{const m=l.subschema({keyword:h,schemaProp:w},f);l.mergeValidEvaluated(m,f)},()=>u.var(f,!0)),l.ok(f))}t.validateSchemaDeps=i,t.default=s})(Ji)),Ji}var na={},ip;function Q_(){if(ip)return na;ip=1,Object.defineProperty(na,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:s})=>(0,t._)`{propertyName: ${s.propertyName}}`},code(s){const{gen:o,schema:a,data:i,it:l}=s;if((0,e.alwaysValidSchema)(l,a))return;const c=o.name("valid");o.forIn("key",i,u=>{s.setParams({propertyName:u}),s.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),o.if((0,t.not)(c),()=>{s.error(!0),l.allErrors||o.break()})}),s.ok(c)}};return na.default=n,na}var sa={},lp;function cp(){if(lp)return sa;lp=1,Object.defineProperty(sa,"__esModule",{value:!0});const t=Ft(),e=$e(),r=Nr(),n=Oe(),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,e._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:p,it:h}=a;if(!p)throw new Error("ajv implementation error");const{allErrors:d,opts:f}=h;if(h.props=!0,f.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(h,l))return;const w=(0,t.allSchemaProperties)(c.properties),m=(0,t.allSchemaProperties)(c.patternProperties);y(),a.ok((0,e._)`${p} === ${r.default.errors}`);function y(){i.forIn("key",u,S=>{!w.length&&!m.length?b(S):i.if(_(S),()=>b(S))})}function _(S){let T;if(w.length>8){const x=(0,n.schemaRefOrVal)(h,c.properties,"properties");T=(0,t.isOwnProperty)(i,x,S)}else w.length?T=(0,e.or)(...w.map(x=>(0,e._)`${S} === ${x}`)):T=e.nil;return m.length&&(T=(0,e.or)(T,...m.map(x=>(0,e._)`${(0,t.usePattern)(a,x)}.test(${S})`))),(0,e.not)(T)}function g(S){i.code((0,e._)`delete ${u}[${S}]`)}function b(S){if(f.removeAdditional==="all"||f.removeAdditional&&l===!1){g(S);return}if(l===!1){a.setParams({additionalProperty:S}),a.error(),d||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(h,l)){const T=i.name("valid");f.removeAdditional==="failing"?(k(S,T,!1),i.if((0,e.not)(T),()=>{a.reset(),g(S)})):(k(S,T),d||i.if((0,e.not)(T),()=>i.break()))}}function k(S,T,x){const I={keyword:"additionalProperties",dataProp:S,dataPropType:n.Type.Str};x===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,T)}}};return sa.default=o,sa}var oa={},up;function X_(){if(up)return oa;up=1,Object.defineProperty(oa,"__esModule",{value:!0});const t=Oo(),e=Ft(),r=Oe(),n=cp(),s={keyword:"properties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=o;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new t.KeywordCxt(u,n.default,"additionalProperties"));const p=(0,e.allSchemaProperties)(i);for(const m of p)u.definedProperties.add(m);u.opts.unevaluated&&p.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(p),u.props));const h=p.filter(m=>!(0,r.alwaysValidSchema)(u,i[m]));if(h.length===0)return;const d=a.name("valid");for(const m of h)f(m)?w(m):(a.if((0,e.propertyInData)(a,c,m,u.opts.ownProperties)),w(m),u.allErrors||a.else().var(d,!0),a.endIf()),o.it.definedProperties.add(m),o.ok(d);function f(m){return u.opts.useDefaults&&!u.compositeRule&&i[m].default!==void 0}function w(m){o.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}}};return oa.default=s,oa}var aa={},dp;function ey(){if(dp)return aa;dp=1,Object.defineProperty(aa,"__esModule",{value:!0});const t=Ft(),e=$e(),r=Oe(),n=Oe(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(o){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=o,{opts:p}=u,h=(0,t.allSchemaProperties)(i),d=h.filter(b=>(0,r.alwaysValidSchema)(u,i[b]));if(h.length===0||d.length===h.length&&(!u.opts.unevaluated||u.props===!0))return;const f=p.strictSchema&&!p.allowMatchingProperties&&c.properties,w=a.name("valid");u.props!==!0&&!(u.props instanceof e.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:m}=u;y();function y(){for(const b of h)f&&_(b),u.allErrors?g(b):(a.var(w,!0),g(b),a.if(w))}function _(b){for(const k in f)new RegExp(b).test(k)&&(0,r.checkStrictMode)(u,`property ${k} matches pattern ${b} (use allowMatchingProperties)`)}function g(b){a.forIn("key",l,k=>{a.if((0,e._)`${(0,t.usePattern)(o,b)}.test(${k})`,()=>{const S=d.includes(b);S||o.subschema({keyword:"patternProperties",schemaProp:b,dataProp:k,dataPropType:n.Type.Str},w),u.opts.unevaluated&&m!==!0?a.assign((0,e._)`${m}[${k}]`,!0):!S&&!u.allErrors&&a.if((0,e.not)(w),()=>a.break())})})}}};return aa.default=s,aa}var ia={},pp;function ty(){if(pp)return ia;pp=1,Object.defineProperty(ia,"__esModule",{value:!0});const t=Oe(),e={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:s,it:o}=r;if((0,t.alwaysValidSchema)(o,s)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return ia.default=e,ia}var la={},fp;function ry(){if(fp)return la;fp=1,Object.defineProperty(la,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ft().validateUnion,error:{message:"must match a schema in anyOf"}};return la.default=e,la}var ca={},hp;function ny(){if(hp)return ca;hp=1,Object.defineProperty(ca,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:s})=>(0,t._)`{passingSchemas: ${s.passing}}`},code(s){const{gen:o,schema:a,parentSchema:i,it:l}=s;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=o.let("valid",!1),p=o.let("passing",null),h=o.name("_valid");s.setParams({passing:p}),o.block(d),s.result(u,()=>s.reset(),()=>s.error(!0));function d(){c.forEach((f,w)=>{let m;(0,e.alwaysValidSchema)(l,f)?o.var(h,!0):m=s.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},h),w>0&&o.if((0,t._)`${h} && ${u}`).assign(u,!1).assign(p,(0,t._)`[${p}, ${w}]`).else(),o.if(h,()=>{o.assign(u,!0),o.assign(p,w),m&&s.mergeEvaluated(m,t.Name)})})}}};return ca.default=n,ca}var ua={},mp;function sy(){if(mp)return ua;mp=1,Object.defineProperty(ua,"__esModule",{value:!0});const t=Oe(),e={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:s,it:o}=r;if(!Array.isArray(s))throw new Error("ajv implementation error");const a=n.name("valid");s.forEach((i,l)=>{if((0,t.alwaysValidSchema)(o,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return ua.default=e,ua}var da={},gp;function oy(){if(gp)return da;gp=1,Object.defineProperty(da,"__esModule",{value:!0});const t=$e(),e=Oe(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:o})=>(0,t.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,t._)`{failingKeyword: ${o.ifClause}}`},code(o){const{gen:a,parentSchema:i,it:l}=o;i.then===void 0&&i.else===void 0&&(0,e.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=s(l,"then"),u=s(l,"else");if(!c&&!u)return;const p=a.let("valid",!0),h=a.name("_valid");if(d(),o.reset(),c&&u){const w=a.let("ifClause");o.setParams({ifClause:w}),a.if(h,f("then",w),f("else",w))}else c?a.if(h,f("then")):a.if((0,t.not)(h),f("else"));o.pass(p,()=>o.error(!0));function d(){const w=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},h);o.mergeEvaluated(w)}function f(w,m){return()=>{const y=o.subschema({keyword:w},h);a.assign(p,h),o.mergeValidEvaluated(y,p),m?a.assign(m,(0,t._)`${w}`):o.setParams({ifClause:w})}}}};function s(o,a){const i=o.schema[a];return i!==void 0&&!(0,e.alwaysValidSchema)(o,i)}return da.default=n,da}var pa={},vp;function ay(){if(vp)return pa;vp=1,Object.defineProperty(pa,"__esModule",{value:!0});const t=Oe(),e={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:s}){n.if===void 0&&(0,t.checkStrictMode)(s,`"${r}" without "if" is ignored`)}};return pa.default=e,pa}var _p;function iy(){if(_p)return Xo;_p=1,Object.defineProperty(Xo,"__esModule",{value:!0});const t=ep(),e=G_(),r=rp(),n=W_(),s=K_(),o=Y_(),a=Q_(),i=cp(),l=X_(),c=ey(),u=ty(),p=ry(),h=ny(),d=sy(),f=oy(),w=ay();function m(y=!1){const _=[u.default,p.default,h.default,d.default,f.default,w.default,a.default,i.default,o.default,l.default,c.default];return y?_.push(e.default,n.default):_.push(t.default,r.default),_.push(s.default),_}return Xo.default=m,Xo}var fa={},ha={},yp;function ly(){if(yp)return ha;yp=1,Object.defineProperty(ha,"__esModule",{value:!0});const t=$e(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,s){const{gen:o,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:p,errSchemaPath:h,schemaEnv:d,self:f}=u;if(!p.validateFormats)return;i?w():m();function w(){const y=o.scopeValue("formats",{ref:f.formats,code:p.code.formats}),_=o.const("fDef",(0,t._)`${y}[${c}]`),g=o.let("fType"),b=o.let("format");o.if((0,t._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>o.assign(g,(0,t._)`${_}.type || "string"`).assign(b,(0,t._)`${_}.validate`),()=>o.assign(g,(0,t._)`"string"`).assign(b,_)),n.fail$data((0,t.or)(k(),S()));function k(){return p.strictSchema===!1?t.nil:(0,t._)`${c} && !${b}`}function S(){const T=d.$async?(0,t._)`(${_}.async ? await ${b}(${a}) : ${b}(${a}))`:(0,t._)`${b}(${a})`,x=(0,t._)`(typeof ${b} == "function" ? ${T} : ${b}.test(${a}))`;return(0,t._)`${b} && ${b} !== true && ${g} === ${s} && !${x}`}}function m(){const y=f.formats[l];if(!y){k();return}if(y===!0)return;const[_,g,b]=S(y);_===s&&n.pass(T());function k(){if(p.strictSchema===!1){f.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${l}" ignored in schema at path "${h}"`}}function S(x){const I=x instanceof RegExp?(0,t.regexpCode)(x):p.code.formats?(0,t._)`${p.code.formats}${(0,t.getProperty)(l)}`:void 0,A=o.scopeValue("formats",{key:l,ref:x,code:I});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,t._)`${A}.validate`]:["string",x,A]}function T(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!d.$async)throw new Error("async format in sync schema");return(0,t._)`await ${b}(${a})`}return typeof g=="function"?(0,t._)`${b}(${a})`:(0,t._)`${b}.test(${a})`}}}};return ha.default=r,ha}var wp;function cy(){if(wp)return fa;wp=1,Object.defineProperty(fa,"__esModule",{value:!0});const e=[ly().default];return fa.default=e,fa}var sn={},bp;function uy(){return bp||(bp=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.contentVocabulary=sn.metadataVocabulary=void 0,sn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],sn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),sn}var kp;function dy(){if(kp)return jo;kp=1,Object.defineProperty(jo,"__esModule",{value:!0});const t=N_(),e=J_(),r=iy(),n=cy(),s=uy(),o=[t.default,e.default,(0,r.default)(),n.default,s.metadataVocabulary,s.contentVocabulary];return jo.default=o,jo}var ma={},fs={},Sp;function py(){if(Sp)return fs;Sp=1,Object.defineProperty(fs,"__esModule",{value:!0}),fs.DiscrError=void 0;var t;return(function(e){e.Tag="tag",e.Mapping="mapping"})(t||(fs.DiscrError=t={})),fs}var Tp;function fy(){if(Tp)return ma;Tp=1,Object.defineProperty(ma,"__esModule",{value:!0});const t=$e(),e=py(),r=Fi(),n=No(),s=Oe(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===e.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,t._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:p,it:h}=i,{oneOf:d}=p;if(!h.opts.discriminator)throw new Error("discriminator: requires discriminator option");const f=u.propertyName;if(typeof f!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const w=l.let("valid",!1),m=l.const("tag",(0,t._)`${c}${(0,t.getProperty)(f)}`);l.if((0,t._)`typeof ${m} == "string"`,()=>y(),()=>i.error(!1,{discrError:e.DiscrError.Tag,tag:m,tagName:f})),i.ok(w);function y(){const b=g();l.if(!1);for(const k in b)l.elseIf((0,t._)`${m} === ${k}`),l.assign(w,_(b[k]));l.else(),i.error(!1,{discrError:e.DiscrError.Mapping,tag:m,tagName:f}),l.endIf()}function _(b){const k=l.name("valid"),S=i.subschema({keyword:"oneOf",schemaProp:b},k);return i.mergeEvaluated(S,t.Name),k}function g(){var b;const k={},S=x(p);let T=!0;for(let P=0;P<d.length;P++){let D=d[P];if(D?.$ref&&!(0,s.schemaHasRulesButRef)(D,h.self.RULES)){const V=D.$ref;if(D=r.resolveRef.call(h.self,h.schemaEnv.root,h.baseId,V),D instanceof r.SchemaEnv&&(D=D.schema),D===void 0)throw new n.default(h.opts.uriResolver,h.baseId,V)}const U=(b=D?.properties)===null||b===void 0?void 0:b[f];if(typeof U!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);T=T&&(S||x(D)),I(U,P)}if(!T)throw new Error(`discriminator: "${f}" must be required`);return k;function x({required:P}){return Array.isArray(P)&&P.includes(f)}function I(P,D){if(P.const)A(P.const,D);else if(P.enum)for(const U of P.enum)A(U,D);else throw new Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function A(P,D){if(typeof P!="string"||P in k)throw new Error(`discriminator: "${f}" values must be unique strings`);k[P]=D}}}};return ma.default=a,ma}const hy={$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 Cp;function $p(){return Cp||(Cp=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const r=O_(),n=dy(),s=fy(),o=hy,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(o,a):o;this.addMetaSchema(f,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=Oo();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=$e();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var p=Zi();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var h=No();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return h.default}})})($o,$o.exports)),$o.exports}var Ep=$p();const my=tn(Ep);var Re;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const o={};for(const a of s)o[a]=a;return o},t.getValidEnumValues=s=>{const o=t.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),a={};for(const i of o)a[i]=s[i];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&o.push(a);return o},t.find=(s,o)=>{for(const a of s)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Re||(Re={}));var Gi;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Gi||(Gi={}));const oe=Re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kr=t=>{switch(typeof t){case"undefined":return oe.undefined;case"string":return oe.string;case"number":return Number.isNaN(t)?oe.nan:oe.number;case"boolean":return oe.boolean;case"function":return oe.function;case"bigint":return oe.bigint;case"symbol":return oe.symbol;case"object":return Array.isArray(t)?oe.array:t===null?oe.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?oe.promise:typeof Map<"u"&&t instanceof Map?oe.map:typeof Set<"u"&&t instanceof Set?oe.set:typeof Date<"u"&&t instanceof Date?oe.date:oe.object;default:return oe.unknown}},Y=Re.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"]),gy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class Rt extends Error{get errors(){return this.issues}constructor(e){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=e}format(e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof Rt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Re.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Rt.create=t=>new Rt(t);const xn=(t,e)=>{let r;switch(t.code){case Y.invalid_type:t.received===oe.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Re.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:r=`Unrecognized key(s) in object: ${Re.joinValues(t.keys,", ")}`;break;case Y.invalid_union:r="Invalid input";break;case Y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Re.joinValues(t.options)}`;break;case Y.invalid_enum_value:r=`Invalid enum value. Expected ${Re.joinValues(t.options)}, received '${t.received}'`;break;case Y.invalid_arguments:r="Invalid function arguments";break;case Y.invalid_return_type:r="Invalid function return type";break;case Y.invalid_date:r="Invalid date";break;case Y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Re.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Y.custom:r="Invalid input";break;case Y.invalid_intersection_types:r="Intersection results could not be merged";break;case Y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Y.not_finite:r="Number must be finite";break;default:r=e.defaultError,Re.assertNever(t)}return{message:r}};let xp=xn;function vy(t){xp=t}function ga(){return xp}const va=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],a={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:e,defaultError:i}).message;return{...s,path:o,message:i}},_y=[];function te(t,e){const r=ga(),n=va({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===xn?void 0:xn].filter(s=>!!s)});t.common.issues.push(n)}class ct{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return me;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const o=await s.key,a=await s.value;n.push({key:o,value:a})}return ct.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:o,value:a}=s;if(o.status==="aborted"||a.status==="aborted")return me;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}}const me=Object.freeze({status:"aborted"}),In=t=>({status:"dirty",value:t}),ft=t=>({status:"valid",value:t}),Wi=t=>t.status==="aborted",Ki=t=>t.status==="dirty",on=t=>t.status==="valid",hs=t=>typeof Promise<"u"&&t instanceof Promise;var le;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(le||(le={}));class sr{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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 Ip=(t,e)=>{if(on(e))return{success:!0,data:e.value};if(!t.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 Rt(t.common.issues);return this._error=r,this._error}}};function ke(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,i)=>{const{message:l}=t;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:s}}let Te=class{get description(){return this._def.description}_getType(e){return kr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ct,ctx:{common:e.parent.common,data:e.data,parsedType:kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(hs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ip(n,s)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kr(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return on(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:e,path:[],parent:r}).then(n=>on(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(hs(s)?s:Promise.resolve(s));return Ip(n,o)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{const a=e(s),i=()=>o.addIssue({code:Y.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Vt({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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 ar.create(this,this._def)}nullable(){return qr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return cn.create(this)}promise(){return Mn.create(this,this._def)}or(e){return ys.create([this,e],this._def)}and(e){return ws.create(this,e,this._def)}transform(e){return new Vt({...ke(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Cs({...ke(this._def),innerType:this,defaultValue:r,typeName:z.ZodDefault})}brand(){return new Xi({typeName:z.ZodBranded,type:this,...ke(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new $s({...ke(this._def),innerType:this,catchValue:r,typeName:z.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Es.create(this,e)}readonly(){return xs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const yy=/^c[^\s-]{8,}$/i,wy=/^[0-9a-z]+$/,by=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ky=/^[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,Sy=/^[a-z0-9_-]{21}$/i,Ty=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cy=/^[-+]?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)?)??$/,$y=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ey="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Yi;const xy=/^(?:(?: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])$/,Iy=/^(?:(?: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])$/,Ry=/^(([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]))$/,Py=/^(([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])$/,Oy=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ay=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rp="((\\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])))",My=new RegExp(`^${Rp}$`);function Pp(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Ny(t){return new RegExp(`^${Pp(t)}$`)}function Op(t){let e=`${Rp}T${Pp(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ly(t,e){return!!((e==="v4"||!e)&&xy.test(t)||(e==="v6"||!e)&&Ry.test(t))}function jy(t,e){if(!Ty.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function qy(t,e){return!!((e==="v4"||!e)&&Iy.test(t)||(e==="v6"||!e)&&Py.test(t))}let Rn=class Co extends Te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==oe.string){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_type,expected:oe.string,received:o.parsedType}),me}const n=new ct;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){const a=e.data.length>o.value,i=e.data.length<o.value;(a||i)&&(s=this._getOrReturnCtx(e,s),a?te(s,{code:Y.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&te(s,{code:Y.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")$y.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"email",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Yi||(Yi=new RegExp(Ey,"u")),Yi.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"emoji",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ky.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"uuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Sy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"nanoid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")yy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cuid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")wy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cuid2",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")by.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"ulid",code:Y.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),te(s,{validation:"url",code:Y.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"regex",code:Y.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Op(o).test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?My.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?Ny(o).test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:Y.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?Cy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"duration",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Ly(e.data,o.version)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"ip",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?jy(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"jwt",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?qy(e.data,o.version)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cidr",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?Oy.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"base64",code:Y.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?Ay.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"base64url",code:Y.invalid_string,message:o.message}),n.dirty()):Re.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:Y.invalid_string,...le.errToObj(n)})}_addCheck(e){return new Co({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...le.errToObj(e)})}url(e){return this._addCheck({kind:"url",...le.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...le.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...le.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...le.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...le.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...le.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...le.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...le.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...le.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...le.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...le.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...le.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...le.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...le.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...le.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...le.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...le.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...le.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...le.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...le.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...le.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...le.errToObj(r)})}nonempty(e){return this.min(1,le.errToObj(e))}trim(){return new Co({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Co({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Co({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rn.create=t=>new Rn({checks:[],typeName:z.ZodString,coerce:t?.coerce??!1,...ke(t)});function zy(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}let ms=class rd extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==oe.number){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_type,expected:oe.number,received:o.parsedType}),me}let n;const s=new ct;for(const o of this._def.checks)o.kind==="int"?Re.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:Y.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?zy(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:Y.not_finite,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,le.toString(r))}gt(e,r){return this.setLimit("min",e,!1,le.toString(r))}lte(e,r){return this.setLimit("max",e,!0,le.toString(r))}lt(e,r){return this.setLimit("max",e,!1,le.toString(r))}setLimit(e,r,n,s){return new rd({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:le.toString(s)}]})}_addCheck(e){return new rd({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:le.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:le.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:le.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:le.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:le.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:le.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:le.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:le.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:le.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Re.isInteger(e.value))}get isFinite(){let e=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"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};ms.create=t=>new ms({checks:[],typeName:z.ZodNumber,coerce:t?.coerce||!1,...ke(t)});class jr extends Te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==oe.bigint)return this._getInvalidInput(e);let n;const s=new ct;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),te(n,{code:Y.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Re.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return te(r,{code:Y.invalid_type,expected:oe.bigint,received:r.parsedType}),me}gte(e,r){return this.setLimit("min",e,!0,le.toString(r))}gt(e,r){return this.setLimit("min",e,!1,le.toString(r))}lte(e,r){return this.setLimit("max",e,!0,le.toString(r))}lt(e,r){return this.setLimit("max",e,!1,le.toString(r))}setLimit(e,r,n,s){return new jr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:le.toString(s)}]})}_addCheck(e){return new jr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:le.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:le.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:le.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:le.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:le.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}jr.create=t=>new jr({checks:[],typeName:z.ZodBigInt,coerce:t?.coerce??!1,...ke(t)});let gs=class extends Te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==oe.boolean){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.boolean,received:n.parsedType}),me}return ft(e.data)}};gs.create=t=>new gs({typeName:z.ZodBoolean,coerce:t?.coerce||!1,...ke(t)});class an extends Te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==oe.date){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_type,expected:oe.date,received:o.parsedType}),me}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return te(o,{code:Y.invalid_date}),me}const n=new ct;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:Y.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Re.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new an({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:le.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:le.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}an.create=t=>new an({checks:[],coerce:t?.coerce||!1,typeName:z.ZodDate,...ke(t)});class _a extends Te{_parse(e){if(this._getType(e)!==oe.symbol){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.symbol,received:n.parsedType}),me}return ft(e.data)}}_a.create=t=>new _a({typeName:z.ZodSymbol,...ke(t)});class vs extends Te{_parse(e){if(this._getType(e)!==oe.undefined){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.undefined,received:n.parsedType}),me}return ft(e.data)}}vs.create=t=>new vs({typeName:z.ZodUndefined,...ke(t)});let _s=class extends Te{_parse(e){if(this._getType(e)!==oe.null){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.null,received:n.parsedType}),me}return ft(e.data)}};_s.create=t=>new _s({typeName:z.ZodNull,...ke(t)});let Pn=class extends Te{constructor(){super(...arguments),this._any=!0}_parse(e){return ft(e.data)}};Pn.create=t=>new Pn({typeName:z.ZodAny,...ke(t)});let ln=class extends Te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ft(e.data)}};ln.create=t=>new ln({typeName:z.ZodUnknown,...ke(t)});let Sr=class extends Te{_parse(e){const r=this._getOrReturnCtx(e);return te(r,{code:Y.invalid_type,expected:oe.never,received:r.parsedType}),me}};Sr.create=t=>new Sr({typeName:z.ZodNever,...ke(t)});class ya extends Te{_parse(e){if(this._getType(e)!==oe.undefined){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.void,received:n.parsedType}),me}return ft(e.data)}}ya.create=t=>new ya({typeName:z.ZodVoid,...ke(t)});let cn=class Mi extends Te{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==oe.array)return te(r,{code:Y.invalid_type,expected:oe.array,received:r.parsedType}),me;if(s.exactLength!==null){const a=r.data.length>s.exactLength.value,i=r.data.length<s.exactLength.value;(a||i)&&(te(r,{code:a?Y.too_big:Y.too_small,minimum:i?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(te(r,{code:Y.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(te(r,{code:Y.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>s.type._parseAsync(new sr(r,a,r.path,i)))).then(a=>ct.mergeArray(n,a));const o=[...r.data].map((a,i)=>s.type._parseSync(new sr(r,a,r.path,i)));return ct.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new Mi({...this._def,minLength:{value:e,message:le.toString(r)}})}max(e,r){return new Mi({...this._def,maxLength:{value:e,message:le.toString(r)}})}length(e,r){return new Mi({...this._def,exactLength:{value:e,message:le.toString(r)}})}nonempty(e){return this.min(1,e)}};cn.create=(t,e)=>new cn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...ke(e)});function On(t){if(t instanceof Lt){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=ar.create(On(n))}return new Lt({...t._def,shape:()=>e})}else return t instanceof cn?new cn({...t._def,type:On(t.element)}):t instanceof ar?ar.create(On(t.unwrap())):t instanceof qr?qr.create(On(t.unwrap())):t instanceof or?or.create(t.items.map(e=>On(e))):t}let Lt=class nr extends Te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Re.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==oe.object){const c=this._getOrReturnCtx(e);return te(c,{code:Y.invalid_type,expected:oe.object,received:c.parsedType}),me}const{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Sr&&this._def.unknownKeys==="strip"))for(const c in s.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=o[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new sr(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Sr){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")i.length>0&&(te(s,{code:Y.unrecognized_keys,keys:i}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of i){const p=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new sr(s,p,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const p=await u.key,h=await u.value;c.push({key:p,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>ct.mergeObjectSync(n,c)):ct.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return le.errToObj,new nr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:le.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new nr({...this._def,unknownKeys:"strip"})}passthrough(){return new nr({...this._def,unknownKeys:"passthrough"})}extend(e){return new nr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new nr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:z.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new nr({...this._def,catchall:e})}pick(e){const r={};for(const n of Re.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new nr({...this._def,shape:()=>r})}omit(e){const r={};for(const n of Re.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new nr({...this._def,shape:()=>r})}deepPartial(){return On(this)}partial(e){const r={};for(const n of Re.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new nr({...this._def,shape:()=>r})}required(e){const r={};for(const n of Re.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ar;)o=o._def.innerType;r[n]=o}return new nr({...this._def,shape:()=>r})}keyof(){return Np(Re.objectKeys(this.shape))}};Lt.create=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strip",catchall:Sr.create(),typeName:z.ZodObject,...ke(e)}),Lt.strictCreate=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strict",catchall:Sr.create(),typeName:z.ZodObject,...ke(e)}),Lt.lazycreate=(t,e)=>new Lt({shape:t,unknownKeys:"strip",catchall:Sr.create(),typeName:z.ZodObject,...ke(e)});let ys=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(i=>new Rt(i.ctx.common.issues));return te(r,{code:Y.invalid_union,unionErrors:a}),me}if(r.common.async)return Promise.all(n.map(async o=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(s);{let o;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(l=>new Rt(l));return te(r,{code:Y.invalid_union,unionErrors:i}),me}}get options(){return this._def.options}};ys.create=(t,e)=>new ys({options:t,typeName:z.ZodUnion,...ke(e)});const Tr=t=>t instanceof bs?Tr(t.schema):t instanceof Vt?Tr(t.innerType()):t instanceof ks?[t.value]:t instanceof Ss?t.options:t instanceof Ts?Re.objectValues(t.enum):t instanceof Cs?Tr(t._def.innerType):t instanceof vs?[void 0]:t instanceof _s?[null]:t instanceof ar?[void 0,...Tr(t.unwrap())]:t instanceof qr?[null,...Tr(t.unwrap())]:t instanceof Xi||t instanceof xs?Tr(t.unwrap()):t instanceof $s?Tr(t._def.innerType):[];let Ap=class y_ extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.object)return te(r,{code:Y.invalid_type,expected:oe.object,received:r.parsedType}),me;const n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(te(r,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),me)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const o of r){const a=Tr(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of a){if(s.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,o)}}return new y_({typeName:z.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...ke(n)})}};function Qi(t,e){const r=kr(t),n=kr(e);if(t===e)return{valid:!0,data:t};if(r===oe.object&&n===oe.object){const s=Re.objectKeys(e),o=Re.objectKeys(t).filter(i=>s.indexOf(i)!==-1),a={...t,...e};for(const i of o){const l=Qi(t[i],e[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===oe.array&&n===oe.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<t.length;o++){const a=t[o],i=e[o],l=Qi(a,i);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return r===oe.date&&n===oe.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let ws=class extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(o,a)=>{if(Wi(o)||Wi(a))return me;const i=Qi(o.value,a.value);return i.valid?((Ki(o)||Ki(a))&&r.dirty(),{status:r.value,value:i.data}):(te(n,{code:Y.invalid_intersection_types}),me)};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(([o,a])=>s(o,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ws.create=(t,e,r)=>new ws({left:t,right:e,typeName:z.ZodIntersection,...ke(r)});class or extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.array)return te(n,{code:Y.invalid_type,expected:oe.array,received:n.parsedType}),me;if(n.data.length<this._def.items.length)return te(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),me;!this._def.rest&&n.data.length>this._def.items.length&&(te(n,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const o=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new sr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ct.mergeArray(r,a)):ct.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new or({...this._def,rest:e})}}or.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new or({items:t,typeName:z.ZodTuple,rest:null,...ke(e)})};let Mp=class nd extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.object)return te(n,{code:Y.invalid_type,expected:oe.object,received:n.parsedType}),me;const s=[],o=this._def.keyType,a=this._def.valueType;for(const i in n.data)s.push({key:o._parse(new sr(n,i,n.path,i)),value:a._parse(new sr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?ct.mergeObjectAsync(r,s):ct.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Te?new nd({keyType:e,valueType:r,typeName:z.ZodRecord,...ke(n)}):new nd({keyType:Rn.create(),valueType:e,typeName:z.ZodRecord,...ke(r)})}};class wa extends Te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.map)return te(n,{code:Y.invalid_type,expected:oe.map,received:n.parsedType}),me;const s=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:s._parse(new sr(n,i,n.path,[c,"key"])),value:o._parse(new sr(n,l,n.path,[c,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return me;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}})}else{const i=new Map;for(const l of a){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return me;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}wa.create=(t,e,r)=>new wa({valueType:e,keyType:t,typeName:z.ZodMap,...ke(r)});class un extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.set)return te(n,{code:Y.invalid_type,expected:oe.set,received:n.parsedType}),me;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(te(n,{code:Y.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(te(n,{code:Y.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const o=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return me;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>o._parse(new sr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(e,r){return new un({...this._def,minSize:{value:e,message:le.toString(r)}})}max(e,r){return new un({...this._def,maxSize:{value:e,message:le.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}un.create=(t,e)=>new un({valueType:t,minSize:null,maxSize:null,typeName:z.ZodSet,...ke(e)});class An extends Te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.function)return te(r,{code:Y.invalid_type,expected:oe.function,received:r.parsedType}),me;function n(i,l){return va({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ga(),xn].filter(c=>!!c),issueData:{code:Y.invalid_arguments,argumentsError:l}})}function s(i,l){return va({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ga(),xn].filter(c=>!!c),issueData:{code:Y.invalid_return_type,returnTypeError:l}})}const o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Mn){const i=this;return ft(async function(...l){const c=new Rt([]),u=await i._def.args.parseAsync(l,o).catch(d=>{throw c.addIssue(n(l,d)),c}),p=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(p,o).catch(d=>{throw c.addIssue(s(p,d)),c})})}else{const i=this;return ft(function(...l){const c=i._def.args.safeParse(l,o);if(!c.success)throw new Rt([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),p=i._def.returns.safeParse(u,o);if(!p.success)throw new Rt([s(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new An({...this._def,args:or.create(e).rest(ln.create())})}returns(e){return new An({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new An({args:e||or.create([]).rest(ln.create()),returns:r||ln.create(),typeName:z.ZodFunction,...ke(n)})}}let bs=class extends Te{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};bs.create=(t,e)=>new bs({getter:t,typeName:z.ZodLazy,...ke(e)});let ks=class extends Te{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return te(r,{received:r.data,code:Y.invalid_literal,expected:this._def.value}),me}return{status:"valid",value:e.data}}get value(){return this._def.value}};ks.create=(t,e)=>new ks({value:t,typeName:z.ZodLiteral,...ke(e)});function Np(t,e){return new Ss({values:t,typeName:z.ZodEnum,...ke(e)})}let Ss=class sd extends Te{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{expected:Re.joinValues(n),received:r.parsedType,code:Y.invalid_type}),me}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{received:r.data,code:Y.invalid_enum_value,options:n}),me}return ft(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return sd.create(e,{...this._def,...r})}exclude(e,r=this._def){return sd.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ss.create=Np;class Ts extends Te{_parse(e){const r=Re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==oe.string&&n.parsedType!==oe.number){const s=Re.objectValues(r);return te(n,{expected:Re.joinValues(s),received:n.parsedType,code:Y.invalid_type}),me}if(this._cache||(this._cache=new Set(Re.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=Re.objectValues(r);return te(n,{received:n.data,code:Y.invalid_enum_value,options:s}),me}return ft(e.data)}get enum(){return this._def.values}}Ts.create=(t,e)=>new Ts({values:t,typeName:z.ZodNativeEnum,...ke(e)});class Mn extends Te{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.promise&&r.common.async===!1)return te(r,{code:Y.invalid_type,expected:oe.promise,received:r.parsedType}),me;const n=r.parsedType===oe.promise?r.data:Promise.resolve(r.data);return ft(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Mn.create=(t,e)=>new Mn({type:t,typeName:z.ZodPromise,...ke(e)});class Vt extends Te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:a=>{te(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const a=s.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return me;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?me:l.status==="dirty"||r.value==="dirty"?In(l.value):l});{if(r.value==="aborted")return me;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?me:i.status==="dirty"||r.value==="dirty"?In(i.value):i}}if(s.type==="refinement"){const a=i=>{const l=s.refinement(i,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?me:(i.status==="dirty"&&r.dirty(),a(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?me:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!on(a))return me;const i=s.transform(a.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>on(a)?Promise.resolve(s.transform(a.value,o)).then(i=>({status:r.value,value:i})):me);Re.assertNever(s)}}Vt.create=(t,e,r)=>new Vt({schema:t,typeName:z.ZodEffects,effect:e,...ke(r)}),Vt.createWithPreprocess=(t,e,r)=>new Vt({schema:e,effect:{type:"preprocess",transform:t},typeName:z.ZodEffects,...ke(r)});let ar=class extends Te{_parse(e){return this._getType(e)===oe.undefined?ft(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ar.create=(t,e)=>new ar({innerType:t,typeName:z.ZodOptional,...ke(e)});let qr=class extends Te{_parse(e){return this._getType(e)===oe.null?ft(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qr.create=(t,e)=>new qr({innerType:t,typeName:z.ZodNullable,...ke(e)});let Cs=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===oe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Cs.create=(t,e)=>new Cs({innerType:t,typeName:z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ke(e)});let $s=class extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return hs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Rt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Rt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};$s.create=(t,e)=>new $s({innerType:t,typeName:z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ke(e)});class ba extends Te{_parse(e){if(this._getType(e)!==oe.nan){const n=this._getOrReturnCtx(e);return te(n,{code:Y.invalid_type,expected:oe.nan,received:n.parsedType}),me}return{status:"valid",value:e.data}}}ba.create=t=>new ba({typeName:z.ZodNaN,...ke(t)});const Dy=Symbol("zod_brand");class Xi extends Te{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Es extends Te{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?me:o.status==="dirty"?(r.dirty(),In(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?me:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Es({in:e,out:r,typeName:z.ZodPipeline})}}let xs=class extends Te{_parse(e){const r=this._def.innerType._parse(e),n=s=>(on(s)&&(s.value=Object.freeze(s.value)),s);return hs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};xs.create=(t,e)=>new xs({innerType:t,typeName:z.ZodReadonly,...ke(e)});function Lp(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function jp(t,e={},r){return t?Pn.create().superRefine((n,s)=>{const o=t(n);if(o instanceof Promise)return o.then(a=>{if(!a){const i=Lp(e,n),l=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:l})}});if(!o){const a=Lp(e,n),i=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:i})}}):Pn.create()}const Uy={object:Lt.lazycreate};var z;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(z||(z={}));const Zy=(t,e={message:`Input not instance of ${t.name}`})=>jp(r=>r instanceof t,e),qp=Rn.create,zp=ms.create,Fy=ba.create,Vy=jr.create,Dp=gs.create,Hy=an.create,By=_a.create,Jy=vs.create,Gy=_s.create,Wy=Pn.create,Ky=ln.create,Yy=Sr.create,Qy=ya.create,Xy=cn.create,Up=Lt.create,e1=Lt.strictCreate,t1=ys.create,r1=Ap.create,n1=ws.create,s1=or.create,o1=Mp.create,a1=wa.create,i1=un.create,l1=An.create,c1=bs.create,u1=ks.create,d1=Ss.create,p1=Ts.create,f1=Mn.create,Zp=Vt.create,h1=ar.create,m1=qr.create,g1=Vt.createWithPreprocess,v1=Es.create,_1=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Dy,DIRTY:In,EMPTY_PATH:_y,INVALID:me,NEVER:me,OK:ft,ParseStatus:ct,Schema:Te,ZodAny:Pn,ZodArray:cn,ZodBigInt:jr,ZodBoolean:gs,ZodBranded:Xi,ZodCatch:$s,ZodDate:an,ZodDefault:Cs,ZodDiscriminatedUnion:Ap,ZodEffects:Vt,ZodEnum:Ss,ZodError:Rt,get ZodFirstPartyTypeKind(){return z},ZodFunction:An,ZodIntersection:ws,ZodIssueCode:Y,ZodLazy:bs,ZodLiteral:ks,ZodMap:wa,ZodNaN:ba,ZodNativeEnum:Ts,ZodNever:Sr,ZodNull:_s,ZodNullable:qr,ZodNumber:ms,ZodObject:Lt,ZodOptional:ar,ZodParsedType:oe,ZodPipeline:Es,ZodPromise:Mn,ZodReadonly:xs,ZodRecord:Mp,ZodSchema:Te,ZodSet:un,ZodString:Rn,ZodSymbol:_a,ZodTransformer:Vt,ZodTuple:or,ZodType:Te,ZodUndefined:vs,ZodUnion:ys,ZodUnknown:ln,ZodVoid:ya,addIssueToContext:te,any:Wy,array:Xy,bigint:Vy,boolean:Dp,coerce:{string:(t=>Rn.create({...t,coerce:!0})),number:(t=>ms.create({...t,coerce:!0})),boolean:(t=>gs.create({...t,coerce:!0})),bigint:(t=>jr.create({...t,coerce:!0})),date:(t=>an.create({...t,coerce:!0}))},custom:jp,date:Hy,datetimeRegex:Op,defaultErrorMap:xn,discriminatedUnion:r1,effect:Zp,enum:d1,function:l1,getErrorMap:ga,getParsedType:kr,instanceof:Zy,intersection:n1,isAborted:Wi,isAsync:hs,isDirty:Ki,isValid:on,late:Uy,lazy:c1,literal:u1,makeIssue:va,map:a1,nan:Fy,nativeEnum:p1,never:Yy,null:Gy,nullable:m1,number:zp,object:Up,get objectUtil(){return Gi},oboolean:()=>Dp().optional(),onumber:()=>zp().optional(),optional:h1,ostring:()=>qp().optional(),pipeline:v1,preprocess:g1,promise:f1,quotelessJson:gy,record:o1,set:i1,setErrorMap:vy,strictObject:e1,string:qp,symbol:By,transformer:Zp,tuple:s1,undefined:Jy,union:t1,unknown:Ky,get util(){return Re},void:Qy},Symbol.toStringTag,{value:"Module"})),Fp=Object.freeze({status:"aborted"});function J(t,e,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(t),e(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function a(i){var l;const c=r?.Parent?new o:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}class Is extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Vp={};function zr(t){return Vp}function Hp(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function y1(t,e){return typeof e=="bigint"?e.toString():e}function el(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function tl(t){return t==null}function rl(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function w1(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}function Ae(t,e,r){Object.defineProperty(t,e,{get(){{const n=r();return t[e]=n,n}},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function Rs(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ps(t){return JSON.stringify(t)}const Bp=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ka(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const b1=el(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Sa(t){if(ka(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(ka(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const k1=new Set(["string","number","symbol"]);function Os(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dr(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ie(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function S1(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const T1={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 C1(t,e){const r={},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return Dr(t,{...t._zod.def,shape:r,checks:[]})}function $1(t,e){const r={...t._zod.def.shape},n=t._zod.def;for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return Dr(t,{...t._zod.def,shape:r,checks:[]})}function E1(t,e){if(!Sa(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const n={...t._zod.def.shape,...e};return Rs(this,"shape",n),n},checks:[]};return Dr(t,r)}function x1(t,e){return Dr(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Rs(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function I1(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(const o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return Dr(e,{...e._zod.def,shape:s,checks:[]})}function R1(t,e,r){const n=e._zod.def.shape,s={...n};if(r)for(const o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(const o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return Dr(e,{...e._zod.def,shape:s,checks:[]})}function As(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function dn(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ta(t){return typeof t=="string"?t:t?.message}function Ur(t,e,r){const n={...t,path:t.path??[]};if(!t.message){const s=Ta(t.inst?._zod.def?.error?.(t))??Ta(e?.error?.(t))??Ta(r.customError?.(t))??Ta(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function nl(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ms(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const Jp=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,y1,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gp=J("$ZodError",Jp),Ca=J("$ZodError",Jp,{Parent:Error});function P1(t,e=r=>r.message){const r={},n=[];for(const s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function O1(t,e){const r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return s(t),n}const Wp=t=>(e,r,n,s)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Is;if(a.issues.length){const i=new(s?.Err??t)(a.issues.map(l=>Ur(l,o,zr())));throw Bp(i,s?.callee),i}return a.value},A1=Wp(Ca),Kp=t=>async(e,r,n,s)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(s?.Err??t)(a.issues.map(l=>Ur(l,o,zr())));throw Bp(i,s?.callee),i}return a.value},M1=Kp(Ca),Yp=t=>(e,r,n)=>{const s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Is;return o.issues.length?{success:!1,error:new(t??Gp)(o.issues.map(a=>Ur(a,s,zr())))}:{success:!0,data:o.value}},sl=Yp(Ca),Qp=t=>async(e,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>Ur(a,s,zr())))}:{success:!0,data:o.value}},ol=Qp(Ca),N1=/^[cC][^\s-]{8,}$/,L1=/^[0-9a-z]+$/,j1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,q1=/^[0-9a-vA-V]{20}$/,z1=/^[A-Za-z0-9]{27}$/,D1=/^[a-zA-Z0-9_-]{21}$/,U1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Z1=/^([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})$/,Xp=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,F1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,V1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function H1(){return new RegExp(V1,"u")}const B1=/^(?:(?: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])$/,J1=/^(([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})$/,G1=/^((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])$/,W1=/^(([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])$/,K1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ef=/^[A-Za-z0-9_-]*$/,Y1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Q1=/^\+(?:[0-9]){6,14}[0-9]$/,tf="(?:(?:\\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])))",X1=new RegExp(`^${tf}$`);function rf(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ew(t){return new RegExp(`^${rf(t)}$`)}function tw(t){const e=rf({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${e}(?:${r.join("|")})`;return new RegExp(`^${tf}T(?:${n})$`)}const rw=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},nw=/^\d+$/,sw=/^-?\d+(?:\.\d+)?/i,ow=/true|false/i,aw=/null/i,iw=/^[^A-Z]*$/,lw=/^[^a-z]*$/,bt=J("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),nf={number:"number",bigint:"bigint",object:"date"},sf=J("$ZodCheckLessThan",(t,e)=>{bt.init(t,e);const r=nf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),of=J("$ZodCheckGreaterThan",(t,e)=>{bt.init(t,e);const r=nf[typeof e.value];t._zod.onattach.push(n=>{const s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),cw=J("$ZodCheckMultipleOf",(t,e)=>{bt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):w1(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),uw=J("$ZodCheckNumberFormat",(t,e)=>{bt.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),n=r?"int":"number",[s,o]=T1[e.format];t._zod.onattach.push(a=>{const i=a._zod.bag;i.format=e.format,i.minimum=s,i.maximum=o,r&&(i.pattern=nw)}),t._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}i<s&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inst:t})}}),dw=J("$ZodCheckMaxLength",(t,e)=>{var r;bt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!tl(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{const s=n.value;if(s.length<=e.maximum)return;const a=nl(s);n.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),pw=J("$ZodCheckMinLength",(t,e)=>{var r;bt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!tl(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{const s=n.value;if(s.length>=e.minimum)return;const a=nl(s);n.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),fw=J("$ZodCheckLengthEquals",(t,e)=>{var r;bt.init(t,e),(r=t._zod.def).when??(r.when=n=>{const s=n.value;return!tl(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{const s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{const s=n.value,o=s.length;if(o===e.length)return;const a=nl(s),i=o>e.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),$a=J("$ZodCheckStringFormat",(t,e)=>{var r,n;bt.init(t,e),t._zod.onattach.push(s=>{const o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),hw=J("$ZodCheckRegex",(t,e)=>{$a.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),mw=J("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=iw),$a.init(t,e)}),gw=J("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=lw),$a.init(t,e)}),vw=J("$ZodCheckIncludes",(t,e)=>{bt.init(t,e);const r=Os(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),_w=J("$ZodCheckStartsWith",(t,e)=>{bt.init(t,e);const r=new RegExp(`^${Os(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),yw=J("$ZodCheckEndsWith",(t,e)=>{bt.init(t,e);const r=new RegExp(`.*${Os(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),ww=J("$ZodCheckOverwrite",(t,e)=>{bt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class bw{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(`
9
9
  `).filter(a=>a),s=Math.min(...n.map(a=>a.length-a.trimStart().length)),o=n.map(a=>a.slice(s)).map(a=>" ".repeat(this.indent*2)+a);for(const a of o)this.content.push(a)}compile(){const e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
10
- `))}}const kw={major:4,minor:0,patch:0},Ze=J("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=kw;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const s of n)for(const o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,a,i)=>{let l=As(o),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(l)continue;const p=o.issues.length,h=u._zod.check(o);if(h instanceof Promise&&i?.async===!1)throw new Is;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,o.issues.length!==p&&(l||(l=As(o,p)))});else{if(o.issues.length===p)continue;l||(l=As(o,p))}}return c?c.then(()=>o):o};t._zod.run=(o,a)=>{const i=t._zod.parse(o,a);if(i instanceof Promise){if(a.async===!1)throw new Is;return i.then(l=>s(l,n,a))}return s(i,n,a)}}t["~standard"]={validate:s=>{try{const o=sl(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return ol(t,s).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),al=J("$ZodString",(t,e)=>{Ze.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??rw(t._zod.bag),t._zod.parse=(r,n)=>{if(e.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:t}),r}}),Ge=J("$ZodStringFormat",(t,e)=>{$a.init(t,e),al.init(t,e)}),Sw=J("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Z1),Ge.init(t,e)}),Tw=J("$ZodUUID",(t,e)=>{if(e.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ef(n))}else e.pattern??(e.pattern=ef());Ge.init(t,e)}),Cw=J("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=F1),Ge.init(t,e)}),$w=J("$ZodURL",(t,e)=>{Ge.init(t,e),t._zod.check=r=>{try{const n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y1.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Ew=J("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=H1()),Ge.init(t,e)}),xw=J("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=D1),Ge.init(t,e)}),Iw=J("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=N1),Ge.init(t,e)}),Rw=J("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=L1),Ge.init(t,e)}),Pw=J("$ZodULID",(t,e)=>{e.pattern??(e.pattern=j1),Ge.init(t,e)}),Ow=J("$ZodXID",(t,e)=>{e.pattern??(e.pattern=q1),Ge.init(t,e)}),Aw=J("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=z1),Ge.init(t,e)}),Mw=J("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=tw(e)),Ge.init(t,e)}),Nw=J("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=X1),Ge.init(t,e)}),Lw=J("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ew(e)),Ge.init(t,e)}),jw=J("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=U1),Ge.init(t,e)}),qw=J("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=B1),Ge.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),zw=J("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=J1),Ge.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Dw=J("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=G1),Ge.init(t,e)}),Uw=J("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=W1),Ge.init(t,e),t._zod.check=r=>{const[n,s]=r.value.split("/");try{if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function lf(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Zw=J("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=K1),Ge.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{lf(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Fw(t){if(!tf.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return lf(r)}const Vw=J("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=tf),Ge.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Fw(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Hw=J("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Q1),Ge.init(t,e)});function Bw(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const Jw=J("$ZodJWT",(t,e)=>{Ge.init(t,e),t._zod.check=r=>{Bw(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),cf=J("$ZodNumber",(t,e)=>{Ze.init(t,e),t._zod.pattern=t._zod.bag.pattern??sw,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;const o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),Gw=J("$ZodNumber",(t,e)=>{uw.init(t,e),cf.init(t,e)}),Ww=J("$ZodBoolean",(t,e)=>{Ze.init(t,e),t._zod.pattern=ow,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}const s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),Kw=J("$ZodNull",(t,e)=>{Ze.init(t,e),t._zod.pattern=aw,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{const s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),Yw=J("$ZodAny",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),Qw=J("$ZodUnknown",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),Xw=J("$ZodNever",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function uf(t,e,r){t.issues.length&&e.issues.push(...dn(r,t.issues)),e.value[r]=t.value}const eb=J("$ZodArray",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);const o=[];for(let a=0;a<s.length;a++){const i=s[a],l=e.element._zod.run({value:i,issues:[]},n);l instanceof Promise?o.push(l.then(c=>uf(c,r,a))):uf(l,r,a)}return o.length?Promise.all(o).then(()=>r):r}});function Ea(t,e,r){t.issues.length&&e.issues.push(...dn(r,t.issues)),e.value[r]=t.value}function df(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...dn(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}const pf=J("$ZodObject",(t,e)=>{Ze.init(t,e);const r=el(()=>{const p=Object.keys(e.shape);for(const d of p)if(!(e.shape[d]instanceof Ze))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const h=S1(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(h)}});Ae(t._zod,"propValues",()=>{const p=e.shape,h={};for(const d in p){const f=p[d]._zod;if(f.values){h[d]??(h[d]=new Set);for(const w of f.values)h[d].add(w)}}return h});const n=p=>{const h=new bw(["shape","payload","ctx"]),d=r.value,f=_=>{const g=Ps(_);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};h.write("const input = payload.value;");const w=Object.create(null);let m=0;for(const _ of d.keys)w[_]=`key_${m++}`;h.write("const newResult = {}");for(const _ of d.keys)if(d.optionalKeys.has(_)){const g=w[_];h.write(`const ${g} = ${f(_)};`);const b=Ps(_);h.write(`
10
+ `))}}const kw={major:4,minor:0,patch:0},Ze=J("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=kw;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const s of n)for(const o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,a,i)=>{let l=As(o),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(l)continue;const p=o.issues.length,h=u._zod.check(o);if(h instanceof Promise&&i?.async===!1)throw new Is;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,o.issues.length!==p&&(l||(l=As(o,p)))});else{if(o.issues.length===p)continue;l||(l=As(o,p))}}return c?c.then(()=>o):o};t._zod.run=(o,a)=>{const i=t._zod.parse(o,a);if(i instanceof Promise){if(a.async===!1)throw new Is;return i.then(l=>s(l,n,a))}return s(i,n,a)}}t["~standard"]={validate:s=>{try{const o=sl(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return ol(t,s).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),al=J("$ZodString",(t,e)=>{Ze.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??rw(t._zod.bag),t._zod.parse=(r,n)=>{if(e.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:t}),r}}),Ge=J("$ZodStringFormat",(t,e)=>{$a.init(t,e),al.init(t,e)}),Sw=J("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Z1),Ge.init(t,e)}),Tw=J("$ZodUUID",(t,e)=>{if(e.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Xp(n))}else e.pattern??(e.pattern=Xp());Ge.init(t,e)}),Cw=J("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=F1),Ge.init(t,e)}),$w=J("$ZodURL",(t,e)=>{Ge.init(t,e),t._zod.check=r=>{try{const n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y1.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Ew=J("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=H1()),Ge.init(t,e)}),xw=J("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=D1),Ge.init(t,e)}),Iw=J("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=N1),Ge.init(t,e)}),Rw=J("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=L1),Ge.init(t,e)}),Pw=J("$ZodULID",(t,e)=>{e.pattern??(e.pattern=j1),Ge.init(t,e)}),Ow=J("$ZodXID",(t,e)=>{e.pattern??(e.pattern=q1),Ge.init(t,e)}),Aw=J("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=z1),Ge.init(t,e)}),Mw=J("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=tw(e)),Ge.init(t,e)}),Nw=J("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=X1),Ge.init(t,e)}),Lw=J("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ew(e)),Ge.init(t,e)}),jw=J("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=U1),Ge.init(t,e)}),qw=J("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=B1),Ge.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),zw=J("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=J1),Ge.init(t,e),t._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Dw=J("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=G1),Ge.init(t,e)}),Uw=J("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=W1),Ge.init(t,e),t._zod.check=r=>{const[n,s]=r.value.split("/");try{if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function af(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Zw=J("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=K1),Ge.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{af(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Fw(t){if(!ef.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return af(r)}const Vw=J("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=ef),Ge.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Fw(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Hw=J("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Q1),Ge.init(t,e)});function Bw(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const Jw=J("$ZodJWT",(t,e)=>{Ge.init(t,e),t._zod.check=r=>{Bw(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),lf=J("$ZodNumber",(t,e)=>{Ze.init(t,e),t._zod.pattern=t._zod.bag.pattern??sw,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;const o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),Gw=J("$ZodNumber",(t,e)=>{uw.init(t,e),lf.init(t,e)}),Ww=J("$ZodBoolean",(t,e)=>{Ze.init(t,e),t._zod.pattern=ow,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}const s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}}),Kw=J("$ZodNull",(t,e)=>{Ze.init(t,e),t._zod.pattern=aw,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{const s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}}),Yw=J("$ZodAny",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),Qw=J("$ZodUnknown",(t,e)=>{Ze.init(t,e),t._zod.parse=r=>r}),Xw=J("$ZodNever",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function cf(t,e,r){t.issues.length&&e.issues.push(...dn(r,t.issues)),e.value[r]=t.value}const eb=J("$ZodArray",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);const o=[];for(let a=0;a<s.length;a++){const i=s[a],l=e.element._zod.run({value:i,issues:[]},n);l instanceof Promise?o.push(l.then(c=>cf(c,r,a))):cf(l,r,a)}return o.length?Promise.all(o).then(()=>r):r}});function Ea(t,e,r){t.issues.length&&e.issues.push(...dn(r,t.issues)),e.value[r]=t.value}function uf(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...dn(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}const df=J("$ZodObject",(t,e)=>{Ze.init(t,e);const r=el(()=>{const p=Object.keys(e.shape);for(const d of p)if(!(e.shape[d]instanceof Ze))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const h=S1(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(h)}});Ae(t._zod,"propValues",()=>{const p=e.shape,h={};for(const d in p){const f=p[d]._zod;if(f.values){h[d]??(h[d]=new Set);for(const w of f.values)h[d].add(w)}}return h});const n=p=>{const h=new bw(["shape","payload","ctx"]),d=r.value,f=_=>{const g=Ps(_);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};h.write("const input = payload.value;");const w=Object.create(null);let m=0;for(const _ of d.keys)w[_]=`key_${m++}`;h.write("const newResult = {}");for(const _ of d.keys)if(d.optionalKeys.has(_)){const g=w[_];h.write(`const ${g} = ${f(_)};`);const b=Ps(_);h.write(`
11
11
  if (${g}.issues.length) {
12
12
  if (input[${b}] === undefined) {
13
13
  if (${b} in input) {
@@ -30,24 +30,24 @@
30
30
  if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
31
31
  ...iss,
32
32
  path: iss.path ? [${Ps(_)}, ...iss.path] : [${Ps(_)}]
33
- })));`),h.write(`newResult[${Ps(_)}] = ${g}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const y=h.compile();return(_,g)=>y(p,_,g)};let s;const o=ka,a=!Hp.jitless,l=a&&b1.value,c=e.catchall;let u;t._zod.parse=(p,h)=>{u??(u=r.value);const d=p.value;if(!o(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),p;const f=[];if(a&&l&&h?.async===!1&&h.jitless!==!0)s||(s=n(e.shape)),p=s(p,h);else{p.value={};const g=u.shape;for(const b of u.keys){const k=g[b],S=k._zod.run({value:d[b],issues:[]},h),T=k._zod.optin==="optional"&&k._zod.optout==="optional";S instanceof Promise?f.push(S.then(x=>T?df(x,p,b,d):Ea(x,p,b))):T?df(S,p,b,d):Ea(S,p,b)}}if(!c)return f.length?Promise.all(f).then(()=>p):p;const w=[],m=u.keySet,y=c._zod,_=y.def.type;for(const g of Object.keys(d)){if(m.has(g))continue;if(_==="never"){w.push(g);continue}const b=y.run({value:d[g],issues:[]},h);b instanceof Promise?f.push(b.then(k=>Ea(k,p,g))):Ea(b,p,g)}return w.length&&p.issues.push({code:"unrecognized_keys",keys:w,input:d,inst:t}),f.length?Promise.all(f).then(()=>p):p}});function ff(t,e,r,n){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>Ur(o,n,zr())))}),e}const hf=J("$ZodUnion",(t,e)=>{Ze.init(t,e),Ae(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ae(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ae(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ae(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>rl(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1;const o=[];for(const a of e.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)o.push(i),s=!0;else{if(i.issues.length===0)return i;o.push(i)}}return s?Promise.all(o).then(a=>ff(a,r,t,n)):ff(o,r,t,n)}}),tb=J("$ZodDiscriminatedUnion",(t,e)=>{hf.init(t,e);const r=t._zod.parse;Ae(t._zod,"propValues",()=>{const s={};for(const o of e.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const[i,l]of Object.entries(a)){s[i]||(s[i]=new Set);for(const c of l)s[i].add(c)}}return s});const n=el(()=>{const s=e.options,o=new Map;for(const a of s){const i=a._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const l of i){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,a)}}return o});t._zod.parse=(s,o)=>{const a=s.value;if(!ka(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),s;const i=n.value.get(a?.[e.discriminator]);return i?i._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),s)}}),rb=J("$ZodIntersection",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value,o=e.left._zod.run({value:s,issues:[]},n),a=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([l,c])=>mf(r,l,c)):mf(r,o,a)}});function il(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Sa(t)&&Sa(e)){const r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(const o of n){const a=il(t[o],e[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};s[o]=a.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<t.length;n++){const s=t[n],o=e[n],a=il(s,o);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function mf(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),As(t))return t;const n=il(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}const nb=J("$ZodRecord",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Sa(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;const o=[];if(e.keyType._zod.values){const a=e.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=e.valueType._zod.run({value:s[l],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...dn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...dn(l,c.issues)),r.value[l]=c.value)}let i;for(const l in s)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(s)){if(a==="__proto__")continue;const i=e.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>Ur(c,n,zr())),input:a,path:[a],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:s[a],issues:[]},n);l instanceof Promise?o.push(l.then(c=>{c.issues.length&&r.issues.push(...dn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...dn(a,l.issues)),r.value[i.value]=l.value)}}return o.length?Promise.all(o).then(()=>r):r}}),sb=J("$ZodEnum",(t,e)=>{Ze.init(t,e);const r=Bp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>k1.has(typeof n)).map(n=>typeof n=="string"?Os(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{const o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),ob=J("$ZodLiteral",(t,e)=>{Ze.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Os(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{const s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),ab=J("$ZodTransform",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(r.value=a,r));if(s instanceof Promise)throw new Is;return r.value=s,r}}),ib=J("$ZodOptional",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ae(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ae(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${rl(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),lb=J("$ZodNullable",(t,e)=>{Ze.init(t,e),Ae(t._zod,"optin",()=>e.innerType._zod.optin),Ae(t._zod,"optout",()=>e.innerType._zod.optout),Ae(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${rl(r.source)}|null)$`):void 0}),Ae(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),cb=J("$ZodDefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Ae(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>gf(o,e)):gf(s,e)}});function gf(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const ub=J("$ZodPrefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Ae(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),db=J("$ZodNonOptional",(t,e)=>{Ze.init(t,e),Ae(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>vf(o,t)):vf(s,t)}});function vf(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const pb=J("$ZodCatch",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Ae(t._zod,"optout",()=>e.innerType._zod.optout),Ae(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(a=>Ur(a,n,zr()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Ur(o,n,zr()))},input:r.value}),r.issues=[]),r)}}),fb=J("$ZodPipe",(t,e)=>{Ze.init(t,e),Ae(t._zod,"values",()=>e.in._zod.values),Ae(t._zod,"optin",()=>e.in._zod.optin),Ae(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{const s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>_f(o,e,n)):_f(s,e,n)}});function _f(t,e,r){return As(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const hb=J("$ZodReadonly",(t,e)=>{Ze.init(t,e),Ae(t._zod,"propValues",()=>e.innerType._zod.propValues),Ae(t._zod,"values",()=>e.innerType._zod.values),Ae(t._zod,"optin",()=>e.innerType._zod.optin),Ae(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(yf):yf(s)}});function yf(t){return t.value=Object.freeze(t.value),t}const mb=J("$ZodLazy",(t,e)=>{Ze.init(t,e),Ae(t._zod,"innerType",()=>e.getter()),Ae(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Ae(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Ae(t._zod,"optin",()=>t._zod.innerType._zod.optin),Ae(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),gb=J("$ZodCustom",(t,e)=>{bt.init(t,e),Ze.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{const n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>wf(o,r,n,t));wf(s,r,n,t)}});function wf(t,e,r,n){if(!t){const s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Ms(s))}}class bf{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const n=r[0];if(this._map.set(e,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,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function vb(){return new bf}const Ns=vb();function _b(t,e){return new t({type:"string",...ie(e)})}function yb(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ie(e)})}function kf(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ie(e)})}function wb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ie(e)})}function bb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ie(e)})}function kb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ie(e)})}function Sb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ie(e)})}function Sf(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ie(e)})}function Tb(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ie(e)})}function Cb(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ie(e)})}function $b(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ie(e)})}function Eb(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ie(e)})}function xb(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ie(e)})}function Ib(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ie(e)})}function Rb(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ie(e)})}function Pb(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ie(e)})}function Ob(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ie(e)})}function Ab(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ie(e)})}function Mb(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ie(e)})}function Tf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ie(e)})}function Nb(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ie(e)})}function Lb(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ie(e)})}function jb(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ie(e)})}function qb(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ie(e)})}function zb(t,e){return new t({type:"string",format:"date",check:"string_format",...ie(e)})}function Db(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ie(e)})}function Ub(t,e){return new t({type:"string",format:"duration",check:"string_format",...ie(e)})}function Zb(t,e){return new t({type:"number",checks:[],...ie(e)})}function Fb(t,e){return new t({type:"number",coerce:!0,checks:[],...ie(e)})}function Vb(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ie(e)})}function Hb(t,e){return new t({type:"boolean",...ie(e)})}function Bb(t,e){return new t({type:"null",...ie(e)})}function Jb(t){return new t({type:"any"})}function Gb(t){return new t({type:"unknown"})}function Wb(t,e){return new t({type:"never",...ie(e)})}function Cf(t,e){return new of({check:"less_than",...ie(e),value:t,inclusive:!1})}function ll(t,e){return new of({check:"less_than",...ie(e),value:t,inclusive:!0})}function $f(t,e){return new af({check:"greater_than",...ie(e),value:t,inclusive:!1})}function cl(t,e){return new af({check:"greater_than",...ie(e),value:t,inclusive:!0})}function Ef(t,e){return new cw({check:"multiple_of",...ie(e),value:t})}function xf(t,e){return new dw({check:"max_length",...ie(e),maximum:t})}function xa(t,e){return new pw({check:"min_length",...ie(e),minimum:t})}function If(t,e){return new fw({check:"length_equals",...ie(e),length:t})}function Kb(t,e){return new hw({check:"string_format",format:"regex",...ie(e),pattern:t})}function Yb(t){return new mw({check:"string_format",format:"lowercase",...ie(t)})}function Qb(t){return new gw({check:"string_format",format:"uppercase",...ie(t)})}function Xb(t,e){return new vw({check:"string_format",format:"includes",...ie(e),includes:t})}function e3(t,e){return new _w({check:"string_format",format:"starts_with",...ie(e),prefix:t})}function t3(t,e){return new yw({check:"string_format",format:"ends_with",...ie(e),suffix:t})}function Ls(t){return new ww({check:"overwrite",tx:t})}function r3(t){return Ls(e=>e.normalize(t))}function n3(){return Ls(t=>t.trim())}function s3(){return Ls(t=>t.toLowerCase())}function o3(){return Ls(t=>t.toUpperCase())}function a3(t,e,r){return new t({type:"array",element:e,...ie(r)})}function i3(t,e,r){const n=ie(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function l3(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ie(r)})}class Rf{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ns,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;const s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=e._zod.toJSONSchema?.();if(l)i.schema=l;else{const p={...r,schemaPath:[...r.schemaPath,e],path:r.path},h=e._zod.parent;if(h)i.ref=h,this.process(h,p),this.seen.get(h).isParent=!0;else{const d=i.schema;switch(s.type){case"string":{const f=d;f.type="string";const{minimum:w,maximum:m,format:y,patterns:_,contentEncoding:g}=e._zod.bag;if(typeof w=="number"&&(f.minLength=w),typeof m=="number"&&(f.maxLength=m),y&&(f.format=o[y]??y,f.format===""&&delete f.format),g&&(f.contentEncoding=g),_&&_.size>0){const b=[..._];b.length===1?f.pattern=b[0].source:b.length>1&&(i.schema.allOf=[...b.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const f=d,{minimum:w,maximum:m,format:y,multipleOf:_,exclusiveMaximum:g,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?f.type="integer":f.type="number",typeof b=="number"&&(f.exclusiveMinimum=b),typeof w=="number"&&(f.minimum=w,typeof b=="number"&&(b>=w?delete f.minimum:delete f.exclusiveMinimum)),typeof g=="number"&&(f.exclusiveMaximum=g),typeof m=="number"&&(f.maximum=m,typeof g=="number"&&(g<=m?delete f.maximum:delete f.exclusiveMaximum)),typeof _=="number"&&(f.multipleOf=_);break}case"boolean":{const f=d;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=d,{minimum:w,maximum:m}=e._zod.bag;typeof w=="number"&&(f.minItems=w),typeof m=="number"&&(f.maxItems=m),f.type="array",f.items=this.process(s.element,{...p,path:[...p.path,"items"]});break}case"object":{const f=d;f.type="object",f.properties={};const w=s.shape;for(const _ in w)f.properties[_]=this.process(w[_],{...p,path:[...p.path,"properties",_]});const m=new Set(Object.keys(w)),y=new Set([...m].filter(_=>{const g=s.shape[_]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));y.size>0&&(f.required=Array.from(y)),s.catchall?._zod.def.type==="never"?f.additionalProperties=!1:s.catchall?s.catchall&&(f.additionalProperties=this.process(s.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=d;f.anyOf=s.options.map((w,m)=>this.process(w,{...p,path:[...p.path,"anyOf",m]}));break}case"intersection":{const f=d,w=this.process(s.left,{...p,path:[...p.path,"allOf",0]}),m=this.process(s.right,{...p,path:[...p.path,"allOf",1]}),y=g=>"allOf"in g&&Object.keys(g).length===1,_=[...y(w)?w.allOf:[w],...y(m)?m.allOf:[m]];f.allOf=_;break}case"tuple":{const f=d;f.type="array";const w=s.items.map((_,g)=>this.process(_,{...p,path:[...p.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?f.prefixItems=w:f.items=w,s.rest){const _=this.process(s.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?f.items=_:f.additionalItems=_}s.rest&&(f.items=this.process(s.rest,{...p,path:[...p.path,"items"]}));const{minimum:m,maximum:y}=e._zod.bag;typeof m=="number"&&(f.minItems=m),typeof y=="number"&&(f.maxItems=y);break}case"record":{const f=d;f.type="object",f.propertyNames=this.process(s.keyType,{...p,path:[...p.path,"propertyNames"]}),f.additionalProperties=this.process(s.valueType,{...p,path:[...p.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 f=d,w=Bp(s.entries);w.every(m=>typeof m=="number")&&(f.type="number"),w.every(m=>typeof m=="string")&&(f.type="string"),f.enum=w;break}case"literal":{const f=d,w=[];for(const m of s.values)if(m===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof m=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(m))}else w.push(m);if(w.length!==0)if(w.length===1){const m=w[0];f.type=m===null?"null":typeof m,f.const=m}else w.every(m=>typeof m=="number")&&(f.type="number"),w.every(m=>typeof m=="string")&&(f.type="string"),w.every(m=>typeof m=="boolean")&&(f.type="string"),w.every(m=>m===null)&&(f.type="null"),f.enum=w;break}case"file":{const f=d,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:m,maximum:y,mime:_}=e._zod.bag;m!==void 0&&(w.minLength=m),y!==void 0&&(w.maxLength=y),_?_.length===1?(w.contentMediaType=_[0],Object.assign(f,w)):f.anyOf=_.map(g=>({...w,contentMediaType:g})):Object.assign(f,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(s.innerType,p);d.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"success":{const f=d;f.type="boolean";break}case"default":{this.process(s.innerType,p),i.ref=s.innerType,d.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,p),i.ref=s.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,p),i.ref=s.innerType;let f;try{f=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=d,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=w.source;break}case"pipe":{const f=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(f,p),i.ref=f;break}case"readonly":{this.process(s.innerType,p),i.ref=s.innerType,d.readOnly=!0;break}case"promise":{this.process(s.innerType,p),i.ref=s.innerType;break}case"optional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"lazy":{const f=e._zod.innerType;this.process(f,p),i.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),this.io==="input"&&Xe(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=u=>{const p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const w=n.external.registry.get(u[0])?.id,m=n.external.uri??(_=>_);if(w)return{ref:m(w)};const y=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=y,{defId:y,ref:`${m("__shared")}#/${p}/${y}`}}if(u[1]===s)return{ref:"#"};const d=`#/${p}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:d+f}},a=u=>{if(u[1].schema.$ref)return;const p=u[1],{ref:h,defId:d}=o(u);p.def={...p.schema},d&&(p.defId=d);const f=p.schema;for(const w in f)delete f[w];f.$ref=h};if(n.cycles==="throw")for(const u of this.seen.entries()){const p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
33
+ })));`),h.write(`newResult[${Ps(_)}] = ${g}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const y=h.compile();return(_,g)=>y(p,_,g)};let s;const o=ka,a=!Vp.jitless,l=a&&b1.value,c=e.catchall;let u;t._zod.parse=(p,h)=>{u??(u=r.value);const d=p.value;if(!o(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),p;const f=[];if(a&&l&&h?.async===!1&&h.jitless!==!0)s||(s=n(e.shape)),p=s(p,h);else{p.value={};const g=u.shape;for(const b of u.keys){const k=g[b],S=k._zod.run({value:d[b],issues:[]},h),T=k._zod.optin==="optional"&&k._zod.optout==="optional";S instanceof Promise?f.push(S.then(x=>T?uf(x,p,b,d):Ea(x,p,b))):T?uf(S,p,b,d):Ea(S,p,b)}}if(!c)return f.length?Promise.all(f).then(()=>p):p;const w=[],m=u.keySet,y=c._zod,_=y.def.type;for(const g of Object.keys(d)){if(m.has(g))continue;if(_==="never"){w.push(g);continue}const b=y.run({value:d[g],issues:[]},h);b instanceof Promise?f.push(b.then(k=>Ea(k,p,g))):Ea(b,p,g)}return w.length&&p.issues.push({code:"unrecognized_keys",keys:w,input:d,inst:t}),f.length?Promise.all(f).then(()=>p):p}});function pf(t,e,r,n){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>Ur(o,n,zr())))}),e}const ff=J("$ZodUnion",(t,e)=>{Ze.init(t,e),Ae(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ae(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ae(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ae(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>rl(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1;const o=[];for(const a of e.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)o.push(i),s=!0;else{if(i.issues.length===0)return i;o.push(i)}}return s?Promise.all(o).then(a=>pf(a,r,t,n)):pf(o,r,t,n)}}),tb=J("$ZodDiscriminatedUnion",(t,e)=>{ff.init(t,e);const r=t._zod.parse;Ae(t._zod,"propValues",()=>{const s={};for(const o of e.options){const a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const[i,l]of Object.entries(a)){s[i]||(s[i]=new Set);for(const c of l)s[i].add(c)}}return s});const n=el(()=>{const s=e.options,o=new Map;for(const a of s){const i=a._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const l of i){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,a)}}return o});t._zod.parse=(s,o)=>{const a=s.value;if(!ka(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),s;const i=n.value.get(a?.[e.discriminator]);return i?i._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[e.discriminator],inst:t}),s)}}),rb=J("$ZodIntersection",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value,o=e.left._zod.run({value:s,issues:[]},n),a=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([l,c])=>hf(r,l,c)):hf(r,o,a)}});function il(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Sa(t)&&Sa(e)){const r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(const o of n){const a=il(t[o],e[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};s[o]=a.data}return{valid:!0,data:s}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<t.length;n++){const s=t[n],o=e[n],a=il(s,o);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function hf(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),As(t))return t;const n=il(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}const nb=J("$ZodRecord",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=r.value;if(!Sa(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;const o=[];if(e.keyType._zod.values){const a=e.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=e.valueType._zod.run({value:s[l],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...dn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...dn(l,c.issues)),r.value[l]=c.value)}let i;for(const l in s)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(s)){if(a==="__proto__")continue;const i=e.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>Ur(c,n,zr())),input:a,path:[a],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:s[a],issues:[]},n);l instanceof Promise?o.push(l.then(c=>{c.issues.length&&r.issues.push(...dn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...dn(a,l.issues)),r.value[i.value]=l.value)}}return o.length?Promise.all(o).then(()=>r):r}}),sb=J("$ZodEnum",(t,e)=>{Ze.init(t,e);const r=Hp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>k1.has(typeof n)).map(n=>typeof n=="string"?Os(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{const o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),ob=J("$ZodLiteral",(t,e)=>{Ze.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Os(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{const s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),ab=J("$ZodTransform",(t,e)=>{Ze.init(t,e),t._zod.parse=(r,n)=>{const s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(r.value=a,r));if(s instanceof Promise)throw new Is;return r.value=s,r}}),ib=J("$ZodOptional",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ae(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ae(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${rl(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),lb=J("$ZodNullable",(t,e)=>{Ze.init(t,e),Ae(t._zod,"optin",()=>e.innerType._zod.optin),Ae(t._zod,"optout",()=>e.innerType._zod.optout),Ae(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${rl(r.source)}|null)$`):void 0}),Ae(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),cb=J("$ZodDefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Ae(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>mf(o,e)):mf(s,e)}});function mf(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const ub=J("$ZodPrefault",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Ae(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),db=J("$ZodNonOptional",(t,e)=>{Ze.init(t,e),Ae(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>gf(o,t)):gf(s,t)}});function gf(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const pb=J("$ZodCatch",(t,e)=>{Ze.init(t,e),t._zod.optin="optional",Ae(t._zod,"optout",()=>e.innerType._zod.optout),Ae(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(a=>Ur(a,n,zr()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Ur(o,n,zr()))},input:r.value}),r.issues=[]),r)}}),fb=J("$ZodPipe",(t,e)=>{Ze.init(t,e),Ae(t._zod,"values",()=>e.in._zod.values),Ae(t._zod,"optin",()=>e.in._zod.optin),Ae(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{const s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>vf(o,e,n)):vf(s,e,n)}});function vf(t,e,r){return As(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const hb=J("$ZodReadonly",(t,e)=>{Ze.init(t,e),Ae(t._zod,"propValues",()=>e.innerType._zod.propValues),Ae(t._zod,"values",()=>e.innerType._zod.values),Ae(t._zod,"optin",()=>e.innerType._zod.optin),Ae(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{const s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(_f):_f(s)}});function _f(t){return t.value=Object.freeze(t.value),t}const mb=J("$ZodLazy",(t,e)=>{Ze.init(t,e),Ae(t._zod,"innerType",()=>e.getter()),Ae(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Ae(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Ae(t._zod,"optin",()=>t._zod.innerType._zod.optin),Ae(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),gb=J("$ZodCustom",(t,e)=>{bt.init(t,e),Ze.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{const n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>yf(o,r,n,t));yf(s,r,n,t)}});function yf(t,e,r,n){if(!t){const s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push(Ms(s))}}class wf{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const n=r[0];if(this._map.set(e,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,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function vb(){return new wf}const Ns=vb();function _b(t,e){return new t({type:"string",...ie(e)})}function yb(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ie(e)})}function bf(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ie(e)})}function wb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ie(e)})}function bb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ie(e)})}function kb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ie(e)})}function Sb(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ie(e)})}function kf(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ie(e)})}function Tb(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ie(e)})}function Cb(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ie(e)})}function $b(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ie(e)})}function Eb(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ie(e)})}function xb(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ie(e)})}function Ib(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ie(e)})}function Rb(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ie(e)})}function Pb(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ie(e)})}function Ob(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ie(e)})}function Ab(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ie(e)})}function Mb(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ie(e)})}function Sf(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ie(e)})}function Nb(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ie(e)})}function Lb(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ie(e)})}function jb(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ie(e)})}function qb(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ie(e)})}function zb(t,e){return new t({type:"string",format:"date",check:"string_format",...ie(e)})}function Db(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ie(e)})}function Ub(t,e){return new t({type:"string",format:"duration",check:"string_format",...ie(e)})}function Zb(t,e){return new t({type:"number",checks:[],...ie(e)})}function Fb(t,e){return new t({type:"number",coerce:!0,checks:[],...ie(e)})}function Vb(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ie(e)})}function Hb(t,e){return new t({type:"boolean",...ie(e)})}function Bb(t,e){return new t({type:"null",...ie(e)})}function Jb(t){return new t({type:"any"})}function Gb(t){return new t({type:"unknown"})}function Wb(t,e){return new t({type:"never",...ie(e)})}function Tf(t,e){return new sf({check:"less_than",...ie(e),value:t,inclusive:!1})}function ll(t,e){return new sf({check:"less_than",...ie(e),value:t,inclusive:!0})}function Cf(t,e){return new of({check:"greater_than",...ie(e),value:t,inclusive:!1})}function cl(t,e){return new of({check:"greater_than",...ie(e),value:t,inclusive:!0})}function $f(t,e){return new cw({check:"multiple_of",...ie(e),value:t})}function Ef(t,e){return new dw({check:"max_length",...ie(e),maximum:t})}function xa(t,e){return new pw({check:"min_length",...ie(e),minimum:t})}function xf(t,e){return new fw({check:"length_equals",...ie(e),length:t})}function Kb(t,e){return new hw({check:"string_format",format:"regex",...ie(e),pattern:t})}function Yb(t){return new mw({check:"string_format",format:"lowercase",...ie(t)})}function Qb(t){return new gw({check:"string_format",format:"uppercase",...ie(t)})}function Xb(t,e){return new vw({check:"string_format",format:"includes",...ie(e),includes:t})}function e3(t,e){return new _w({check:"string_format",format:"starts_with",...ie(e),prefix:t})}function t3(t,e){return new yw({check:"string_format",format:"ends_with",...ie(e),suffix:t})}function Ls(t){return new ww({check:"overwrite",tx:t})}function r3(t){return Ls(e=>e.normalize(t))}function n3(){return Ls(t=>t.trim())}function s3(){return Ls(t=>t.toLowerCase())}function o3(){return Ls(t=>t.toUpperCase())}function a3(t,e,r){return new t({type:"array",element:e,...ie(r)})}function i3(t,e,r){const n=ie(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function l3(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ie(r)})}class If{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ns,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;const s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,r.schemaPath.includes(e)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=e._zod.toJSONSchema?.();if(l)i.schema=l;else{const p={...r,schemaPath:[...r.schemaPath,e],path:r.path},h=e._zod.parent;if(h)i.ref=h,this.process(h,p),this.seen.get(h).isParent=!0;else{const d=i.schema;switch(s.type){case"string":{const f=d;f.type="string";const{minimum:w,maximum:m,format:y,patterns:_,contentEncoding:g}=e._zod.bag;if(typeof w=="number"&&(f.minLength=w),typeof m=="number"&&(f.maxLength=m),y&&(f.format=o[y]??y,f.format===""&&delete f.format),g&&(f.contentEncoding=g),_&&_.size>0){const b=[..._];b.length===1?f.pattern=b[0].source:b.length>1&&(i.schema.allOf=[...b.map(k=>({...this.target==="draft-7"?{type:"string"}:{},pattern:k.source}))])}break}case"number":{const f=d,{minimum:w,maximum:m,format:y,multipleOf:_,exclusiveMaximum:g,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?f.type="integer":f.type="number",typeof b=="number"&&(f.exclusiveMinimum=b),typeof w=="number"&&(f.minimum=w,typeof b=="number"&&(b>=w?delete f.minimum:delete f.exclusiveMinimum)),typeof g=="number"&&(f.exclusiveMaximum=g),typeof m=="number"&&(f.maximum=m,typeof g=="number"&&(g<=m?delete f.maximum:delete f.exclusiveMaximum)),typeof _=="number"&&(f.multipleOf=_);break}case"boolean":{const f=d;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const f=d,{minimum:w,maximum:m}=e._zod.bag;typeof w=="number"&&(f.minItems=w),typeof m=="number"&&(f.maxItems=m),f.type="array",f.items=this.process(s.element,{...p,path:[...p.path,"items"]});break}case"object":{const f=d;f.type="object",f.properties={};const w=s.shape;for(const _ in w)f.properties[_]=this.process(w[_],{...p,path:[...p.path,"properties",_]});const m=new Set(Object.keys(w)),y=new Set([...m].filter(_=>{const g=s.shape[_]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));y.size>0&&(f.required=Array.from(y)),s.catchall?._zod.def.type==="never"?f.additionalProperties=!1:s.catchall?s.catchall&&(f.additionalProperties=this.process(s.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{const f=d;f.anyOf=s.options.map((w,m)=>this.process(w,{...p,path:[...p.path,"anyOf",m]}));break}case"intersection":{const f=d,w=this.process(s.left,{...p,path:[...p.path,"allOf",0]}),m=this.process(s.right,{...p,path:[...p.path,"allOf",1]}),y=g=>"allOf"in g&&Object.keys(g).length===1,_=[...y(w)?w.allOf:[w],...y(m)?m.allOf:[m]];f.allOf=_;break}case"tuple":{const f=d;f.type="array";const w=s.items.map((_,g)=>this.process(_,{...p,path:[...p.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?f.prefixItems=w:f.items=w,s.rest){const _=this.process(s.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?f.items=_:f.additionalItems=_}s.rest&&(f.items=this.process(s.rest,{...p,path:[...p.path,"items"]}));const{minimum:m,maximum:y}=e._zod.bag;typeof m=="number"&&(f.minItems=m),typeof y=="number"&&(f.maxItems=y);break}case"record":{const f=d;f.type="object",f.propertyNames=this.process(s.keyType,{...p,path:[...p.path,"propertyNames"]}),f.additionalProperties=this.process(s.valueType,{...p,path:[...p.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 f=d,w=Hp(s.entries);w.every(m=>typeof m=="number")&&(f.type="number"),w.every(m=>typeof m=="string")&&(f.type="string"),f.enum=w;break}case"literal":{const f=d,w=[];for(const m of s.values)if(m===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof m=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(m))}else w.push(m);if(w.length!==0)if(w.length===1){const m=w[0];f.type=m===null?"null":typeof m,f.const=m}else w.every(m=>typeof m=="number")&&(f.type="number"),w.every(m=>typeof m=="string")&&(f.type="string"),w.every(m=>typeof m=="boolean")&&(f.type="string"),w.every(m=>m===null)&&(f.type="null"),f.enum=w;break}case"file":{const f=d,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:m,maximum:y,mime:_}=e._zod.bag;m!==void 0&&(w.minLength=m),y!==void 0&&(w.maxLength=y),_?_.length===1?(w.contentMediaType=_[0],Object.assign(f,w)):f.anyOf=_.map(g=>({...w,contentMediaType:g})):Object.assign(f,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const f=this.process(s.innerType,p);d.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"success":{const f=d;f.type="boolean";break}case"default":{this.process(s.innerType,p),i.ref=s.innerType,d.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,p),i.ref=s.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,p),i.ref=s.innerType;let f;try{f=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const f=d,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=w.source;break}case"pipe":{const f=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(f,p),i.ref=f;break}case"readonly":{this.process(s.innerType,p),i.ref=s.innerType,d.readOnly=!0;break}case"promise":{this.process(s.innerType,p),i.ref=s.innerType;break}case"optional":{this.process(s.innerType,p),i.ref=s.innerType;break}case"lazy":{const f=e._zod.innerType;this.process(f,p),i.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),this.io==="input"&&Xe(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=u=>{const p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const w=n.external.registry.get(u[0])?.id,m=n.external.uri??(_=>_);if(w)return{ref:m(w)};const y=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=y,{defId:y,ref:`${m("__shared")}#/${p}/${y}`}}if(u[1]===s)return{ref:"#"};const d=`#/${p}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:d+f}},a=u=>{if(u[1].schema.$ref)return;const p=u[1],{ref:h,defId:d}=o(u);p.def={...p.schema},d&&(p.defId=d);const f=p.schema;for(const w in f)delete f[w];f.$ref=h};if(n.cycles==="throw")for(const u of this.seen.entries()){const p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
34
34
 
35
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const p=u[1];if(e===u[0]){a(u);continue}if(n.external){const d=n.external.registry.get(u[0])?.id;if(e!==u[0]&&d){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(p.cycle){a(u);continue}if(p.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,p)=>{const h=this.seen.get(u),d=h.def??h.schema,f={...d};if(h.ref===null)return;const w=h.ref;if(h.ref=null,w){i(w,p);const m=this.seen.get(w).schema;m.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(m)):(Object.assign(d,m),Object.assign(d,f))}h.isParent||this.override({zodSchema:u,jsonSchema:d,path:h.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,s.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const p=u[1];p.def&&p.defId&&(c[p.defId]=p.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 ul(t,e){if(t instanceof bf){const n=new Rf(e),s={};for(const i of t._idmap.entries()){const[l,c]=i;n.process(c)}const o={},a={registry:t,uri:e?.uri,defs:s};for(const i of t._idmap.entries()){const[l,c]=i;o[l]=n.emit(c,{...e,external:a})}if(Object.keys(s).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[i]:s}}return{schemas:o}}const r=new Rf(e);return r.process(t),r.emit(t,e)}function Xe(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const s=t._zod.def;switch(s.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 Xe(s.element,r);case"object":{for(const o in s.shape)if(Xe(s.shape[o],r))return!0;return!1}case"union":{for(const o of s.options)if(Xe(o,r))return!0;return!1}case"intersection":return Xe(s.left,r)||Xe(s.right,r);case"tuple":{for(const o of s.items)if(Xe(o,r))return!0;return!!(s.rest&&Xe(s.rest,r))}case"record":return Xe(s.keyType,r)||Xe(s.valueType,r);case"map":return Xe(s.keyType,r)||Xe(s.valueType,r);case"set":return Xe(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Xe(s.innerType,r);case"lazy":return Xe(s.getter(),r);case"default":return Xe(s.innerType,r);case"prefault":return Xe(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Xe(s.in,r)||Xe(s.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const c3=J("ZodISODateTime",(t,e)=>{Mw.init(t,e),Ke.init(t,e)});function Pf(t){return qb(c3,t)}const u3=J("ZodISODate",(t,e)=>{Nw.init(t,e),Ke.init(t,e)});function d3(t){return zb(u3,t)}const p3=J("ZodISOTime",(t,e)=>{Lw.init(t,e),Ke.init(t,e)});function f3(t){return Db(p3,t)}const h3=J("ZodISODuration",(t,e)=>{jw.init(t,e),Ke.init(t,e)});function m3(t){return Ub(h3,t)}const Ia=J("ZodError",(t,e)=>{Wp.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>O1(t,r)},flatten:{value:r=>P1(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),g3=Kp(Ia),v3=Yp(Ia),_3=Qp(Ia),dl=Xp(Ia),Be=J("ZodType",(t,e)=>(Ze.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>g3(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>_3(t,r,n),t.parseAsync=async(r,n)=>v3(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>dl(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(l9(r,n)),t.superRefine=r=>t.check(c9(r)),t.overwrite=r=>t.check(Ls(r)),t.optional=()=>Q(t),t.nullable=()=>Zf(t),t.nullish=()=>Q(Zf(t)),t.nonoptional=r=>e9(t,r),t.array=()=>N(t),t.or=r=>ce([t,r]),t.and=r=>hl(t,r),t.transform=r=>gl(t,Df(r)),t.default=r=>Y3(t,r),t.prefault=r=>X3(t,r),t.catch=r=>r9(t,r),t.pipe=r=>gl(t,r),t.readonly=()=>o9(t),t.describe=r=>{const n=t.clone();return Ns.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ns.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ns.get(t);const n=t.clone();return Ns.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Of=J("_ZodString",(t,e)=>{al.init(t,e),Be.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Kb(...n)),t.includes=(...n)=>t.check(Xb(...n)),t.startsWith=(...n)=>t.check(e3(...n)),t.endsWith=(...n)=>t.check(t3(...n)),t.min=(...n)=>t.check(xa(...n)),t.max=(...n)=>t.check(xf(...n)),t.length=(...n)=>t.check(If(...n)),t.nonempty=(...n)=>t.check(xa(1,...n)),t.lowercase=n=>t.check(Yb(n)),t.uppercase=n=>t.check(Qb(n)),t.trim=()=>t.check(n3()),t.normalize=(...n)=>t.check(r3(...n)),t.toLowerCase=()=>t.check(s3()),t.toUpperCase=()=>t.check(o3())}),y3=J("ZodString",(t,e)=>{al.init(t,e),Of.init(t,e),t.email=r=>t.check(yb(w3,r)),t.url=r=>t.check(Sf(Mf,r)),t.jwt=r=>t.check(jb(N3,r)),t.emoji=r=>t.check(Tb(k3,r)),t.guid=r=>t.check(kf(Af,r)),t.uuid=r=>t.check(wb(Ra,r)),t.uuidv4=r=>t.check(bb(Ra,r)),t.uuidv6=r=>t.check(kb(Ra,r)),t.uuidv7=r=>t.check(Sb(Ra,r)),t.nanoid=r=>t.check(Cb(S3,r)),t.guid=r=>t.check(kf(Af,r)),t.cuid=r=>t.check($b(T3,r)),t.cuid2=r=>t.check(Eb(C3,r)),t.ulid=r=>t.check(xb($3,r)),t.base64=r=>t.check(Tf(Nf,r)),t.base64url=r=>t.check(Nb(A3,r)),t.xid=r=>t.check(Ib(E3,r)),t.ksuid=r=>t.check(Rb(x3,r)),t.ipv4=r=>t.check(Pb(I3,r)),t.ipv6=r=>t.check(Ob(R3,r)),t.cidrv4=r=>t.check(Ab(P3,r)),t.cidrv6=r=>t.check(Mb(O3,r)),t.e164=r=>t.check(Lb(M3,r)),t.datetime=r=>t.check(Pf(r)),t.date=r=>t.check(d3(r)),t.time=r=>t.check(f3(r)),t.duration=r=>t.check(m3(r))});function v(t){return _b(y3,t)}const Ke=J("ZodStringFormat",(t,e)=>{Ge.init(t,e),Of.init(t,e)}),w3=J("ZodEmail",(t,e)=>{Cw.init(t,e),Ke.init(t,e)}),Af=J("ZodGUID",(t,e)=>{Sw.init(t,e),Ke.init(t,e)}),Ra=J("ZodUUID",(t,e)=>{Tw.init(t,e),Ke.init(t,e)}),Mf=J("ZodURL",(t,e)=>{$w.init(t,e),Ke.init(t,e)});function b3(t){return Sf(Mf,t)}const k3=J("ZodEmoji",(t,e)=>{Ew.init(t,e),Ke.init(t,e)}),S3=J("ZodNanoID",(t,e)=>{xw.init(t,e),Ke.init(t,e)}),T3=J("ZodCUID",(t,e)=>{Iw.init(t,e),Ke.init(t,e)}),C3=J("ZodCUID2",(t,e)=>{Rw.init(t,e),Ke.init(t,e)}),$3=J("ZodULID",(t,e)=>{Pw.init(t,e),Ke.init(t,e)}),E3=J("ZodXID",(t,e)=>{Ow.init(t,e),Ke.init(t,e)}),x3=J("ZodKSUID",(t,e)=>{Aw.init(t,e),Ke.init(t,e)}),I3=J("ZodIPv4",(t,e)=>{qw.init(t,e),Ke.init(t,e)}),R3=J("ZodIPv6",(t,e)=>{zw.init(t,e),Ke.init(t,e)}),P3=J("ZodCIDRv4",(t,e)=>{Dw.init(t,e),Ke.init(t,e)}),O3=J("ZodCIDRv6",(t,e)=>{Uw.init(t,e),Ke.init(t,e)}),Nf=J("ZodBase64",(t,e)=>{Zw.init(t,e),Ke.init(t,e)});function Lf(t){return Tf(Nf,t)}const A3=J("ZodBase64URL",(t,e)=>{Vw.init(t,e),Ke.init(t,e)}),M3=J("ZodE164",(t,e)=>{Hw.init(t,e),Ke.init(t,e)}),N3=J("ZodJWT",(t,e)=>{Jw.init(t,e),Ke.init(t,e)}),pl=J("ZodNumber",(t,e)=>{cf.init(t,e),Be.init(t,e),t.gt=(n,s)=>t.check($f(n,s)),t.gte=(n,s)=>t.check(cl(n,s)),t.min=(n,s)=>t.check(cl(n,s)),t.lt=(n,s)=>t.check(Cf(n,s)),t.lte=(n,s)=>t.check(ll(n,s)),t.max=(n,s)=>t.check(ll(n,s)),t.int=n=>t.check(jf(n)),t.safe=n=>t.check(jf(n)),t.positive=n=>t.check($f(0,n)),t.nonnegative=n=>t.check(cl(0,n)),t.negative=n=>t.check(Cf(0,n)),t.nonpositive=n=>t.check(ll(0,n)),t.multipleOf=(n,s)=>t.check(Ef(n,s)),t.step=(n,s)=>t.check(Ef(n,s)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function L(t){return Zb(pl,t)}const L3=J("ZodNumberFormat",(t,e)=>{Gw.init(t,e),pl.init(t,e)});function jf(t){return Vb(L3,t)}const j3=J("ZodBoolean",(t,e)=>{Ww.init(t,e),Be.init(t,e)});function ge(t){return Hb(j3,t)}const q3=J("ZodNull",(t,e)=>{Kw.init(t,e),Be.init(t,e)});function fl(t){return Bb(q3,t)}const z3=J("ZodAny",(t,e)=>{Yw.init(t,e),Be.init(t,e)});function ht(){return Jb(z3)}const D3=J("ZodUnknown",(t,e)=>{Qw.init(t,e),Be.init(t,e)});function Le(){return Gb(D3)}const U3=J("ZodNever",(t,e)=>{Xw.init(t,e),Be.init(t,e)});function Z3(t){return Wb(U3,t)}const F3=J("ZodArray",(t,e)=>{eb.init(t,e),Be.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xa(r,n)),t.nonempty=r=>t.check(xa(1,r)),t.max=(r,n)=>t.check(xf(r,n)),t.length=(r,n)=>t.check(If(r,n)),t.unwrap=()=>t.element});function N(t,e){return a3(F3,t,e)}const qf=J("ZodObject",(t,e)=>{pf.init(t,e),Be.init(t,e),Ae(t,"shape",()=>e.shape),t.keyof=()=>Ce(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Le()}),t.loose=()=>t.clone({...t._zod.def,catchall:Le()}),t.strict=()=>t.clone({...t._zod.def,catchall:Z3()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>E1(t,r),t.merge=r=>x1(t,r),t.pick=r=>C1(t,r),t.omit=r=>$1(t,r),t.partial=(...r)=>I1(Uf,t,r[0]),t.required=(...r)=>R1(Ff,t,r[0])});function C(t,e){const r={type:"object",get shape(){return Rs(this,"shape",{...t}),this.shape},...ie(e)};return new qf(r)}function Ye(t,e){return new qf({type:"object",get shape(){return Rs(this,"shape",{...t}),this.shape},catchall:Le(),...ie(e)})}const zf=J("ZodUnion",(t,e)=>{hf.init(t,e),Be.init(t,e),t.options=e.options});function ce(t,e){return new zf({type:"union",options:t,...ie(e)})}const V3=J("ZodDiscriminatedUnion",(t,e)=>{zf.init(t,e),tb.init(t,e)});function et(t,e,r){return new V3({type:"union",options:e,discriminator:t,...ie(r)})}const H3=J("ZodIntersection",(t,e)=>{rb.init(t,e),Be.init(t,e)});function hl(t,e){return new H3({type:"intersection",left:t,right:e})}const B3=J("ZodRecord",(t,e)=>{nb.init(t,e),Be.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Se(t,e,r){return new B3({type:"record",keyType:t,valueType:e,...ie(r)})}const ml=J("ZodEnum",(t,e)=>{sb.init(t,e),Be.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{const o={};for(const a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new ml({...e,checks:[],...ie(s),entries:o})},t.exclude=(n,s)=>{const o={...e.entries};for(const a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new ml({...e,checks:[],...ie(s),entries:o})}});function Ce(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new ml({type:"enum",entries:r,...ie(e)})}const J3=J("ZodLiteral",(t,e)=>{ob.init(t,e),Be.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function j(t,e){return new J3({type:"literal",values:Array.isArray(t)?t:[t],...ie(e)})}const G3=J("ZodTransform",(t,e)=>{ab.init(t,e),Be.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ms(o,r.value,e));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(Ms(a))}};const s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});function Df(t){return new G3({type:"transform",transform:t})}const Uf=J("ZodOptional",(t,e)=>{ib.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Q(t){return new Uf({type:"optional",innerType:t})}const W3=J("ZodNullable",(t,e)=>{lb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Zf(t){return new W3({type:"nullable",innerType:t})}const K3=J("ZodDefault",(t,e)=>{cb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Y3(t,e){return new K3({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Q3=J("ZodPrefault",(t,e)=>{ub.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function X3(t,e){return new Q3({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Ff=J("ZodNonOptional",(t,e)=>{db.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function e9(t,e){return new Ff({type:"nonoptional",innerType:t,...ie(e)})}const t9=J("ZodCatch",(t,e)=>{pb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function r9(t,e){return new t9({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const n9=J("ZodPipe",(t,e)=>{fb.init(t,e),Be.init(t,e),t.in=e.in,t.out=e.out});function gl(t,e){return new n9({type:"pipe",in:t,out:e})}const s9=J("ZodReadonly",(t,e)=>{hb.init(t,e),Be.init(t,e)});function o9(t){return new s9({type:"readonly",innerType:t})}const a9=J("ZodLazy",(t,e)=>{mb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.getter()});function Vf(t){return new a9({type:"lazy",getter:t})}const vl=J("ZodCustom",(t,e)=>{gb.init(t,e),Be.init(t,e)});function i9(t){const e=new bt({check:"custom"});return e._zod.check=t,e}function Hf(t,e){return i3(vl,t??(()=>!0),e)}function l9(t,e={}){return l3(vl,t,e)}function c9(t){const e=i9(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ms(n,r.value,e._zod.def));else{const s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Ms(s))}},t(r.value,r)));return e}function Pa(t,e={error:`Input not instance of ${t.name}`}){const r=new vl({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ie(e)});return r._zod.bag.Class=t,r}function Bf(t,e){return gl(Df(t),e)}const Jf={custom:"custom"};function Gf(t){return Fb(pl,t)}const js="2025-11-25",Wf=[js,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Cr="io.modelcontextprotocol/related-task",Oa="2.0",ir=Hf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Kf=ce([v(),L().int()]),Yf=v(),u9=Ye({ttl:ce([L(),fl()]).optional(),pollInterval:L().optional()}),_l=Ye({taskId:v()}),d9=Ye({progressToken:Kf.optional(),[Cr]:_l.optional()}),kt=Ye({task:u9.optional(),_meta:d9.optional()}),ot=C({method:v(),params:kt.optional()}),pn=Ye({_meta:C({[Cr]:Q(_l)}).passthrough().optional()}),jt=C({method:v(),params:pn.optional()}),ut=Ye({_meta:Ye({[Cr]:_l.optional()}).optional()}),Aa=ce([v(),L().int()]),Qf=C({jsonrpc:j(Oa),id:Aa,...ot.shape}).strict(),yl=t=>Qf.safeParse(t).success,Xf=C({jsonrpc:j(Oa),...jt.shape}).strict(),p9=t=>Xf.safeParse(t).success,eh=C({jsonrpc:j(Oa),id:Aa,result:ut}).strict(),qs=t=>eh.safeParse(t).success;var ae;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ae||(ae={}));const th=C({jsonrpc:j(Oa),id:Aa,error:C({code:L().int(),message:v(),data:Q(Le())})}).strict(),f9=t=>th.safeParse(t).success,$r=ce([Qf,Xf,eh,th]),Zr=ut.strict(),h9=pn.extend({requestId:Aa,reason:v().optional()}),wl=jt.extend({method:j("notifications/cancelled"),params:h9}),m9=C({src:v(),mimeType:v().optional(),sizes:N(v()).optional()}),zs=C({icons:N(m9).optional()}),Nn=C({name:v(),title:v().optional()}),rh=Nn.extend({...Nn.shape,...zs.shape,version:v(),websiteUrl:v().optional()}),g9=hl(C({applyDefaults:ge().optional()}),Se(v(),Le())),v9=Bf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,hl(C({form:g9.optional(),url:ir.optional()}),Se(v(),Le()).optional())),_9=C({list:Q(C({}).passthrough()),cancel:Q(C({}).passthrough()),requests:Q(C({sampling:Q(C({createMessage:Q(C({}).passthrough())}).passthrough()),elicitation:Q(C({create:Q(C({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),y9=C({list:Q(C({}).passthrough()),cancel:Q(C({}).passthrough()),requests:Q(C({tools:Q(C({call:Q(C({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),w9=C({experimental:Se(v(),ir).optional(),sampling:C({context:ir.optional(),tools:ir.optional()}).optional(),elicitation:v9.optional(),roots:C({listChanged:ge().optional()}).optional(),tasks:Q(_9)}),b9=kt.extend({protocolVersion:v(),capabilities:w9,clientInfo:rh}),nh=ot.extend({method:j("initialize"),params:b9}),k9=C({experimental:Se(v(),ir).optional(),logging:ir.optional(),completions:ir.optional(),prompts:Q(C({listChanged:Q(ge())})),resources:C({subscribe:ge().optional(),listChanged:ge().optional()}).optional(),tools:C({listChanged:ge().optional()}).optional(),tasks:Q(y9)}).passthrough(),sh=ut.extend({protocolVersion:v(),capabilities:k9,serverInfo:rh,instructions:v().optional()}),bl=jt.extend({method:j("notifications/initialized")}),S9=t=>bl.safeParse(t).success,kl=ot.extend({method:j("ping")}),T9=C({progress:L(),total:Q(L()),message:Q(v())}),C9=C({...pn.shape,...T9.shape,progressToken:Kf}),Sl=jt.extend({method:j("notifications/progress"),params:C9}),$9=kt.extend({cursor:Yf.optional()}),Ds=ot.extend({params:$9.optional()}),Us=ut.extend({nextCursor:Q(Yf)}),Zs=C({taskId:v(),status:Ce(["working","input_required","completed","failed","cancelled"]),ttl:ce([L(),fl()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:Q(L()),statusMessage:Q(v())}),Ln=ut.extend({task:Zs}),E9=pn.merge(Zs),Ma=jt.extend({method:j("notifications/tasks/status"),params:E9}),Tl=ot.extend({method:j("tasks/get"),params:kt.extend({taskId:v()})}),Cl=ut.merge(Zs),$l=ot.extend({method:j("tasks/result"),params:kt.extend({taskId:v()})}),El=Ds.extend({method:j("tasks/list")}),xl=Us.extend({tasks:N(Zs)}),x9=ot.extend({method:j("tasks/cancel"),params:kt.extend({taskId:v()})}),I9=ut.merge(Zs),oh=C({uri:v(),mimeType:Q(v()),_meta:Se(v(),Le()).optional()}),ah=oh.extend({text:v()}),Il=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ih=oh.extend({blob:Il}),jn=C({audience:N(Ce(["user","assistant"])).optional(),priority:L().min(0).max(1).optional(),lastModified:Pf({offset:!0}).optional()}),lh=C({...Nn.shape,...zs.shape,uri:v(),description:Q(v()),mimeType:Q(v()),annotations:jn.optional(),_meta:Q(Ye({}))}),R9=C({...Nn.shape,...zs.shape,uriTemplate:v(),description:Q(v()),mimeType:Q(v()),annotations:jn.optional(),_meta:Q(Ye({}))}),Na=Ds.extend({method:j("resources/list")}),ch=Us.extend({resources:N(lh)}),Rl=Ds.extend({method:j("resources/templates/list")}),uh=Us.extend({resourceTemplates:N(R9)}),Pl=kt.extend({uri:v()}),P9=Pl,Ol=ot.extend({method:j("resources/read"),params:P9}),dh=ut.extend({contents:N(ce([ah,ih]))}),ph=jt.extend({method:j("notifications/resources/list_changed")}),O9=Pl,fh=ot.extend({method:j("resources/subscribe"),params:O9}),A9=Pl,hh=ot.extend({method:j("resources/unsubscribe"),params:A9}),M9=pn.extend({uri:v()}),mh=jt.extend({method:j("notifications/resources/updated"),params:M9}),N9=C({name:v(),description:Q(v()),required:Q(ge())}),L9=C({...Nn.shape,...zs.shape,description:Q(v()),arguments:Q(N(N9)),_meta:Q(Ye({}))}),Al=Ds.extend({method:j("prompts/list")}),gh=Us.extend({prompts:N(L9)}),j9=kt.extend({name:v(),arguments:Se(v(),v()).optional()}),Ml=ot.extend({method:j("prompts/get"),params:j9}),Nl=C({type:j("text"),text:v(),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),Ll=C({type:j("image"),data:Il,mimeType:v(),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),jl=C({type:j("audio"),data:Il,mimeType:v(),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),q9=C({type:j("tool_use"),name:v(),id:v(),input:C({}).passthrough(),_meta:Q(C({}).passthrough())}).passthrough(),z9=C({type:j("resource"),resource:ce([ah,ih]),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),D9=lh.extend({type:j("resource_link")}),ql=ce([Nl,Ll,jl,D9,z9]),U9=C({role:Ce(["user","assistant"]),content:ql}),vh=ut.extend({description:Q(v()),messages:N(U9)}),_h=jt.extend({method:j("notifications/prompts/list_changed")}),Z9=C({title:v().optional(),readOnlyHint:ge().optional(),destructiveHint:ge().optional(),idempotentHint:ge().optional(),openWorldHint:ge().optional()}),F9=C({taskSupport:Ce(["required","optional","forbidden"]).optional()}),yh=C({...Nn.shape,...zs.shape,description:v().optional(),inputSchema:C({type:j("object"),properties:Se(v(),ir).optional(),required:N(v()).optional()}).catchall(Le()),outputSchema:C({type:j("object"),properties:Se(v(),ir).optional(),required:N(v()).optional()}).catchall(Le()).optional(),annotations:Q(Z9),execution:Q(F9),_meta:Se(v(),Le()).optional()}),zl=Ds.extend({method:j("tools/list")}),wh=Us.extend({tools:N(yh)}),qn=ut.extend({content:N(ql).default([]),structuredContent:Se(v(),Le()).optional(),isError:Q(ge())});qn.or(ut.extend({toolResult:Le()}));const V9=kt.extend({name:v(),arguments:Q(Se(v(),Le()))}),La=ot.extend({method:j("tools/call"),params:V9}),bh=jt.extend({method:j("notifications/tools/list_changed")}),ja=Ce(["debug","info","notice","warning","error","critical","alert","emergency"]),H9=kt.extend({level:ja}),qa=ot.extend({method:j("logging/setLevel"),params:H9}),B9=pn.extend({level:ja,logger:v().optional(),data:Le()}),kh=jt.extend({method:j("notifications/message"),params:B9}),J9=C({name:v().optional()}),G9=C({hints:Q(N(J9)),costPriority:Q(L().min(0).max(1)),speedPriority:Q(L().min(0).max(1)),intelligencePriority:Q(L().min(0).max(1))}),W9=C({mode:Q(Ce(["auto","required","none"]))}),K9=C({type:j("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:N(ql).default([]),structuredContent:C({}).passthrough().optional(),isError:Q(ge()),_meta:Q(C({}).passthrough())}).passthrough(),Y9=et("type",[Nl,Ll,jl]),za=et("type",[Nl,Ll,jl,q9,K9]),Q9=C({role:Ce(["user","assistant"]),content:ce([za,N(za)]),_meta:Q(C({}).passthrough())}).passthrough(),X9=kt.extend({messages:N(Q9),modelPreferences:G9.optional(),systemPrompt:v().optional(),includeContext:Ce(["none","thisServer","allServers"]).optional(),temperature:L().optional(),maxTokens:L().int(),stopSequences:N(v()).optional(),metadata:ir.optional(),tools:Q(N(yh)),toolChoice:Q(W9)}),Dl=ot.extend({method:j("sampling/createMessage"),params:X9}),Da=ut.extend({model:v(),stopReason:Q(Ce(["endTurn","stopSequence","maxTokens"]).or(v())),role:Ce(["user","assistant"]),content:Y9}),Sh=ut.extend({model:v(),stopReason:Q(Ce(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:Ce(["user","assistant"]),content:ce([za,N(za)])}),e4=C({type:j("boolean"),title:v().optional(),description:v().optional(),default:ge().optional()}),t4=C({type:j("string"),title:v().optional(),description:v().optional(),minLength:L().optional(),maxLength:L().optional(),format:Ce(["email","uri","date","date-time"]).optional(),default:v().optional()}),r4=C({type:Ce(["number","integer"]),title:v().optional(),description:v().optional(),minimum:L().optional(),maximum:L().optional(),default:L().optional()}),n4=C({type:j("string"),title:v().optional(),description:v().optional(),enum:N(v()),default:v().optional()}),s4=C({type:j("string"),title:v().optional(),description:v().optional(),oneOf:N(C({const:v(),title:v()})),default:v().optional()}),o4=C({type:j("string"),title:v().optional(),description:v().optional(),enum:N(v()),enumNames:N(v()).optional(),default:v().optional()}),a4=ce([n4,s4]),i4=C({type:j("array"),title:v().optional(),description:v().optional(),minItems:L().optional(),maxItems:L().optional(),items:C({type:j("string"),enum:N(v())}),default:N(v()).optional()}),l4=C({type:j("array"),title:v().optional(),description:v().optional(),minItems:L().optional(),maxItems:L().optional(),items:C({anyOf:N(C({const:v(),title:v()}))}),default:N(v()).optional()}),c4=ce([i4,l4]),u4=ce([o4,a4,c4]),d4=ce([u4,e4,t4,r4]),p4=kt.extend({mode:j("form").optional(),message:v(),requestedSchema:C({type:j("object"),properties:Se(v(),d4),required:N(v()).optional()})}),f4=kt.extend({mode:j("url"),message:v(),elicitationId:v(),url:v().url()}),h4=ce([p4,f4]),Ul=ot.extend({method:j("elicitation/create"),params:h4}),m4=pn.extend({elicitationId:v()}),g4=jt.extend({method:j("notifications/elicitation/complete"),params:m4}),Fs=ut.extend({action:Ce(["accept","decline","cancel"]),content:Bf(t=>t===null?void 0:t,Se(v(),ce([v(),L(),ge(),N(v())])).optional())}),v4=C({type:j("ref/resource"),uri:v()}),_4=C({type:j("ref/prompt"),name:v()}),y4=kt.extend({ref:ce([_4,v4]),argument:C({name:v(),value:v()}),context:C({arguments:Se(v(),v()).optional()}).optional()}),Zl=ot.extend({method:j("completion/complete"),params:y4});function w4(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function b4(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}const Th=ut.extend({completion:Ye({values:N(v()).max(100),total:Q(L().int()),hasMore:Q(ge())})}),k4=C({uri:v().startsWith("file://"),name:v().optional(),_meta:Se(v(),Le()).optional()}),Ch=ot.extend({method:j("roots/list")}),Fl=ut.extend({roots:N(k4)}),$h=jt.extend({method:j("notifications/roots/list_changed")});ce([kl,nh,Zl,qa,Ml,Al,Na,Rl,Ol,fh,hh,La,zl,Tl,$l,El]),ce([wl,Sl,bl,$h,Ma]),ce([Zr,Da,Sh,Fs,Fl,Cl,xl,Ln]),ce([kl,Dl,Ul,Ch,Tl,$l,El]),ce([wl,Sl,kh,mh,ph,bh,_h,Ma,g4]),ce([Zr,sh,Th,vh,gh,ch,uh,dh,qn,wh,Cl,xl,Ln]);class ne extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===ae.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new S4(s.elicitations,r)}return new ne(e,r,n)}}class S4 extends ne{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ae.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e,r;return(r=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&r!==void 0?r:[]}}const T4=J("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ze.init(t,e),t.def=e,t.parse=(r,n)=>A1(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>sl(t,r,n),t.parseAsync=async(r,n)=>M1(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ol(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),C4=J("ZodMiniObject",(t,e)=>{pf.init(t,e),T4.init(t,e),Ae(t,"shape",()=>e.shape)});function Eh(t,e){const r={type:"object",get shape(){return Rs(this,"shape",{...t}),this.shape},...ie(e)};return new C4(r)}function qt(t){return!!t._zod}function Vs(t){const e=Object.values(t);if(e.length===0)return Eh({});const r=e.every(qt),n=e.every(s=>!qt(s));if(r)return Eh(t);if(n)return Zp(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ht(t,e){return qt(t)?sl(t,e):t.safeParse(e)}async function Vl(t,e){return qt(t)?await ol(t,e):await t.safeParseAsync(e)}function zn(t){var e,r;if(!t)return;let n;if(qt(t)?n=(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.shape:n=t.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function Hs(t){var e;if(t){if(typeof t=="object"){const r=t,n=t;if(!r._def&&!n._zod){const s=Object.values(t);if(s.length>0&&s.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Vs(t)}}if(qt(t)){const n=(e=t._zod)===null||e===void 0?void 0:e.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Hl(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){const e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function $4(t){var e,r,n,s;if(qt(t))return(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.description;const o=t;return(n=t.description)!==null&&n!==void 0?n:(s=o._def)===null||s===void 0?void 0:s.description}function E4(t){var e,r,n;if(qt(t))return((r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.type)==="optional";const s=t;return typeof t.isOptional=="function"?t.isOptional():((n=s._def)===null||n===void 0?void 0:n.typeName)==="ZodOptional"}function xh(t){var e;if(qt(t)){const a=(e=t._zod)===null||e===void 0?void 0:e.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const s=t.value;if(s!==void 0)return s}function fn(t){return t==="completed"||t==="failed"||t==="cancelled"}const x4=Symbol("Let zodToJsonSchema decide on which parser to use"),Ih={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},I4=t=>typeof t=="string"?{...Ih,name:t}:{...Ih,...t},R4=t=>{const e=I4(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Rh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function qe(t,e,r,n,s){t[e]=r,Rh(t,e,n,s)}const Ph=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function St(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ph(e,t.currentPath):e.join("/")}}function P4(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==z.ZodAny&&(r.items=Me(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&qe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&qe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(qe(r,"minItems",t.exactLength.value,t.exactLength.message,e),qe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function O4(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function A4(){return{type:"boolean"}}function Oh(t,e){return Me(t.type._def,e)}const M4=(t,e)=>Me(t.innerType._def,e);function Ah(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Ah(t,e,s))};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 N4(t,e)}}const N4=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":qe(r,"minimum",n.value,n.message,e);break;case"max":qe(r,"maximum",n.value,n.message,e);break}return r};function L4(t,e){return{...Me(t.innerType._def,e),default:t.defaultValue()}}function j4(t,e){return e.effectStrategy==="input"?Me(t.schema._def,e):St(e)}function q4(t){return{type:"string",enum:Array.from(t.values)}}const z4=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function D4(t,e){const r=[Me(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Me(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(o=>{if(z4(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...l}=o;a=l}else n=void 0;s.push(a)}}),s.length?{allOf:s,...n}:void 0}function U4(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let Bl;const Bt={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:()=>(Bl===void 0&&(Bl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Bl),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 Mh(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Jt(r,"email",n.message,e);break;case"format:idn-email":Jt(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,Bt.email,n.message,e);break}break;case"url":Jt(r,"uri",n.message,e);break;case"uuid":Jt(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,Bt.cuid,n.message,e);break;case"cuid2":mt(r,Bt.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${Jl(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${Jl(n.value,e)}$`),n.message,e);break;case"datetime":Jt(r,"date-time",n.message,e);break;case"date":Jt(r,"date",n.message,e);break;case"time":Jt(r,"time",n.message,e);break;case"duration":Jt(r,"duration",n.message,e);break;case"length":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(Jl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Jt(r,"ipv4",n.message,e),n.version!=="v4"&&Jt(r,"ipv6",n.message,e);break}case"base64url":mt(r,Bt.base64url,n.message,e);break;case"jwt":mt(r,Bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,Bt.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,Bt.ipv6Cidr,n.message,e);break}case"emoji":mt(r,Bt.emoji(),n.message,e);break;case"ulid":{mt(r,Bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Jt(r,"binary",n.message,e);break}case"contentEncoding:base64":{qe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,Bt.base64,n.message,e);break}}break}case"nanoid":mt(r,Bt.nanoid,n.message,e)}return r}function Jl(t,e){return e.patternStrategy==="escape"?F4(t):t}const Z4=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function F4(t){let e="";for(let r=0;r<t.length;r++)Z4.has(t[r])||(e+="\\"),e+=t[r];return e}function Jt(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):qe(t,"format",e,r,n)}function mt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Nh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):qe(t,"pattern",Nh(e,n),r,n)}function Nh(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",o=!1,a=!1,i=!1;for(let l=0;l<n.length;l++){if(o){s+=n[l],o=!1;continue}if(r.i){if(a){if(n[l].match(/[a-z]/)){i?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),i=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],i=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){s+=`(^|(?<=[\r
35
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const p=u[1];if(e===u[0]){a(u);continue}if(n.external){const d=n.external.registry.get(u[0])?.id;if(e!==u[0]&&d){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(p.cycle){a(u);continue}if(p.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,p)=>{const h=this.seen.get(u),d=h.def??h.schema,f={...d};if(h.ref===null)return;const w=h.ref;if(h.ref=null,w){i(w,p);const m=this.seen.get(w).schema;m.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(m)):(Object.assign(d,m),Object.assign(d,f))}h.isParent||this.override({zodSchema:u,jsonSchema:d,path:h.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,s.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const p=u[1];p.def&&p.defId&&(c[p.defId]=p.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 ul(t,e){if(t instanceof wf){const n=new If(e),s={};for(const i of t._idmap.entries()){const[l,c]=i;n.process(c)}const o={},a={registry:t,uri:e?.uri,defs:s};for(const i of t._idmap.entries()){const[l,c]=i;o[l]=n.emit(c,{...e,external:a})}if(Object.keys(s).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[i]:s}}return{schemas:o}}const r=new If(e);return r.process(t),r.emit(t,e)}function Xe(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const s=t._zod.def;switch(s.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 Xe(s.element,r);case"object":{for(const o in s.shape)if(Xe(s.shape[o],r))return!0;return!1}case"union":{for(const o of s.options)if(Xe(o,r))return!0;return!1}case"intersection":return Xe(s.left,r)||Xe(s.right,r);case"tuple":{for(const o of s.items)if(Xe(o,r))return!0;return!!(s.rest&&Xe(s.rest,r))}case"record":return Xe(s.keyType,r)||Xe(s.valueType,r);case"map":return Xe(s.keyType,r)||Xe(s.valueType,r);case"set":return Xe(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Xe(s.innerType,r);case"lazy":return Xe(s.getter(),r);case"default":return Xe(s.innerType,r);case"prefault":return Xe(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Xe(s.in,r)||Xe(s.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const c3=J("ZodISODateTime",(t,e)=>{Mw.init(t,e),Ke.init(t,e)});function Rf(t){return qb(c3,t)}const u3=J("ZodISODate",(t,e)=>{Nw.init(t,e),Ke.init(t,e)});function d3(t){return zb(u3,t)}const p3=J("ZodISOTime",(t,e)=>{Lw.init(t,e),Ke.init(t,e)});function f3(t){return Db(p3,t)}const h3=J("ZodISODuration",(t,e)=>{jw.init(t,e),Ke.init(t,e)});function m3(t){return Ub(h3,t)}const Ia=J("ZodError",(t,e)=>{Gp.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>O1(t,r)},flatten:{value:r=>P1(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),g3=Wp(Ia),v3=Kp(Ia),_3=Yp(Ia),dl=Qp(Ia),Be=J("ZodType",(t,e)=>(Ze.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>g3(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>_3(t,r,n),t.parseAsync=async(r,n)=>v3(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>dl(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(l9(r,n)),t.superRefine=r=>t.check(c9(r)),t.overwrite=r=>t.check(Ls(r)),t.optional=()=>Q(t),t.nullable=()=>Uf(t),t.nullish=()=>Q(Uf(t)),t.nonoptional=r=>e9(t,r),t.array=()=>N(t),t.or=r=>ce([t,r]),t.and=r=>hl(t,r),t.transform=r=>gl(t,zf(r)),t.default=r=>Y3(t,r),t.prefault=r=>X3(t,r),t.catch=r=>r9(t,r),t.pipe=r=>gl(t,r),t.readonly=()=>o9(t),t.describe=r=>{const n=t.clone();return Ns.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ns.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ns.get(t);const n=t.clone();return Ns.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Pf=J("_ZodString",(t,e)=>{al.init(t,e),Be.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Kb(...n)),t.includes=(...n)=>t.check(Xb(...n)),t.startsWith=(...n)=>t.check(e3(...n)),t.endsWith=(...n)=>t.check(t3(...n)),t.min=(...n)=>t.check(xa(...n)),t.max=(...n)=>t.check(Ef(...n)),t.length=(...n)=>t.check(xf(...n)),t.nonempty=(...n)=>t.check(xa(1,...n)),t.lowercase=n=>t.check(Yb(n)),t.uppercase=n=>t.check(Qb(n)),t.trim=()=>t.check(n3()),t.normalize=(...n)=>t.check(r3(...n)),t.toLowerCase=()=>t.check(s3()),t.toUpperCase=()=>t.check(o3())}),y3=J("ZodString",(t,e)=>{al.init(t,e),Pf.init(t,e),t.email=r=>t.check(yb(w3,r)),t.url=r=>t.check(kf(Af,r)),t.jwt=r=>t.check(jb(N3,r)),t.emoji=r=>t.check(Tb(k3,r)),t.guid=r=>t.check(bf(Of,r)),t.uuid=r=>t.check(wb(Ra,r)),t.uuidv4=r=>t.check(bb(Ra,r)),t.uuidv6=r=>t.check(kb(Ra,r)),t.uuidv7=r=>t.check(Sb(Ra,r)),t.nanoid=r=>t.check(Cb(S3,r)),t.guid=r=>t.check(bf(Of,r)),t.cuid=r=>t.check($b(T3,r)),t.cuid2=r=>t.check(Eb(C3,r)),t.ulid=r=>t.check(xb($3,r)),t.base64=r=>t.check(Sf(Mf,r)),t.base64url=r=>t.check(Nb(A3,r)),t.xid=r=>t.check(Ib(E3,r)),t.ksuid=r=>t.check(Rb(x3,r)),t.ipv4=r=>t.check(Pb(I3,r)),t.ipv6=r=>t.check(Ob(R3,r)),t.cidrv4=r=>t.check(Ab(P3,r)),t.cidrv6=r=>t.check(Mb(O3,r)),t.e164=r=>t.check(Lb(M3,r)),t.datetime=r=>t.check(Rf(r)),t.date=r=>t.check(d3(r)),t.time=r=>t.check(f3(r)),t.duration=r=>t.check(m3(r))});function v(t){return _b(y3,t)}const Ke=J("ZodStringFormat",(t,e)=>{Ge.init(t,e),Pf.init(t,e)}),w3=J("ZodEmail",(t,e)=>{Cw.init(t,e),Ke.init(t,e)}),Of=J("ZodGUID",(t,e)=>{Sw.init(t,e),Ke.init(t,e)}),Ra=J("ZodUUID",(t,e)=>{Tw.init(t,e),Ke.init(t,e)}),Af=J("ZodURL",(t,e)=>{$w.init(t,e),Ke.init(t,e)});function b3(t){return kf(Af,t)}const k3=J("ZodEmoji",(t,e)=>{Ew.init(t,e),Ke.init(t,e)}),S3=J("ZodNanoID",(t,e)=>{xw.init(t,e),Ke.init(t,e)}),T3=J("ZodCUID",(t,e)=>{Iw.init(t,e),Ke.init(t,e)}),C3=J("ZodCUID2",(t,e)=>{Rw.init(t,e),Ke.init(t,e)}),$3=J("ZodULID",(t,e)=>{Pw.init(t,e),Ke.init(t,e)}),E3=J("ZodXID",(t,e)=>{Ow.init(t,e),Ke.init(t,e)}),x3=J("ZodKSUID",(t,e)=>{Aw.init(t,e),Ke.init(t,e)}),I3=J("ZodIPv4",(t,e)=>{qw.init(t,e),Ke.init(t,e)}),R3=J("ZodIPv6",(t,e)=>{zw.init(t,e),Ke.init(t,e)}),P3=J("ZodCIDRv4",(t,e)=>{Dw.init(t,e),Ke.init(t,e)}),O3=J("ZodCIDRv6",(t,e)=>{Uw.init(t,e),Ke.init(t,e)}),Mf=J("ZodBase64",(t,e)=>{Zw.init(t,e),Ke.init(t,e)});function Nf(t){return Sf(Mf,t)}const A3=J("ZodBase64URL",(t,e)=>{Vw.init(t,e),Ke.init(t,e)}),M3=J("ZodE164",(t,e)=>{Hw.init(t,e),Ke.init(t,e)}),N3=J("ZodJWT",(t,e)=>{Jw.init(t,e),Ke.init(t,e)}),pl=J("ZodNumber",(t,e)=>{lf.init(t,e),Be.init(t,e),t.gt=(n,s)=>t.check(Cf(n,s)),t.gte=(n,s)=>t.check(cl(n,s)),t.min=(n,s)=>t.check(cl(n,s)),t.lt=(n,s)=>t.check(Tf(n,s)),t.lte=(n,s)=>t.check(ll(n,s)),t.max=(n,s)=>t.check(ll(n,s)),t.int=n=>t.check(Lf(n)),t.safe=n=>t.check(Lf(n)),t.positive=n=>t.check(Cf(0,n)),t.nonnegative=n=>t.check(cl(0,n)),t.negative=n=>t.check(Tf(0,n)),t.nonpositive=n=>t.check(ll(0,n)),t.multipleOf=(n,s)=>t.check($f(n,s)),t.step=(n,s)=>t.check($f(n,s)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function L(t){return Zb(pl,t)}const L3=J("ZodNumberFormat",(t,e)=>{Gw.init(t,e),pl.init(t,e)});function Lf(t){return Vb(L3,t)}const j3=J("ZodBoolean",(t,e)=>{Ww.init(t,e),Be.init(t,e)});function ge(t){return Hb(j3,t)}const q3=J("ZodNull",(t,e)=>{Kw.init(t,e),Be.init(t,e)});function fl(t){return Bb(q3,t)}const z3=J("ZodAny",(t,e)=>{Yw.init(t,e),Be.init(t,e)});function ht(){return Jb(z3)}const D3=J("ZodUnknown",(t,e)=>{Qw.init(t,e),Be.init(t,e)});function Le(){return Gb(D3)}const U3=J("ZodNever",(t,e)=>{Xw.init(t,e),Be.init(t,e)});function Z3(t){return Wb(U3,t)}const F3=J("ZodArray",(t,e)=>{eb.init(t,e),Be.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xa(r,n)),t.nonempty=r=>t.check(xa(1,r)),t.max=(r,n)=>t.check(Ef(r,n)),t.length=(r,n)=>t.check(xf(r,n)),t.unwrap=()=>t.element});function N(t,e){return a3(F3,t,e)}const jf=J("ZodObject",(t,e)=>{df.init(t,e),Be.init(t,e),Ae(t,"shape",()=>e.shape),t.keyof=()=>Ce(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Le()}),t.loose=()=>t.clone({...t._zod.def,catchall:Le()}),t.strict=()=>t.clone({...t._zod.def,catchall:Z3()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>E1(t,r),t.merge=r=>x1(t,r),t.pick=r=>C1(t,r),t.omit=r=>$1(t,r),t.partial=(...r)=>I1(Df,t,r[0]),t.required=(...r)=>R1(Zf,t,r[0])});function C(t,e){const r={type:"object",get shape(){return Rs(this,"shape",{...t}),this.shape},...ie(e)};return new jf(r)}function Ye(t,e){return new jf({type:"object",get shape(){return Rs(this,"shape",{...t}),this.shape},catchall:Le(),...ie(e)})}const qf=J("ZodUnion",(t,e)=>{ff.init(t,e),Be.init(t,e),t.options=e.options});function ce(t,e){return new qf({type:"union",options:t,...ie(e)})}const V3=J("ZodDiscriminatedUnion",(t,e)=>{qf.init(t,e),tb.init(t,e)});function et(t,e,r){return new V3({type:"union",options:e,discriminator:t,...ie(r)})}const H3=J("ZodIntersection",(t,e)=>{rb.init(t,e),Be.init(t,e)});function hl(t,e){return new H3({type:"intersection",left:t,right:e})}const B3=J("ZodRecord",(t,e)=>{nb.init(t,e),Be.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Se(t,e,r){return new B3({type:"record",keyType:t,valueType:e,...ie(r)})}const ml=J("ZodEnum",(t,e)=>{sb.init(t,e),Be.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{const o={};for(const a of n)if(r.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new ml({...e,checks:[],...ie(s),entries:o})},t.exclude=(n,s)=>{const o={...e.entries};for(const a of n)if(r.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new ml({...e,checks:[],...ie(s),entries:o})}});function Ce(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new ml({type:"enum",entries:r,...ie(e)})}const J3=J("ZodLiteral",(t,e)=>{ob.init(t,e),Be.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function j(t,e){return new J3({type:"literal",values:Array.isArray(t)?t:[t],...ie(e)})}const G3=J("ZodTransform",(t,e)=>{ab.init(t,e),Be.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(Ms(o,r.value,e));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(Ms(a))}};const s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});function zf(t){return new G3({type:"transform",transform:t})}const Df=J("ZodOptional",(t,e)=>{ib.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Q(t){return new Df({type:"optional",innerType:t})}const W3=J("ZodNullable",(t,e)=>{lb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Uf(t){return new W3({type:"nullable",innerType:t})}const K3=J("ZodDefault",(t,e)=>{cb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Y3(t,e){return new K3({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Q3=J("ZodPrefault",(t,e)=>{ub.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function X3(t,e){return new Q3({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Zf=J("ZodNonOptional",(t,e)=>{db.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType});function e9(t,e){return new Zf({type:"nonoptional",innerType:t,...ie(e)})}const t9=J("ZodCatch",(t,e)=>{pb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function r9(t,e){return new t9({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const n9=J("ZodPipe",(t,e)=>{fb.init(t,e),Be.init(t,e),t.in=e.in,t.out=e.out});function gl(t,e){return new n9({type:"pipe",in:t,out:e})}const s9=J("ZodReadonly",(t,e)=>{hb.init(t,e),Be.init(t,e)});function o9(t){return new s9({type:"readonly",innerType:t})}const a9=J("ZodLazy",(t,e)=>{mb.init(t,e),Be.init(t,e),t.unwrap=()=>t._zod.def.getter()});function Ff(t){return new a9({type:"lazy",getter:t})}const vl=J("ZodCustom",(t,e)=>{gb.init(t,e),Be.init(t,e)});function i9(t){const e=new bt({check:"custom"});return e._zod.check=t,e}function Vf(t,e){return i3(vl,t??(()=>!0),e)}function l9(t,e={}){return l3(vl,t,e)}function c9(t){const e=i9(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ms(n,r.value,e._zod.def));else{const s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(Ms(s))}},t(r.value,r)));return e}function Pa(t,e={error:`Input not instance of ${t.name}`}){const r=new vl({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...ie(e)});return r._zod.bag.Class=t,r}function Hf(t,e){return gl(zf(t),e)}const Bf={custom:"custom"};function Jf(t){return Fb(pl,t)}const js="2025-11-25",Gf=[js,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Cr="io.modelcontextprotocol/related-task",Oa="2.0",ir=Vf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Wf=ce([v(),L().int()]),Kf=v(),u9=Ye({ttl:ce([L(),fl()]).optional(),pollInterval:L().optional()}),_l=Ye({taskId:v()}),d9=Ye({progressToken:Wf.optional(),[Cr]:_l.optional()}),kt=Ye({task:u9.optional(),_meta:d9.optional()}),ot=C({method:v(),params:kt.optional()}),pn=Ye({_meta:C({[Cr]:Q(_l)}).passthrough().optional()}),jt=C({method:v(),params:pn.optional()}),ut=Ye({_meta:Ye({[Cr]:_l.optional()}).optional()}),Aa=ce([v(),L().int()]),Yf=C({jsonrpc:j(Oa),id:Aa,...ot.shape}).strict(),yl=t=>Yf.safeParse(t).success,Qf=C({jsonrpc:j(Oa),...jt.shape}).strict(),p9=t=>Qf.safeParse(t).success,Xf=C({jsonrpc:j(Oa),id:Aa,result:ut}).strict(),qs=t=>Xf.safeParse(t).success;var ae;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ae||(ae={}));const eh=C({jsonrpc:j(Oa),id:Aa,error:C({code:L().int(),message:v(),data:Q(Le())})}).strict(),f9=t=>eh.safeParse(t).success,$r=ce([Yf,Qf,Xf,eh]),Zr=ut.strict(),h9=pn.extend({requestId:Aa,reason:v().optional()}),wl=jt.extend({method:j("notifications/cancelled"),params:h9}),m9=C({src:v(),mimeType:v().optional(),sizes:N(v()).optional()}),zs=C({icons:N(m9).optional()}),Nn=C({name:v(),title:v().optional()}),th=Nn.extend({...Nn.shape,...zs.shape,version:v(),websiteUrl:v().optional()}),g9=hl(C({applyDefaults:ge().optional()}),Se(v(),Le())),v9=Hf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,hl(C({form:g9.optional(),url:ir.optional()}),Se(v(),Le()).optional())),_9=C({list:Q(C({}).passthrough()),cancel:Q(C({}).passthrough()),requests:Q(C({sampling:Q(C({createMessage:Q(C({}).passthrough())}).passthrough()),elicitation:Q(C({create:Q(C({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),y9=C({list:Q(C({}).passthrough()),cancel:Q(C({}).passthrough()),requests:Q(C({tools:Q(C({call:Q(C({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),w9=C({experimental:Se(v(),ir).optional(),sampling:C({context:ir.optional(),tools:ir.optional()}).optional(),elicitation:v9.optional(),roots:C({listChanged:ge().optional()}).optional(),tasks:Q(_9)}),b9=kt.extend({protocolVersion:v(),capabilities:w9,clientInfo:th}),rh=ot.extend({method:j("initialize"),params:b9}),k9=C({experimental:Se(v(),ir).optional(),logging:ir.optional(),completions:ir.optional(),prompts:Q(C({listChanged:Q(ge())})),resources:C({subscribe:ge().optional(),listChanged:ge().optional()}).optional(),tools:C({listChanged:ge().optional()}).optional(),tasks:Q(y9)}).passthrough(),nh=ut.extend({protocolVersion:v(),capabilities:k9,serverInfo:th,instructions:v().optional()}),bl=jt.extend({method:j("notifications/initialized")}),S9=t=>bl.safeParse(t).success,kl=ot.extend({method:j("ping")}),T9=C({progress:L(),total:Q(L()),message:Q(v())}),C9=C({...pn.shape,...T9.shape,progressToken:Wf}),Sl=jt.extend({method:j("notifications/progress"),params:C9}),$9=kt.extend({cursor:Kf.optional()}),Ds=ot.extend({params:$9.optional()}),Us=ut.extend({nextCursor:Q(Kf)}),Zs=C({taskId:v(),status:Ce(["working","input_required","completed","failed","cancelled"]),ttl:ce([L(),fl()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:Q(L()),statusMessage:Q(v())}),Ln=ut.extend({task:Zs}),E9=pn.merge(Zs),Ma=jt.extend({method:j("notifications/tasks/status"),params:E9}),Tl=ot.extend({method:j("tasks/get"),params:kt.extend({taskId:v()})}),Cl=ut.merge(Zs),$l=ot.extend({method:j("tasks/result"),params:kt.extend({taskId:v()})}),El=Ds.extend({method:j("tasks/list")}),xl=Us.extend({tasks:N(Zs)}),x9=ot.extend({method:j("tasks/cancel"),params:kt.extend({taskId:v()})}),I9=ut.merge(Zs),sh=C({uri:v(),mimeType:Q(v()),_meta:Se(v(),Le()).optional()}),oh=sh.extend({text:v()}),Il=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ah=sh.extend({blob:Il}),jn=C({audience:N(Ce(["user","assistant"])).optional(),priority:L().min(0).max(1).optional(),lastModified:Rf({offset:!0}).optional()}),ih=C({...Nn.shape,...zs.shape,uri:v(),description:Q(v()),mimeType:Q(v()),annotations:jn.optional(),_meta:Q(Ye({}))}),R9=C({...Nn.shape,...zs.shape,uriTemplate:v(),description:Q(v()),mimeType:Q(v()),annotations:jn.optional(),_meta:Q(Ye({}))}),Na=Ds.extend({method:j("resources/list")}),lh=Us.extend({resources:N(ih)}),Rl=Ds.extend({method:j("resources/templates/list")}),ch=Us.extend({resourceTemplates:N(R9)}),Pl=kt.extend({uri:v()}),P9=Pl,Ol=ot.extend({method:j("resources/read"),params:P9}),uh=ut.extend({contents:N(ce([oh,ah]))}),dh=jt.extend({method:j("notifications/resources/list_changed")}),O9=Pl,ph=ot.extend({method:j("resources/subscribe"),params:O9}),A9=Pl,fh=ot.extend({method:j("resources/unsubscribe"),params:A9}),M9=pn.extend({uri:v()}),hh=jt.extend({method:j("notifications/resources/updated"),params:M9}),N9=C({name:v(),description:Q(v()),required:Q(ge())}),L9=C({...Nn.shape,...zs.shape,description:Q(v()),arguments:Q(N(N9)),_meta:Q(Ye({}))}),Al=Ds.extend({method:j("prompts/list")}),mh=Us.extend({prompts:N(L9)}),j9=kt.extend({name:v(),arguments:Se(v(),v()).optional()}),Ml=ot.extend({method:j("prompts/get"),params:j9}),Nl=C({type:j("text"),text:v(),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),Ll=C({type:j("image"),data:Il,mimeType:v(),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),jl=C({type:j("audio"),data:Il,mimeType:v(),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),q9=C({type:j("tool_use"),name:v(),id:v(),input:C({}).passthrough(),_meta:Q(C({}).passthrough())}).passthrough(),z9=C({type:j("resource"),resource:ce([oh,ah]),annotations:jn.optional(),_meta:Se(v(),Le()).optional()}),D9=ih.extend({type:j("resource_link")}),ql=ce([Nl,Ll,jl,D9,z9]),U9=C({role:Ce(["user","assistant"]),content:ql}),gh=ut.extend({description:Q(v()),messages:N(U9)}),vh=jt.extend({method:j("notifications/prompts/list_changed")}),Z9=C({title:v().optional(),readOnlyHint:ge().optional(),destructiveHint:ge().optional(),idempotentHint:ge().optional(),openWorldHint:ge().optional()}),F9=C({taskSupport:Ce(["required","optional","forbidden"]).optional()}),_h=C({...Nn.shape,...zs.shape,description:v().optional(),inputSchema:C({type:j("object"),properties:Se(v(),ir).optional(),required:N(v()).optional()}).catchall(Le()),outputSchema:C({type:j("object"),properties:Se(v(),ir).optional(),required:N(v()).optional()}).catchall(Le()).optional(),annotations:Q(Z9),execution:Q(F9),_meta:Se(v(),Le()).optional()}),zl=Ds.extend({method:j("tools/list")}),yh=Us.extend({tools:N(_h)}),qn=ut.extend({content:N(ql).default([]),structuredContent:Se(v(),Le()).optional(),isError:Q(ge())});qn.or(ut.extend({toolResult:Le()}));const V9=kt.extend({name:v(),arguments:Q(Se(v(),Le()))}),La=ot.extend({method:j("tools/call"),params:V9}),wh=jt.extend({method:j("notifications/tools/list_changed")}),ja=Ce(["debug","info","notice","warning","error","critical","alert","emergency"]),H9=kt.extend({level:ja}),qa=ot.extend({method:j("logging/setLevel"),params:H9}),B9=pn.extend({level:ja,logger:v().optional(),data:Le()}),bh=jt.extend({method:j("notifications/message"),params:B9}),J9=C({name:v().optional()}),G9=C({hints:Q(N(J9)),costPriority:Q(L().min(0).max(1)),speedPriority:Q(L().min(0).max(1)),intelligencePriority:Q(L().min(0).max(1))}),W9=C({mode:Q(Ce(["auto","required","none"]))}),K9=C({type:j("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:N(ql).default([]),structuredContent:C({}).passthrough().optional(),isError:Q(ge()),_meta:Q(C({}).passthrough())}).passthrough(),Y9=et("type",[Nl,Ll,jl]),za=et("type",[Nl,Ll,jl,q9,K9]),Q9=C({role:Ce(["user","assistant"]),content:ce([za,N(za)]),_meta:Q(C({}).passthrough())}).passthrough(),X9=kt.extend({messages:N(Q9),modelPreferences:G9.optional(),systemPrompt:v().optional(),includeContext:Ce(["none","thisServer","allServers"]).optional(),temperature:L().optional(),maxTokens:L().int(),stopSequences:N(v()).optional(),metadata:ir.optional(),tools:Q(N(_h)),toolChoice:Q(W9)}),Dl=ot.extend({method:j("sampling/createMessage"),params:X9}),Da=ut.extend({model:v(),stopReason:Q(Ce(["endTurn","stopSequence","maxTokens"]).or(v())),role:Ce(["user","assistant"]),content:Y9}),kh=ut.extend({model:v(),stopReason:Q(Ce(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:Ce(["user","assistant"]),content:ce([za,N(za)])}),e4=C({type:j("boolean"),title:v().optional(),description:v().optional(),default:ge().optional()}),t4=C({type:j("string"),title:v().optional(),description:v().optional(),minLength:L().optional(),maxLength:L().optional(),format:Ce(["email","uri","date","date-time"]).optional(),default:v().optional()}),r4=C({type:Ce(["number","integer"]),title:v().optional(),description:v().optional(),minimum:L().optional(),maximum:L().optional(),default:L().optional()}),n4=C({type:j("string"),title:v().optional(),description:v().optional(),enum:N(v()),default:v().optional()}),s4=C({type:j("string"),title:v().optional(),description:v().optional(),oneOf:N(C({const:v(),title:v()})),default:v().optional()}),o4=C({type:j("string"),title:v().optional(),description:v().optional(),enum:N(v()),enumNames:N(v()).optional(),default:v().optional()}),a4=ce([n4,s4]),i4=C({type:j("array"),title:v().optional(),description:v().optional(),minItems:L().optional(),maxItems:L().optional(),items:C({type:j("string"),enum:N(v())}),default:N(v()).optional()}),l4=C({type:j("array"),title:v().optional(),description:v().optional(),minItems:L().optional(),maxItems:L().optional(),items:C({anyOf:N(C({const:v(),title:v()}))}),default:N(v()).optional()}),c4=ce([i4,l4]),u4=ce([o4,a4,c4]),d4=ce([u4,e4,t4,r4]),p4=kt.extend({mode:j("form").optional(),message:v(),requestedSchema:C({type:j("object"),properties:Se(v(),d4),required:N(v()).optional()})}),f4=kt.extend({mode:j("url"),message:v(),elicitationId:v(),url:v().url()}),h4=ce([p4,f4]),Ul=ot.extend({method:j("elicitation/create"),params:h4}),m4=pn.extend({elicitationId:v()}),g4=jt.extend({method:j("notifications/elicitation/complete"),params:m4}),Fs=ut.extend({action:Ce(["accept","decline","cancel"]),content:Hf(t=>t===null?void 0:t,Se(v(),ce([v(),L(),ge(),N(v())])).optional())}),v4=C({type:j("ref/resource"),uri:v()}),_4=C({type:j("ref/prompt"),name:v()}),y4=kt.extend({ref:ce([_4,v4]),argument:C({name:v(),value:v()}),context:C({arguments:Se(v(),v()).optional()}).optional()}),Zl=ot.extend({method:j("completion/complete"),params:y4});function w4(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function b4(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}const Sh=ut.extend({completion:Ye({values:N(v()).max(100),total:Q(L().int()),hasMore:Q(ge())})}),k4=C({uri:v().startsWith("file://"),name:v().optional(),_meta:Se(v(),Le()).optional()}),Th=ot.extend({method:j("roots/list")}),Fl=ut.extend({roots:N(k4)}),Ch=jt.extend({method:j("notifications/roots/list_changed")});ce([kl,rh,Zl,qa,Ml,Al,Na,Rl,Ol,ph,fh,La,zl,Tl,$l,El]),ce([wl,Sl,bl,Ch,Ma]),ce([Zr,Da,kh,Fs,Fl,Cl,xl,Ln]),ce([kl,Dl,Ul,Th,Tl,$l,El]),ce([wl,Sl,bh,hh,dh,wh,vh,Ma,g4]),ce([Zr,nh,Sh,gh,mh,lh,ch,uh,qn,yh,Cl,xl,Ln]);class ne extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===ae.UrlElicitationRequired&&n){const s=n;if(s.elicitations)return new S4(s.elicitations,r)}return new ne(e,r,n)}}class S4 extends ne{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ae.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e,r;return(r=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&r!==void 0?r:[]}}const T4=J("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ze.init(t,e),t.def=e,t.parse=(r,n)=>A1(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>sl(t,r,n),t.parseAsync=async(r,n)=>M1(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ol(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),C4=J("ZodMiniObject",(t,e)=>{df.init(t,e),T4.init(t,e),Ae(t,"shape",()=>e.shape)});function $h(t,e){const r={type:"object",get shape(){return Rs(this,"shape",{...t}),this.shape},...ie(e)};return new C4(r)}function qt(t){return!!t._zod}function Vs(t){const e=Object.values(t);if(e.length===0)return $h({});const r=e.every(qt),n=e.every(s=>!qt(s));if(r)return $h(t);if(n)return Up(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ht(t,e){return qt(t)?sl(t,e):t.safeParse(e)}async function Vl(t,e){return qt(t)?await ol(t,e):await t.safeParseAsync(e)}function zn(t){var e,r;if(!t)return;let n;if(qt(t)?n=(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.shape:n=t.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function Hs(t){var e;if(t){if(typeof t=="object"){const r=t,n=t;if(!r._def&&!n._zod){const s=Object.values(t);if(s.length>0&&s.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Vs(t)}}if(qt(t)){const n=(e=t._zod)===null||e===void 0?void 0:e.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Hl(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){const e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function $4(t){var e,r,n,s;if(qt(t))return(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.description;const o=t;return(n=t.description)!==null&&n!==void 0?n:(s=o._def)===null||s===void 0?void 0:s.description}function E4(t){var e,r,n;if(qt(t))return((r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.type)==="optional";const s=t;return typeof t.isOptional=="function"?t.isOptional():((n=s._def)===null||n===void 0?void 0:n.typeName)==="ZodOptional"}function Eh(t){var e;if(qt(t)){const a=(e=t._zod)===null||e===void 0?void 0:e.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}const n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}const s=t.value;if(s!==void 0)return s}function fn(t){return t==="completed"||t==="failed"||t==="cancelled"}const x4=Symbol("Let zodToJsonSchema decide on which parser to use"),xh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},I4=t=>typeof t=="string"?{...xh,name:t}:{...xh,...t},R4=t=>{const e=I4(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Ih(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function qe(t,e,r,n,s){t[e]=r,Ih(t,e,n,s)}const Rh=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function St(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Rh(e,t.currentPath):e.join("/")}}function P4(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==z.ZodAny&&(r.items=Me(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&qe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&qe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(qe(r,"minItems",t.exactLength.value,t.exactLength.message,e),qe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function O4(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function A4(){return{type:"boolean"}}function Ph(t,e){return Me(t.type._def,e)}const M4=(t,e)=>Me(t.innerType._def,e);function Oh(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Oh(t,e,s))};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 N4(t,e)}}const N4=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":qe(r,"minimum",n.value,n.message,e);break;case"max":qe(r,"maximum",n.value,n.message,e);break}return r};function L4(t,e){return{...Me(t.innerType._def,e),default:t.defaultValue()}}function j4(t,e){return e.effectStrategy==="input"?Me(t.schema._def,e):St(e)}function q4(t){return{type:"string",enum:Array.from(t.values)}}const z4=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function D4(t,e){const r=[Me(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Me(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(o=>{if(z4(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:i,...l}=o;a=l}else n=void 0;s.push(a)}}),s.length?{allOf:s,...n}:void 0}function U4(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let Bl;const Bt={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:()=>(Bl===void 0&&(Bl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Bl),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 Ah(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Jt(r,"email",n.message,e);break;case"format:idn-email":Jt(r,"idn-email",n.message,e);break;case"pattern:zod":mt(r,Bt.email,n.message,e);break}break;case"url":Jt(r,"uri",n.message,e);break;case"uuid":Jt(r,"uuid",n.message,e);break;case"regex":mt(r,n.regex,n.message,e);break;case"cuid":mt(r,Bt.cuid,n.message,e);break;case"cuid2":mt(r,Bt.cuid2,n.message,e);break;case"startsWith":mt(r,RegExp(`^${Jl(n.value,e)}`),n.message,e);break;case"endsWith":mt(r,RegExp(`${Jl(n.value,e)}$`),n.message,e);break;case"datetime":Jt(r,"date-time",n.message,e);break;case"date":Jt(r,"date",n.message,e);break;case"time":Jt(r,"time",n.message,e);break;case"duration":Jt(r,"duration",n.message,e);break;case"length":qe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),qe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{mt(r,RegExp(Jl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Jt(r,"ipv4",n.message,e),n.version!=="v4"&&Jt(r,"ipv6",n.message,e);break}case"base64url":mt(r,Bt.base64url,n.message,e);break;case"jwt":mt(r,Bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&mt(r,Bt.ipv4Cidr,n.message,e),n.version!=="v4"&&mt(r,Bt.ipv6Cidr,n.message,e);break}case"emoji":mt(r,Bt.emoji(),n.message,e);break;case"ulid":{mt(r,Bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Jt(r,"binary",n.message,e);break}case"contentEncoding:base64":{qe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{mt(r,Bt.base64,n.message,e);break}}break}case"nanoid":mt(r,Bt.nanoid,n.message,e)}return r}function Jl(t,e){return e.patternStrategy==="escape"?F4(t):t}const Z4=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function F4(t){let e="";for(let r=0;r<t.length;r++)Z4.has(t[r])||(e+="\\"),e+=t[r];return e}function Jt(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):qe(t,"format",e,r,n)}function mt(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Mh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):qe(t,"pattern",Mh(e,n),r,n)}function Mh(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",o=!1,a=!1,i=!1;for(let l=0;l<n.length;l++){if(o){s+=n[l],o=!1;continue}if(r.i){if(a){if(n[l].match(/[a-z]/)){i?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),i=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],i=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){s+=`(^|(?<=[\r
36
36
  ]))`;continue}else if(n[l]==="$"){s+=`($|(?=[\r
37
37
  ]))`;continue}}if(r.s&&n[l]==="."){s+=a?`${n[l]}\r
38
38
  `:`[${n[l]}\r
39
- ]`;continue}s+=n[l],n[l]==="\\"?o=!0:a&&n[l]==="]"?a=!1:!a&&n[l]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Lh(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===z.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??St(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===z.ZodString&&t.keyType._def.checks?.length){const{type:n,...s}=Mh(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===z.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...s}=Oh(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function V4(t,e){if(e.mapStrategy==="record")return Lh(t,e);const r=Me(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||St(e),n=Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||St(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function H4(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function B4(t){return t.target==="openAi"?void 0:{not:St({...t,currentPath:[...t.currentPath,"not"]})}}function J4(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ua={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function G4(t,e){if(e.target==="openApi3")return jh(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ua&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Ua[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return jh(t,e)}const jh=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Me(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function W4(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Ua[t.innerType._def.typeName],nullable:!0}:{type:[Ua[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=Me(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Me(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function K4(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Rh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function Y4(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(const i in o){let l=o[i];if(l===void 0||l._def===void 0)continue;let c=X4(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Me(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,c||s.push(i))}s.length&&(n.required=s);const a=Q4(t,e);return a!==void 0&&(n.additionalProperties=a),n}function Q4(t,e){if(t.catchall._def.typeName!=="ZodNever")return Me(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function X4(t){try{return t.isOptional()}catch{return!0}}const ek=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Me(t.innerType._def,e);const r=Me(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:St(e)},r]}:St(e)},tk=(t,e)=>{if(e.pipeStrategy==="input")return Me(t.in._def,e);if(e.pipeStrategy==="output")return Me(t.out._def,e);const r=Me(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Me(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function rk(t,e){return Me(t.type._def,e)}function nk(t,e){const n={type:"array",uniqueItems:!0,items:Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&qe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&qe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function sk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Me(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Me(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Me(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function ok(t){return{not:St(t)}}function ak(t){return St(t)}const ik=(t,e)=>Me(t.innerType._def,e),lk=(t,e,r)=>{switch(e){case z.ZodString:return Mh(t,r);case z.ZodNumber:return K4(t,r);case z.ZodObject:return Y4(t,r);case z.ZodBigInt:return O4(t,r);case z.ZodBoolean:return A4();case z.ZodDate:return Ah(t,r);case z.ZodUndefined:return ok(r);case z.ZodNull:return J4(r);case z.ZodArray:return P4(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return G4(t,r);case z.ZodIntersection:return D4(t,r);case z.ZodTuple:return sk(t,r);case z.ZodRecord:return Lh(t,r);case z.ZodLiteral:return U4(t,r);case z.ZodEnum:return q4(t);case z.ZodNativeEnum:return H4(t);case z.ZodNullable:return W4(t,r);case z.ZodOptional:return ek(t,r);case z.ZodMap:return V4(t,r);case z.ZodSet:return nk(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return rk(t,r);case z.ZodNaN:case z.ZodNever:return B4(r);case z.ZodEffects:return j4(t,r);case z.ZodAny:return St(r);case z.ZodUnknown:return ak(r);case z.ZodDefault:return L4(t,r);case z.ZodBranded:return Oh(t,r);case z.ZodReadonly:return ik(t,r);case z.ZodCatch:return M4(t,r);case z.ZodPipeline:return tk(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Me(t,e,r=!1){const n=e.seen.get(t);if(e.override){const i=e.override?.(t,e,n,r);if(i!==x4)return i}if(n&&!r){const i=ck(n,e);if(i!==void 0)return i}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=lk(t,t.typeName,e),a=typeof o=="function"?Me(o(),e):o;if(a&&uk(t,e,a),e.postProcess){const i=e.postProcess(a,t,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}const ck=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ph(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),St(e)):e.$refStrategy==="seen"?St(e):void 0}},uk=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),dk=(t,e)=>{const r=R4(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:Me(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??St(r)}),{}):void 0;const s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Me(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??St(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function pk(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function qh(t,e){var r,n,s;return qt(t)?ul(t,{target:pk(e?.target),io:(r=e?.pipeStrategy)!==null&&r!==void 0?r:"input"}):dk(t,{strictUnions:(n=e?.strictUnions)!==null&&n!==void 0?n:!0,pipeStrategy:(s=e?.pipeStrategy)!==null&&s!==void 0?s:"input"})}function zh(t){const e=zn(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");const n=xh(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Dh(t,e){const r=Ht(t,e);if(!r.success)throw r.error;return r.data}const fk=6e4;class Uh{constructor(e){this._options=e,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(wl,r=>{this._oncancel(r)}),this.setNotificationHandler(Sl,r=>{this._onprogress(r)}),this.setRequestHandler(kl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Tl,async(r,n)=>{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ne(ae.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler($l,async(r,n)=>{const s=async()=>{var o;const a=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(l.type==="response"||l.type==="error"){const c=l.message,u=c.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),l.type==="response")p(c);else{const h=c,d=new ne(h.error.code,h.error.message,h.error.data);p(d)}else{const h=l.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${u}`))}continue}await((o=this._transport)===null||o===void 0?void 0:o.send(l.message,{relatedRequestId:n.requestId}))}}const i=await this._taskStore.getTask(a,n.sessionId);if(!i)throw new ne(ae.InvalidParams,`Task not found: ${a}`);if(!fn(i.status))return await this._waitForTaskUpdate(a,n.signal),await s();if(fn(i.status)){const l=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...l,_meta:{...l._meta,[Cr]:{taskId:a}}}}return await s()};return await s()}),this.setRequestHandler(El,async(r,n)=>{var s;try{const{tasks:o,nextCursor:a}=await this._taskStore.listTasks((s=r.params)===null||s===void 0?void 0:s.cursor,n.sessionId);return{tasks:o,nextCursor:a,_meta:{}}}catch(o){throw new ne(ae.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(x9,async(r,n)=>{try{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ne(ae.InvalidParams,`Task not found: ${r.params.taskId}`);if(fn(s.status))throw new ne(ae.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ne(ae.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof ne?s:new ne(ae.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){const r=this._requestHandlerAbortControllers.get(e.params.requestId);r?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),ne.fromError(ae.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,s;this._transport=e;const o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};const a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=l=>{a?.(l),this._onerror(l)};const i=(s=this._transport)===null||s===void 0?void 0:s.onmessage;this._transport.onmessage=(l,c)=>{i?.(l,c),qs(l)||f9(l)?this._onresponse(l):yl(l)?this._onrequest(l,c):p9(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const n=ne.fromError(ae.ConnectionClosed,"Connection closed");this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);for(const s of r.values())s(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,r){var n,s,o,a,i,l;const c=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,u=this._transport,p=(a=(o=(s=e.params)===null||s===void 0?void 0:s._meta)===null||o===void 0?void 0:o[Cr])===null||a===void 0?void 0:a.taskId;if(c===void 0){const m={jsonrpc:"2.0",id:e.id,error:{code:ae.MethodNotFound,message:"Method not found"}};p&&this._taskMessageQueue?this._enqueueTaskMessage(p,{type:"error",message:m,timestamp:Date.now()},u?.sessionId).catch(y=>this._onerror(new Error(`Failed to enqueue error response: ${y}`))):u?.send(m).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)));return}const h=new AbortController;this._requestHandlerAbortControllers.set(e.id,h);const d=(i=e.params)===null||i===void 0?void 0:i.task,f=this._taskStore?this.requestTaskStore(e,u?.sessionId):void 0,w={signal:h.signal,sessionId:u?.sessionId,_meta:(l=e.params)===null||l===void 0?void 0:l._meta,sendNotification:async m=>{const y={relatedRequestId:e.id};p&&(y.relatedTask={taskId:p}),await this.notification(m,y)},sendRequest:async(m,y,_)=>{var g,b;const k={..._,relatedRequestId:e.id};p&&!k.relatedTask&&(k.relatedTask={taskId:p});const S=(b=(g=k.relatedTask)===null||g===void 0?void 0:g.taskId)!==null&&b!==void 0?b:p;return S&&f&&await f.updateTaskStatus(S,"input_required"),await this.request(m,y,k)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:p,taskStore:f,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{d&&this.assertTaskHandlerCapability(e.method)}).then(()=>c(e,w)).then(async m=>{if(h.signal.aborted)return;const y={result:m,jsonrpc:"2.0",id:e.id};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"response",message:y,timestamp:Date.now()},u?.sessionId):await u?.send(y)},async m=>{var y;if(h.signal.aborted)return;const _={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:ae.InternalError,message:(y=m.message)!==null&&y!==void 0?y:"Internal error",...m.data!==void 0&&{data:m.data}}};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"error",message:_,timestamp:Date.now()},u?.sessionId):await u?.send(_)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),a(l);return}o(n)}_onresponse(e){const r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),qs(e))n(e);else{const a=new ne(e.error.code,e.error.message,e.error.data);n(a)}return}const s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(qs(e)&&e.result&&typeof e.result=="object"){const a=e.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,r))}}if(o||this._progressHandlers.delete(r),qs(e))s(e);else{const a=ne.fromError(e.error.code,e.error.message,e.error.data);s(a)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}async*requestStream(e,r,n){var s,o,a,i;const{task:l}=n??{};if(!l){try{yield{type:"result",result:await this.request(e,r,n)}}catch(u){yield{type:"error",error:u instanceof ne?u:new ne(ae.InternalError,String(u))}}return}let c;try{const u=await this.request(e,Ln,n);if(u.task)c=u.task.taskId,yield{type:"taskCreated",task:u.task};else throw new ne(ae.InternalError,"Task creation did not return a task");for(;;){const p=await this.getTask({taskId:c},n);if(yield{type:"taskStatus",task:p},fn(p.status)){p.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)}:p.status==="failed"?yield{type:"error",error:new ne(ae.InternalError,`Task ${c} failed`)}:p.status==="cancelled"&&(yield{type:"error",error:new ne(ae.InternalError,`Task ${c} was cancelled`)});return}if(p.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)};return}const h=(a=(s=p.pollInterval)!==null&&s!==void 0?s:(o=this._options)===null||o===void 0?void 0:o.defaultTaskPollInterval)!==null&&a!==void 0?a:1e3;await new Promise(d=>setTimeout(d,h)),(i=n?.signal)===null||i===void 0||i.throwIfAborted()}}catch(u){yield{type:"error",error:u instanceof ne?u:new ne(ae.InternalError,String(u))}}}request(e,r,n){const{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{var p,h,d,f,w,m,y;const _=I=>{u(I)};if(!this._transport){_(new Error("Not connected"));return}if(((p=this._options)===null||p===void 0?void 0:p.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(I){_(I);return}(h=n?.signal)===null||h===void 0||h.throwIfAborted();const g=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),b.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:g}}),i&&(b.params={...b.params,task:i}),l&&(b.params={...b.params,_meta:{...((f=b.params)===null||f===void 0?void 0:f._meta)||{},[Cr]:l}});const k=I=>{var A;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(I)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(D=>this._onerror(new Error(`Failed to send cancellation: ${D}`)));const P=I instanceof ne?I:new ne(ae.RequestTimeout,String(I));u(P)};this._responseHandlers.set(g,I=>{var A;if(!(!((A=n?.signal)===null||A===void 0)&&A.aborted)){if(I instanceof Error)return u(I);try{const P=Ht(r,I.result);P.success?c(P.data):u(P.error)}catch(P){u(P)}}}),(w=n?.signal)===null||w===void 0||w.addEventListener("abort",()=>{var I;k((I=n?.signal)===null||I===void 0?void 0:I.reason)});const S=(m=n?.timeout)!==null&&m!==void 0?m:fk,T=()=>k(ne.fromError(ae.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(g,S,n?.maxTotalTimeout,T,(y=n?.resetTimeoutOnProgress)!==null&&y!==void 0?y:!1);const x=l?.taskId;if(x){const I=A=>{const P=this._responseHandlers.get(g);P?P(A):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,I),this._enqueueTaskMessage(x,{type:"request",message:b,timestamp:Date.now()}).catch(A=>{this._cleanupTimeout(g),u(A)})}else this._transport.send(b,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(I=>{this._cleanupTimeout(g),u(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Cl,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},xl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},I9,r)}async notification(e,r){var n,s,o,a,i;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const l=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(l){const h={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((s=e.params)===null||s===void 0?void 0:s._meta)||{},[Cr]:r.relatedTask}}};await this._enqueueTaskMessage(l,{type:"notification",message:h,timestamp:Date.now()});return}if(((a=(o=this._options)===null||o===void 0?void 0:o.debouncedNotificationMethods)!==null&&a!==void 0?a:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var h,d;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let f={...e,jsonrpc:"2.0"};r?.relatedTask&&(f={...f,params:{...f.params,_meta:{...((h=f.params)===null||h===void 0?void 0:h._meta)||{},[Cr]:r.relatedTask}}}),(d=this._transport)===null||d===void 0||d.send(f,r).catch(w=>this._onerror(w))});return}let p={...e,jsonrpc:"2.0"};r?.relatedTask&&(p={...p,params:{...p.params,_meta:{...((i=p.params)===null||i===void 0?void 0:i._meta)||{},[Cr]:r.relatedTask}}}),await this._transport.send(p,r)}setRequestHandler(e,r){const n=zh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{const a=Dh(e,s);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const n=zh(e);this._notificationHandlers.set(n,s=>{const o=Dh(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){var s;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=(s=this._options)===null||s===void 0?void 0:s.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,r);for(const s of n)if(s.type==="request"&&yl(s.message)){const o=s.message.id,a=this._requestResolvers.get(o);a?(a(new ne(ae.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){var n,s,o;let a=(s=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&s!==void 0?s:1e3;try{const i=await((o=this._taskStore)===null||o===void 0?void 0:o.getTask(e));i?.pollInterval&&(a=i.pollInterval)}catch{}return new Promise((i,l)=>{if(r.aborted){l(new ne(ae.InvalidRequest,"Request cancelled"));return}const c=setTimeout(i,a);r.addEventListener("abort",()=>{clearTimeout(c),l(new ne(ae.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{const o=await n.getTask(s,r);if(!o)throw new ne(ae.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,a)=>{await n.storeTaskResult(s,o,a,r);const i=await n.getTask(s,r);if(i){const l=Ma.parse({method:"notifications/tasks/status",params:i});await this.notification(l),fn(i.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,a)=>{const i=await n.getTask(s,r);if(!i)throw new ne(ae.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(fn(i.status))throw new ne(ae.InvalidParams,`Cannot update task "${s}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,a,r);const l=await n.getTask(s,r);if(l){const c=Ma.parse({method:"notifications/tasks/status",params:l});await this.notification(c),fn(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}function Zh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Fh(t,e){const r={...t};for(const n in e){const s=n,o=e[s];if(o===void 0)continue;const a=r[s];Zh(a)&&Zh(o)?r[s]={...a,...o}:r[s]=o}return r}var Za={exports:{}},Gl={},Vh;function hk(){return Vh||(Vh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(P,D){return{validate:P,compare:D}}t.fullFormats={date:e(o,a),time:e(l(!0),c),"date-time":e(h(!0),d),"iso-time":e(l(),u),"iso-date-time":e(h(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:A,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:g,int32:{type:"number",validate:S},int64:{type:"number",validate:T},float:{type:"number",validate:x},double:{type:"number",validate:x},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":e(/^\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,f),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},t.formatNames=Object.keys(t.fullFormats);function r(P){return P%4===0&&(P%100!==0||P%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(P){const D=n.exec(P);if(!D)return!1;const U=+D[1],V=+D[2],se=+D[3];return V>=1&&V<=12&&se>=1&&se<=(V===2&&r(U)?29:s[V])}function a(P,D){if(P&&D)return P>D?1:P<D?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(P){return function(U){const V=i.exec(U);if(!V)return!1;const se=+V[1],fe=+V[2],de=+V[3],re=V[4],_e=V[5]==="-"?-1:1,H=+(V[6]||0),O=+(V[7]||0);if(H>23||O>59||P&&!re)return!1;if(se<=23&&fe<=59&&de<60)return!0;const F=fe-O*_e,q=se-H*_e-(F<0?1:0);return(q===23||q===-1)&&(F===59||F===-1)&&de<61}}function c(P,D){if(!(P&&D))return;const U=new Date("2020-01-01T"+P).valueOf(),V=new Date("2020-01-01T"+D).valueOf();if(U&&V)return U-V}function u(P,D){if(!(P&&D))return;const U=i.exec(P),V=i.exec(D);if(U&&V)return P=U[1]+U[2]+U[3],D=V[1]+V[2]+V[3],P>D?1:P<D?-1:0}const p=/t|\s/i;function h(P){const D=l(P);return function(V){const se=V.split(p);return se.length===2&&o(se[0])&&D(se[1])}}function d(P,D){if(!(P&&D))return;const U=new Date(P).valueOf(),V=new Date(D).valueOf();if(U&&V)return U-V}function f(P,D){if(!(P&&D))return;const[U,V]=P.split(p),[se,fe]=D.split(p),de=a(U,se);if(de!==void 0)return de||c(V,fe)}const w=/\/|:/,m=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function y(P){return w.test(P)&&m.test(P)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(P){return _.lastIndex=0,_.test(P)}const b=-2147483648,k=2**31-1;function S(P){return Number.isInteger(P)&&P<=k&&P>=b}function T(P){return Number.isInteger(P)}function x(){return!0}const I=/[^\\]\\Z/;function A(P){if(I.test(P))return!1;try{return new RegExp(P),!0}catch{return!1}}})(Gl)),Gl}var Wl={},Hh;function mk(){return Hh||(Hh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=Ep(),r=$e(),n=r.operators,s={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}},o={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${s[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${s[i].okStr}, limit: ${l}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:o,code(i){const{gen:l,data:c,schemaCode:u,keyword:p,it:h}=i,{opts:d,self:f}=h;if(!d.validateFormats)return;const w=new e.KeywordCxt(h,f.RULES.all.format.definition,"format");w.$data?m():y();function m(){const g=l.scopeValue("formats",{ref:f.formats,code:d.code.formats}),b=l.const("fmt",(0,r._)`${g}[${w.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,_(b)))}function y(){const g=w.schema,b=f.formats[g];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${p}": format "${g}" does not define "compare" function`);const k=l.scopeValue("formats",{key:g,ref:b,code:d.code.formats?(0,r._)`${d.code.formats}${(0,r.getProperty)(g)}`:void 0});i.fail$data(_(k))}function _(g){return(0,r._)`${g}.compare(${c}, ${u}) ${s[p].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(t.formatLimitDefinition),i);t.default=a})(Wl)),Wl}var Bh;function gk(){return Bh||(Bh=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const r=hk(),n=mk(),s=$e(),o=new s.Name("fullFormats"),a=new s.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,o),c;const[p,h]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,o],d=u.formats||r.formatNames;return l(c,d,p,h),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const h=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!h)throw new Error(`Unknown format "${c}"`);return h};function l(c,u,p,h){var d,f;(d=(f=c.opts.code).formats)!==null&&d!==void 0||(f.formats=(0,s._)`require("ajv-formats/dist/formats").${h}`);for(const w of u)c.addFormat(w,p[w])}t.exports=e=i,Object.defineProperty(e,"__esModule",{value:!0}),e.default=i})(Za,Za.exports)),Za.exports}var vk=gk();const _k=tn(vk);function yk(){const t=new xp.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return _k(t),t}class Jh{constructor(e){this._ajv=e??yk()}getValidator(e){var r;const n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return s=>n(s)?{valid:!0,data:s,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}class wk{constructor(e){this._client=e}async*callToolStream(e,r=qn,n){var s;const o=this._client,a={...n,task:(s=n?.task)!==null&&s!==void 0?s:o.isToolTask(e.name)?{}:void 0},i=o.requestStream({method:"tools/call",params:e},r,a),l=o.getToolOutputValidator(e.name);for await(const c of i){if(c.type==="result"&&l){const u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new ne(ae.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{const p=l(u.structuredContent);if(!p.valid){yield{type:"error",error:new ne(ae.InvalidParams,`Structured content does not match the tool's output schema: ${p.errorMessage}`)};return}}catch(p){if(p instanceof ne){yield{type:"error",error:p};return}yield{type:"error",error:new ne(ae.InvalidParams,`Failed to validate structured content: ${p instanceof Error?p.message:String(p)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}}function Gh(t,e,r){var n;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!(!((n=t.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break}}function Wh(t,e,r){var n,s;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!(!((n=t.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!(!((s=t.elicitation)===null||s===void 0)&&s.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break}}function Fa(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){const r=e,n=t.properties;for(const s of Object.keys(n)){const o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&Fa(o,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)Fa(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)Fa(r,e)}}function bk(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};const e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}class Bs extends Uh{constructor(e,r){var n,s;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(s=r?.jsonSchemaValidator)!==null&&s!==void 0?s:new Jh}get experimental(){return this._experimental||(this._experimental={tasks:new wk(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fh(this._capabilities,e)}setRequestHandler(e,r){var n,s,o;const a=zn(e),i=a?.method;if(!i)throw new Error("Schema is missing a method literal");let l;if(qt(i)){const u=i,p=(n=u._zod)===null||n===void 0?void 0:n.def;l=(s=p?.value)!==null&&s!==void 0?s:u.value}else{const u=i,p=u._def;l=(o=p?.value)!==null&&o!==void 0?o:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");const c=l;if(c==="elicitation/create"){const u=async(p,h)=>{var d,f,w;const m=Ht(Ul,p);if(!m.success){const I=m.error instanceof Error?m.error.message:String(m.error);throw new ne(ae.InvalidParams,`Invalid elicitation request: ${I}`)}const{params:y}=m.data,_=(d=y.mode)!==null&&d!==void 0?d:"form",{supportsFormMode:g,supportsUrlMode:b}=bk(this._capabilities.elicitation);if(_==="form"&&!g)throw new ne(ae.InvalidParams,"Client does not support form-mode elicitation requests");if(_==="url"&&!b)throw new ne(ae.InvalidParams,"Client does not support URL-mode elicitation requests");const k=await Promise.resolve(r(p,h));if(y.task){const I=Ht(Ln,k);if(!I.success){const A=I.error instanceof Error?I.error.message:String(I.error);throw new ne(ae.InvalidParams,`Invalid task creation result: ${A}`)}return I.data}const S=Ht(Fs,k);if(!S.success){const I=S.error instanceof Error?S.error.message:String(S.error);throw new ne(ae.InvalidParams,`Invalid elicitation result: ${I}`)}const T=S.data,x=_==="form"?y.requestedSchema:void 0;if(_==="form"&&T.action==="accept"&&T.content&&x&&!((w=(f=this._capabilities.elicitation)===null||f===void 0?void 0:f.form)===null||w===void 0)&&w.applyDefaults)try{Fa(x,T.content)}catch{}return T};return super.setRequestHandler(e,u)}if(c==="sampling/createMessage"){const u=async(p,h)=>{const d=Ht(Dl,p);if(!d.success){const y=d.error instanceof Error?d.error.message:String(d.error);throw new ne(ae.InvalidParams,`Invalid sampling request: ${y}`)}const{params:f}=d.data,w=await Promise.resolve(r(p,h));if(f.task){const y=Ht(Ln,w);if(!y.success){const _=y.error instanceof Error?y.error.message:String(y.error);throw new ne(ae.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}const m=Ht(Da,w);if(!m.success){const y=m.error instanceof Error?m.error.message:String(m.error);throw new ne(ae.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(e,u)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:js,capabilities:this._capabilities,clientInfo:this._clientInfo}},sh,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Wf.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,s,o,a;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);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 ${e})`);break}}assertTaskCapability(e){var r,n;Gh((n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,e,"Server")}assertTaskHandlerCapability(e){var r;this._capabilities&&Wh((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Zr,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Th,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Zr,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},vh,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},gh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},ch,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},uh,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},dh,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Zr,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Zr,r)}async callTool(e,r=qn,n){if(this.isToolTaskRequired(e.name))throw new ne(ae.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const s=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new ne(ae.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const a=o(s.structuredContent);if(!a.valid)throw new ne(ae.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ne?a:new ne(ae.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return s}isToolTask(e){var r,n,s,o;return!((o=(s=(n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests)===null||s===void 0?void 0:s.tools)===null||o===void 0)&&o.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){var r;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const n of e){if(n.outputSchema){const o=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,o)}const s=(r=n.execution)===null||r===void 0?void 0:r.taskSupport;(s==="required"||s==="optional")&&this._cachedKnownTaskTools.add(n.name),s==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const n=await this.request({method:"tools/list",params:e},wh,r);return this.cacheToolMetadata(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Kh extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Kl(t){}function Yh(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=Kl,onError:r=Kl,onRetry:n=Kl,onComment:s}=t;let o="",a=!0,i,l="",c="";function u(w){const m=a?w.replace(/^\xEF\xBB\xBF/,""):w,[y,_]=kk(`${o}${m}`);for(const g of y)p(g);o=_,a=!1}function p(w){if(w===""){d();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}const m=w.indexOf(":");if(m!==-1){const y=w.slice(0,m),_=w[m+1]===" "?2:1,g=w.slice(m+_);h(y,g,w);return}h(w,"",w)}function h(w,m,y){switch(w){case"event":c=m;break;case"data":l=`${l}${m}
40
- `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):r(new Kh(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:y}));break;default:r(new Kh(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:m,line:y}));break}}function d(){l.length>0&&e({id:i,event:c||void 0,data:l.endsWith(`
39
+ ]`;continue}s+=n[l],n[l]==="\\"?o=!0:a&&n[l]==="]"?a=!1:!a&&n[l]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Nh(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===z.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??St(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===z.ZodString&&t.keyType._def.checks?.length){const{type:n,...s}=Ah(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===z.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...s}=Ph(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function V4(t,e){if(e.mapStrategy==="record")return Nh(t,e);const r=Me(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||St(e),n=Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||St(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function H4(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function B4(t){return t.target==="openAi"?void 0:{not:St({...t,currentPath:[...t.currentPath,"not"]})}}function J4(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ua={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function G4(t,e){if(e.target==="openApi3")return Lh(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ua&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Ua[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return Lh(t,e)}const Lh=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Me(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function W4(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Ua[t.innerType._def.typeName],nullable:!0}:{type:[Ua[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=Me(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=Me(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function K4(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Ih(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?qe(r,"minimum",n.value,n.message,e):qe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),qe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?qe(r,"maximum",n.value,n.message,e):qe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),qe(r,"maximum",n.value,n.message,e));break;case"multipleOf":qe(r,"multipleOf",n.value,n.message,e);break}return r}function Y4(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(const i in o){let l=o[i];if(l===void 0||l._def===void 0)continue;let c=X4(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Me(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,c||s.push(i))}s.length&&(n.required=s);const a=Q4(t,e);return a!==void 0&&(n.additionalProperties=a),n}function Q4(t,e){if(t.catchall._def.typeName!=="ZodNever")return Me(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function X4(t){try{return t.isOptional()}catch{return!0}}const ek=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Me(t.innerType._def,e);const r=Me(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:St(e)},r]}:St(e)},tk=(t,e)=>{if(e.pipeStrategy==="input")return Me(t.in._def,e);if(e.pipeStrategy==="output")return Me(t.out._def,e);const r=Me(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Me(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function rk(t,e){return Me(t.type._def,e)}function nk(t,e){const n={type:"array",uniqueItems:!0,items:Me(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&qe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&qe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function sk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Me(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Me(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Me(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function ok(t){return{not:St(t)}}function ak(t){return St(t)}const ik=(t,e)=>Me(t.innerType._def,e),lk=(t,e,r)=>{switch(e){case z.ZodString:return Ah(t,r);case z.ZodNumber:return K4(t,r);case z.ZodObject:return Y4(t,r);case z.ZodBigInt:return O4(t,r);case z.ZodBoolean:return A4();case z.ZodDate:return Oh(t,r);case z.ZodUndefined:return ok(r);case z.ZodNull:return J4(r);case z.ZodArray:return P4(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return G4(t,r);case z.ZodIntersection:return D4(t,r);case z.ZodTuple:return sk(t,r);case z.ZodRecord:return Nh(t,r);case z.ZodLiteral:return U4(t,r);case z.ZodEnum:return q4(t);case z.ZodNativeEnum:return H4(t);case z.ZodNullable:return W4(t,r);case z.ZodOptional:return ek(t,r);case z.ZodMap:return V4(t,r);case z.ZodSet:return nk(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return rk(t,r);case z.ZodNaN:case z.ZodNever:return B4(r);case z.ZodEffects:return j4(t,r);case z.ZodAny:return St(r);case z.ZodUnknown:return ak(r);case z.ZodDefault:return L4(t,r);case z.ZodBranded:return Ph(t,r);case z.ZodReadonly:return ik(t,r);case z.ZodCatch:return M4(t,r);case z.ZodPipeline:return tk(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Me(t,e,r=!1){const n=e.seen.get(t);if(e.override){const i=e.override?.(t,e,n,r);if(i!==x4)return i}if(n&&!r){const i=ck(n,e);if(i!==void 0)return i}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=lk(t,t.typeName,e),a=typeof o=="function"?Me(o(),e):o;if(a&&uk(t,e,a),e.postProcess){const i=e.postProcess(a,t,e);return s.jsonSchema=a,i}return s.jsonSchema=a,a}const ck=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Rh(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),St(e)):e.$refStrategy==="seen"?St(e):void 0}},uk=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),dk=(t,e)=>{const r=R4(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:Me(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??St(r)}),{}):void 0;const s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Me(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??St(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function pk(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function jh(t,e){var r,n,s;return qt(t)?ul(t,{target:pk(e?.target),io:(r=e?.pipeStrategy)!==null&&r!==void 0?r:"input"}):dk(t,{strictUnions:(n=e?.strictUnions)!==null&&n!==void 0?n:!0,pipeStrategy:(s=e?.pipeStrategy)!==null&&s!==void 0?s:"input"})}function qh(t){const e=zn(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Eh(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zh(t,e){const r=Ht(t,e);if(!r.success)throw r.error;return r.data}const fk=6e4;class Dh{constructor(e){this._options=e,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(wl,r=>{this._oncancel(r)}),this.setNotificationHandler(Sl,r=>{this._onprogress(r)}),this.setRequestHandler(kl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Tl,async(r,n)=>{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ne(ae.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler($l,async(r,n)=>{const s=async()=>{var o;const a=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(l.type==="response"||l.type==="error"){const c=l.message,u=c.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),l.type==="response")p(c);else{const h=c,d=new ne(h.error.code,h.error.message,h.error.data);p(d)}else{const h=l.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${u}`))}continue}await((o=this._transport)===null||o===void 0?void 0:o.send(l.message,{relatedRequestId:n.requestId}))}}const i=await this._taskStore.getTask(a,n.sessionId);if(!i)throw new ne(ae.InvalidParams,`Task not found: ${a}`);if(!fn(i.status))return await this._waitForTaskUpdate(a,n.signal),await s();if(fn(i.status)){const l=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...l,_meta:{...l._meta,[Cr]:{taskId:a}}}}return await s()};return await s()}),this.setRequestHandler(El,async(r,n)=>{var s;try{const{tasks:o,nextCursor:a}=await this._taskStore.listTasks((s=r.params)===null||s===void 0?void 0:s.cursor,n.sessionId);return{tasks:o,nextCursor:a,_meta:{}}}catch(o){throw new ne(ae.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(x9,async(r,n)=>{try{const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ne(ae.InvalidParams,`Task not found: ${r.params.taskId}`);if(fn(s.status))throw new ne(ae.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ne(ae.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof ne?s:new ne(ae.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){const r=this._requestHandlerAbortControllers.get(e.params.requestId);r?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),ne.fromError(ae.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,s;this._transport=e;const o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};const a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=l=>{a?.(l),this._onerror(l)};const i=(s=this._transport)===null||s===void 0?void 0:s.onmessage;this._transport.onmessage=(l,c)=>{i?.(l,c),qs(l)||f9(l)?this._onresponse(l):yl(l)?this._onrequest(l,c):p9(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const n=ne.fromError(ae.ConnectionClosed,"Connection closed");this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);for(const s of r.values())s(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,r){var n,s,o,a,i,l;const c=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,u=this._transport,p=(a=(o=(s=e.params)===null||s===void 0?void 0:s._meta)===null||o===void 0?void 0:o[Cr])===null||a===void 0?void 0:a.taskId;if(c===void 0){const m={jsonrpc:"2.0",id:e.id,error:{code:ae.MethodNotFound,message:"Method not found"}};p&&this._taskMessageQueue?this._enqueueTaskMessage(p,{type:"error",message:m,timestamp:Date.now()},u?.sessionId).catch(y=>this._onerror(new Error(`Failed to enqueue error response: ${y}`))):u?.send(m).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)));return}const h=new AbortController;this._requestHandlerAbortControllers.set(e.id,h);const d=(i=e.params)===null||i===void 0?void 0:i.task,f=this._taskStore?this.requestTaskStore(e,u?.sessionId):void 0,w={signal:h.signal,sessionId:u?.sessionId,_meta:(l=e.params)===null||l===void 0?void 0:l._meta,sendNotification:async m=>{const y={relatedRequestId:e.id};p&&(y.relatedTask={taskId:p}),await this.notification(m,y)},sendRequest:async(m,y,_)=>{var g,b;const k={..._,relatedRequestId:e.id};p&&!k.relatedTask&&(k.relatedTask={taskId:p});const S=(b=(g=k.relatedTask)===null||g===void 0?void 0:g.taskId)!==null&&b!==void 0?b:p;return S&&f&&await f.updateTaskStatus(S,"input_required"),await this.request(m,y,k)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:p,taskStore:f,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{d&&this.assertTaskHandlerCapability(e.method)}).then(()=>c(e,w)).then(async m=>{if(h.signal.aborted)return;const y={result:m,jsonrpc:"2.0",id:e.id};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"response",message:y,timestamp:Date.now()},u?.sessionId):await u?.send(y)},async m=>{var y;if(h.signal.aborted)return;const _={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(m.code)?m.code:ae.InternalError,message:(y=m.message)!==null&&y!==void 0?y:"Internal error",...m.data!==void 0&&{data:m.data}}};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"error",message:_,timestamp:Date.now()},u?.sessionId):await u?.send(_)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const a=this._responseHandlers.get(s),i=this._timeoutInfo.get(s);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),a(l);return}o(n)}_onresponse(e){const r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),qs(e))n(e);else{const a=new ne(e.error.code,e.error.message,e.error.data);n(a)}return}const s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(qs(e)&&e.result&&typeof e.result=="object"){const a=e.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,r))}}if(o||this._progressHandlers.delete(r),qs(e))s(e);else{const a=ne.fromError(e.error.code,e.error.message,e.error.data);s(a)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}async*requestStream(e,r,n){var s,o,a,i;const{task:l}=n??{};if(!l){try{yield{type:"result",result:await this.request(e,r,n)}}catch(u){yield{type:"error",error:u instanceof ne?u:new ne(ae.InternalError,String(u))}}return}let c;try{const u=await this.request(e,Ln,n);if(u.task)c=u.task.taskId,yield{type:"taskCreated",task:u.task};else throw new ne(ae.InternalError,"Task creation did not return a task");for(;;){const p=await this.getTask({taskId:c},n);if(yield{type:"taskStatus",task:p},fn(p.status)){p.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)}:p.status==="failed"?yield{type:"error",error:new ne(ae.InternalError,`Task ${c} failed`)}:p.status==="cancelled"&&(yield{type:"error",error:new ne(ae.InternalError,`Task ${c} was cancelled`)});return}if(p.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)};return}const h=(a=(s=p.pollInterval)!==null&&s!==void 0?s:(o=this._options)===null||o===void 0?void 0:o.defaultTaskPollInterval)!==null&&a!==void 0?a:1e3;await new Promise(d=>setTimeout(d,h)),(i=n?.signal)===null||i===void 0||i.throwIfAborted()}}catch(u){yield{type:"error",error:u instanceof ne?u:new ne(ae.InternalError,String(u))}}}request(e,r,n){const{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{var p,h,d,f,w,m,y;const _=I=>{u(I)};if(!this._transport){_(new Error("Not connected"));return}if(((p=this._options)===null||p===void 0?void 0:p.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(I){_(I);return}(h=n?.signal)===null||h===void 0||h.throwIfAborted();const g=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),b.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:g}}),i&&(b.params={...b.params,task:i}),l&&(b.params={...b.params,_meta:{...((f=b.params)===null||f===void 0?void 0:f._meta)||{},[Cr]:l}});const k=I=>{var A;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(A=this._transport)===null||A===void 0||A.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(I)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(D=>this._onerror(new Error(`Failed to send cancellation: ${D}`)));const P=I instanceof ne?I:new ne(ae.RequestTimeout,String(I));u(P)};this._responseHandlers.set(g,I=>{var A;if(!(!((A=n?.signal)===null||A===void 0)&&A.aborted)){if(I instanceof Error)return u(I);try{const P=Ht(r,I.result);P.success?c(P.data):u(P.error)}catch(P){u(P)}}}),(w=n?.signal)===null||w===void 0||w.addEventListener("abort",()=>{var I;k((I=n?.signal)===null||I===void 0?void 0:I.reason)});const S=(m=n?.timeout)!==null&&m!==void 0?m:fk,T=()=>k(ne.fromError(ae.RequestTimeout,"Request timed out",{timeout:S}));this._setupTimeout(g,S,n?.maxTotalTimeout,T,(y=n?.resetTimeoutOnProgress)!==null&&y!==void 0?y:!1);const x=l?.taskId;if(x){const I=A=>{const P=this._responseHandlers.get(g);P?P(A):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,I),this._enqueueTaskMessage(x,{type:"request",message:b,timestamp:Date.now()}).catch(A=>{this._cleanupTimeout(g),u(A)})}else this._transport.send(b,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(I=>{this._cleanupTimeout(g),u(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Cl,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},xl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},I9,r)}async notification(e,r){var n,s,o,a,i;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const l=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(l){const h={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((s=e.params)===null||s===void 0?void 0:s._meta)||{},[Cr]:r.relatedTask}}};await this._enqueueTaskMessage(l,{type:"notification",message:h,timestamp:Date.now()});return}if(((a=(o=this._options)===null||o===void 0?void 0:o.debouncedNotificationMethods)!==null&&a!==void 0?a:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var h,d;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let f={...e,jsonrpc:"2.0"};r?.relatedTask&&(f={...f,params:{...f.params,_meta:{...((h=f.params)===null||h===void 0?void 0:h._meta)||{},[Cr]:r.relatedTask}}}),(d=this._transport)===null||d===void 0||d.send(f,r).catch(w=>this._onerror(w))});return}let p={...e,jsonrpc:"2.0"};r?.relatedTask&&(p={...p,params:{...p.params,_meta:{...((i=p.params)===null||i===void 0?void 0:i._meta)||{},[Cr]:r.relatedTask}}}),await this._transport.send(p,r)}setRequestHandler(e,r){const n=qh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{const a=zh(e,s);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){const n=qh(e);this._notificationHandlers.set(n,s=>{const o=zh(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){var s;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=(s=this._options)===null||s===void 0?void 0:s.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,r);for(const s of n)if(s.type==="request"&&yl(s.message)){const o=s.message.id,a=this._requestResolvers.get(o);a?(a(new ne(ae.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){var n,s,o;let a=(s=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&s!==void 0?s:1e3;try{const i=await((o=this._taskStore)===null||o===void 0?void 0:o.getTask(e));i?.pollInterval&&(a=i.pollInterval)}catch{}return new Promise((i,l)=>{if(r.aborted){l(new ne(ae.InvalidRequest,"Request cancelled"));return}const c=setTimeout(i,a);r.addEventListener("abort",()=>{clearTimeout(c),l(new ne(ae.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{const o=await n.getTask(s,r);if(!o)throw new ne(ae.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,a)=>{await n.storeTaskResult(s,o,a,r);const i=await n.getTask(s,r);if(i){const l=Ma.parse({method:"notifications/tasks/status",params:i});await this.notification(l),fn(i.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,a)=>{const i=await n.getTask(s,r);if(!i)throw new ne(ae.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(fn(i.status))throw new ne(ae.InvalidParams,`Cannot update task "${s}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,a,r);const l=await n.getTask(s,r);if(l){const c=Ma.parse({method:"notifications/tasks/status",params:l});await this.notification(c),fn(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}function Uh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Zh(t,e){const r={...t};for(const n in e){const s=n,o=e[s];if(o===void 0)continue;const a=r[s];Uh(a)&&Uh(o)?r[s]={...a,...o}:r[s]=o}return r}var Za={exports:{}},Gl={},Fh;function hk(){return Fh||(Fh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(P,D){return{validate:P,compare:D}}t.fullFormats={date:e(o,a),time:e(l(!0),c),"date-time":e(h(!0),d),"iso-time":e(l(),u),"iso-date-time":e(h(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:A,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:g,int32:{type:"number",validate:S},int64:{type:"number",validate:T},float:{type:"number",validate:x},double:{type:"number",validate:x},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":e(/^\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,f),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},t.formatNames=Object.keys(t.fullFormats);function r(P){return P%4===0&&(P%100!==0||P%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(P){const D=n.exec(P);if(!D)return!1;const U=+D[1],V=+D[2],se=+D[3];return V>=1&&V<=12&&se>=1&&se<=(V===2&&r(U)?29:s[V])}function a(P,D){if(P&&D)return P>D?1:P<D?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(P){return function(U){const V=i.exec(U);if(!V)return!1;const se=+V[1],fe=+V[2],de=+V[3],re=V[4],_e=V[5]==="-"?-1:1,H=+(V[6]||0),O=+(V[7]||0);if(H>23||O>59||P&&!re)return!1;if(se<=23&&fe<=59&&de<60)return!0;const F=fe-O*_e,q=se-H*_e-(F<0?1:0);return(q===23||q===-1)&&(F===59||F===-1)&&de<61}}function c(P,D){if(!(P&&D))return;const U=new Date("2020-01-01T"+P).valueOf(),V=new Date("2020-01-01T"+D).valueOf();if(U&&V)return U-V}function u(P,D){if(!(P&&D))return;const U=i.exec(P),V=i.exec(D);if(U&&V)return P=U[1]+U[2]+U[3],D=V[1]+V[2]+V[3],P>D?1:P<D?-1:0}const p=/t|\s/i;function h(P){const D=l(P);return function(V){const se=V.split(p);return se.length===2&&o(se[0])&&D(se[1])}}function d(P,D){if(!(P&&D))return;const U=new Date(P).valueOf(),V=new Date(D).valueOf();if(U&&V)return U-V}function f(P,D){if(!(P&&D))return;const[U,V]=P.split(p),[se,fe]=D.split(p),de=a(U,se);if(de!==void 0)return de||c(V,fe)}const w=/\/|:/,m=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function y(P){return w.test(P)&&m.test(P)}const _=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(P){return _.lastIndex=0,_.test(P)}const b=-2147483648,k=2**31-1;function S(P){return Number.isInteger(P)&&P<=k&&P>=b}function T(P){return Number.isInteger(P)}function x(){return!0}const I=/[^\\]\\Z/;function A(P){if(I.test(P))return!1;try{return new RegExp(P),!0}catch{return!1}}})(Gl)),Gl}var Wl={},Vh;function mk(){return Vh||(Vh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=$p(),r=$e(),n=r.operators,s={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}},o={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${s[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${s[i].okStr}, limit: ${l}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:o,code(i){const{gen:l,data:c,schemaCode:u,keyword:p,it:h}=i,{opts:d,self:f}=h;if(!d.validateFormats)return;const w=new e.KeywordCxt(h,f.RULES.all.format.definition,"format");w.$data?m():y();function m(){const g=l.scopeValue("formats",{ref:f.formats,code:d.code.formats}),b=l.const("fmt",(0,r._)`${g}[${w.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${b} != "object"`,(0,r._)`${b} instanceof RegExp`,(0,r._)`typeof ${b}.compare != "function"`,_(b)))}function y(){const g=w.schema,b=f.formats[g];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${p}": format "${g}" does not define "compare" function`);const k=l.scopeValue("formats",{key:g,ref:b,code:d.code.formats?(0,r._)`${d.code.formats}${(0,r.getProperty)(g)}`:void 0});i.fail$data(_(k))}function _(g){return(0,r._)`${g}.compare(${c}, ${u}) ${s[p].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(t.formatLimitDefinition),i);t.default=a})(Wl)),Wl}var Hh;function gk(){return Hh||(Hh=1,(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const r=hk(),n=mk(),s=$e(),o=new s.Name("fullFormats"),a=new s.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,o),c;const[p,h]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,o],d=u.formats||r.formatNames;return l(c,d,p,h),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const h=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!h)throw new Error(`Unknown format "${c}"`);return h};function l(c,u,p,h){var d,f;(d=(f=c.opts.code).formats)!==null&&d!==void 0||(f.formats=(0,s._)`require("ajv-formats/dist/formats").${h}`);for(const w of u)c.addFormat(w,p[w])}t.exports=e=i,Object.defineProperty(e,"__esModule",{value:!0}),e.default=i})(Za,Za.exports)),Za.exports}var vk=gk();const _k=tn(vk);function yk(){const t=new Ep.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return _k(t),t}class Bh{constructor(e){this._ajv=e??yk()}getValidator(e){var r;const n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return s=>n(s)?{valid:!0,data:s,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}class wk{constructor(e){this._client=e}async*callToolStream(e,r=qn,n){var s;const o=this._client,a={...n,task:(s=n?.task)!==null&&s!==void 0?s:o.isToolTask(e.name)?{}:void 0},i=o.requestStream({method:"tools/call",params:e},r,a),l=o.getToolOutputValidator(e.name);for await(const c of i){if(c.type==="result"&&l){const u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new ne(ae.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{const p=l(u.structuredContent);if(!p.valid){yield{type:"error",error:new ne(ae.InvalidParams,`Structured content does not match the tool's output schema: ${p.errorMessage}`)};return}}catch(p){if(p instanceof ne){yield{type:"error",error:p};return}yield{type:"error",error:new ne(ae.InvalidParams,`Failed to validate structured content: ${p instanceof Error?p.message:String(p)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}}function Jh(t,e,r){var n;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!(!((n=t.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break}}function Gh(t,e,r){var n,s;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!(!((n=t.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!(!((s=t.elicitation)===null||s===void 0)&&s.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break}}function Fa(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){const r=e,n=t.properties;for(const s of Object.keys(n)){const o=n[s];r[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[s]=o.default),r[s]!==void 0&&Fa(o,r[s])}}if(Array.isArray(t.anyOf))for(const r of t.anyOf)Fa(r,e);if(Array.isArray(t.oneOf))for(const r of t.oneOf)Fa(r,e)}}function bk(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};const e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}class Bs extends Dh{constructor(e,r){var n,s;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(s=r?.jsonSchemaValidator)!==null&&s!==void 0?s:new Bh}get experimental(){return this._experimental||(this._experimental={tasks:new wk(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zh(this._capabilities,e)}setRequestHandler(e,r){var n,s,o;const a=zn(e),i=a?.method;if(!i)throw new Error("Schema is missing a method literal");let l;if(qt(i)){const u=i,p=(n=u._zod)===null||n===void 0?void 0:n.def;l=(s=p?.value)!==null&&s!==void 0?s:u.value}else{const u=i,p=u._def;l=(o=p?.value)!==null&&o!==void 0?o:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");const c=l;if(c==="elicitation/create"){const u=async(p,h)=>{var d,f,w;const m=Ht(Ul,p);if(!m.success){const I=m.error instanceof Error?m.error.message:String(m.error);throw new ne(ae.InvalidParams,`Invalid elicitation request: ${I}`)}const{params:y}=m.data,_=(d=y.mode)!==null&&d!==void 0?d:"form",{supportsFormMode:g,supportsUrlMode:b}=bk(this._capabilities.elicitation);if(_==="form"&&!g)throw new ne(ae.InvalidParams,"Client does not support form-mode elicitation requests");if(_==="url"&&!b)throw new ne(ae.InvalidParams,"Client does not support URL-mode elicitation requests");const k=await Promise.resolve(r(p,h));if(y.task){const I=Ht(Ln,k);if(!I.success){const A=I.error instanceof Error?I.error.message:String(I.error);throw new ne(ae.InvalidParams,`Invalid task creation result: ${A}`)}return I.data}const S=Ht(Fs,k);if(!S.success){const I=S.error instanceof Error?S.error.message:String(S.error);throw new ne(ae.InvalidParams,`Invalid elicitation result: ${I}`)}const T=S.data,x=_==="form"?y.requestedSchema:void 0;if(_==="form"&&T.action==="accept"&&T.content&&x&&!((w=(f=this._capabilities.elicitation)===null||f===void 0?void 0:f.form)===null||w===void 0)&&w.applyDefaults)try{Fa(x,T.content)}catch{}return T};return super.setRequestHandler(e,u)}if(c==="sampling/createMessage"){const u=async(p,h)=>{const d=Ht(Dl,p);if(!d.success){const y=d.error instanceof Error?d.error.message:String(d.error);throw new ne(ae.InvalidParams,`Invalid sampling request: ${y}`)}const{params:f}=d.data,w=await Promise.resolve(r(p,h));if(f.task){const y=Ht(Ln,w);if(!y.success){const _=y.error instanceof Error?y.error.message:String(y.error);throw new ne(ae.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}const m=Ht(Da,w);if(!m.success){const y=m.error instanceof Error?m.error.message:String(m.error);throw new ne(ae.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(e,u)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:js,capabilities:this._capabilities,clientInfo:this._clientInfo}},nh,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Gf.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,s,o,a;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);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 ${e})`);break}}assertTaskCapability(e){var r,n;Jh((n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,e,"Server")}assertTaskHandlerCapability(e){var r;this._capabilities&&Gh((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Zr,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Sh,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Zr,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},gh,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},mh,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},lh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ch,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},uh,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Zr,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Zr,r)}async callTool(e,r=qn,n){if(this.isToolTaskRequired(e.name))throw new ne(ae.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const s=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new ne(ae.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const a=o(s.structuredContent);if(!a.valid)throw new ne(ae.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ne?a:new ne(ae.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return s}isToolTask(e){var r,n,s,o;return!((o=(s=(n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests)===null||s===void 0?void 0:s.tools)===null||o===void 0)&&o.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){var r;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const n of e){if(n.outputSchema){const o=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,o)}const s=(r=n.execution)===null||r===void 0?void 0:r.taskSupport;(s==="required"||s==="optional")&&this._cachedKnownTaskTools.add(n.name),s==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const n=await this.request({method:"tools/list",params:e},yh,r);return this.cacheToolMetadata(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Wh extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Kl(t){}function Kh(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=Kl,onError:r=Kl,onRetry:n=Kl,onComment:s}=t;let o="",a=!0,i,l="",c="";function u(w){const m=a?w.replace(/^\xEF\xBB\xBF/,""):w,[y,_]=kk(`${o}${m}`);for(const g of y)p(g);o=_,a=!1}function p(w){if(w===""){d();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}const m=w.indexOf(":");if(m!==-1){const y=w.slice(0,m),_=w[m+1]===" "?2:1,g=w.slice(m+_);h(y,g,w);return}h(w,"",w)}function h(w,m,y){switch(w){case"event":c=m;break;case"data":l=`${l}${m}
40
+ `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):r(new Wh(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:y}));break;default:r(new Wh(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:m,line:y}));break}}function d(){l.length>0&&e({id:i,event:c||void 0,data:l.endsWith(`
41
41
  `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function f(w={}){o&&w.consume&&p(o),a=!0,i=void 0,l="",c="",o=""}return{feed:u,reset:f}}function kk(t){const e=[];let r="",n=0;for(;n<t.length;){const s=t.indexOf("\r",n),o=t.indexOf(`
42
42
  `,n);let a=-1;if(s!==-1&&o!==-1?a=Math.min(s,o):s!==-1?s===t.length-1?a=-1:a=s:o!==-1&&(a=o),a===-1){r=t.slice(n);break}else{const i=t.slice(n,a);e.push(i),n=a+1,t[n-1]==="\r"&&t[n]===`
43
- `&&n++}}return[e,r]}class Qh extends Event{constructor(e,r){var n,s;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(s=r?.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(Xh(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Xh(this),r)}}function Sk(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Yl(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Yl).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Yl(t.cause)}`:t.message:`${t}`}function Xh(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var e0=t=>{throw TypeError(t)},Ql=(t,e,r)=>e.has(t)||e0("Cannot "+r),Ie=(t,e,r)=>(Ql(t,e,"read from private field"),r?r.call(t):e.get(t)),tt=(t,e,r)=>e.has(t)?e0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),We=(t,e,r,n)=>(Ql(t,e,"write to private field"),e.set(t,r),r),Er=(t,e,r)=>(Ql(t,e,"access private method"),r),Tt,hn,Dn,Va,Ha,Js,Un,Gs,Fr,Zn,Fn,Vn,Ws,Gt,Xl,ec,tc,t0,rc,nc,Ks,sc,oc;class Ba extends EventTarget{constructor(e,r){var n,s;super(),tt(this,Gt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,tt(this,Tt),tt(this,hn),tt(this,Dn),tt(this,Va),tt(this,Ha),tt(this,Js),tt(this,Un),tt(this,Gs,null),tt(this,Fr),tt(this,Zn),tt(this,Fn,null),tt(this,Vn,null),tt(this,Ws,null),tt(this,ec,async o=>{var a;Ie(this,Zn).reset();const{body:i,redirected:l,status:c,headers:u}=o;if(c===204){Er(this,Gt,Ks).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?We(this,Dn,new URL(o.url)):We(this,Dn,void 0),c!==200){Er(this,Gt,Ks).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Er(this,Gt,Ks).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ie(this,Tt)===this.CLOSED)return;We(this,Tt,this.OPEN);const p=new Event("open");if((a=Ie(this,Ws))==null||a.call(this,p),this.dispatchEvent(p),typeof i!="object"||!i||!("getReader"in i)){Er(this,Gt,Ks).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const h=new TextDecoder,d=i.getReader();let f=!0;do{const{done:w,value:m}=await d.read();m&&Ie(this,Zn).feed(h.decode(m,{stream:!w})),w&&(f=!1,Ie(this,Zn).reset(),Er(this,Gt,sc).call(this))}while(f)}),tt(this,tc,o=>{We(this,Fr,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Er(this,Gt,sc).call(this,Yl(o))}),tt(this,rc,o=>{typeof o.id=="string"&&We(this,Gs,o.id);const a=new MessageEvent(o.event||"message",{data:o.data,origin:Ie(this,Dn)?Ie(this,Dn).origin:Ie(this,hn).origin,lastEventId:o.id||""});Ie(this,Vn)&&(!o.event||o.event==="message")&&Ie(this,Vn).call(this,a),this.dispatchEvent(a)}),tt(this,nc,o=>{We(this,Js,o)}),tt(this,oc,()=>{We(this,Un,void 0),Ie(this,Tt)===this.CONNECTING&&Er(this,Gt,Xl).call(this)});try{if(e instanceof URL)We(this,hn,e);else if(typeof e=="string")We(this,hn,new URL(e,Tk()));else throw new Error("Invalid URL")}catch{throw Sk("An invalid or illegal string was specified")}We(this,Zn,Yh({onEvent:Ie(this,rc),onRetry:Ie(this,nc)})),We(this,Tt,this.CONNECTING),We(this,Js,3e3),We(this,Ha,(n=r?.fetch)!=null?n:globalThis.fetch),We(this,Va,(s=r?.withCredentials)!=null?s:!1),Er(this,Gt,Xl).call(this)}get readyState(){return Ie(this,Tt)}get url(){return Ie(this,hn).href}get withCredentials(){return Ie(this,Va)}get onerror(){return Ie(this,Fn)}set onerror(e){We(this,Fn,e)}get onmessage(){return Ie(this,Vn)}set onmessage(e){We(this,Vn,e)}get onopen(){return Ie(this,Ws)}set onopen(e){We(this,Ws,e)}addEventListener(e,r,n){const s=r;super.addEventListener(e,s,n)}removeEventListener(e,r,n){const s=r;super.removeEventListener(e,s,n)}close(){Ie(this,Un)&&clearTimeout(Ie(this,Un)),Ie(this,Tt)!==this.CLOSED&&(Ie(this,Fr)&&Ie(this,Fr).abort(),We(this,Tt,this.CLOSED),We(this,Fr,void 0))}}Tt=new WeakMap,hn=new WeakMap,Dn=new WeakMap,Va=new WeakMap,Ha=new WeakMap,Js=new WeakMap,Un=new WeakMap,Gs=new WeakMap,Fr=new WeakMap,Zn=new WeakMap,Fn=new WeakMap,Vn=new WeakMap,Ws=new WeakMap,Gt=new WeakSet,Xl=function(){We(this,Tt,this.CONNECTING),We(this,Fr,new AbortController),Ie(this,Ha)(Ie(this,hn),Er(this,Gt,t0).call(this)).then(Ie(this,ec)).catch(Ie(this,tc))},ec=new WeakMap,tc=new WeakMap,t0=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ie(this,Gs)?{"Last-Event-ID":Ie(this,Gs)}:void 0},cache:"no-store",signal:(t=Ie(this,Fr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},rc=new WeakMap,nc=new WeakMap,Ks=function(t,e){var r;Ie(this,Tt)!==this.CLOSED&&We(this,Tt,this.CLOSED);const n=new Qh("error",{code:e,message:t});(r=Ie(this,Fn))==null||r.call(this,n),this.dispatchEvent(n)},sc=function(t,e){var r;if(Ie(this,Tt)===this.CLOSED)return;We(this,Tt,this.CONNECTING);const n=new Qh("error",{code:e,message:t});(r=Ie(this,Fn))==null||r.call(this,n),this.dispatchEvent(n),We(this,Un,setTimeout(Ie(this,oc),Ie(this,Js)))},oc=new WeakMap,Ba.CONNECTING=0,Ba.OPEN=1,Ba.CLOSED=2;function Tk(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function Ja(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function r0(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n?.headers?{...Ja(e.headers),...Ja(n.headers)}:e.headers};return t(r,s)}:t}let ac;ac=globalThis.crypto;async function Ck(t){return(await ac).getRandomValues(new Uint8Array(t))}async function $k(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let n="";for(;n.length<t;){const s=await Ck(t-n.length);for(const o of s)o<r&&(n+=e[o%e.length])}return n}async function Ek(t){return await $k(t)}async function xk(t){const e=await(await ac).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function n0(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await Ek(t),r=await xk(e);return{code_verifier:e,code_challenge:r}}const at=b3().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Jf.custom,message:"URL must be parseable",fatal:!0}),Vp}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ik=Ye({resource:v().url(),authorization_servers:N(at).optional(),jwks_uri:v().url().optional(),scopes_supported:N(v()).optional(),bearer_methods_supported:N(v()).optional(),resource_signing_alg_values_supported:N(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ge().optional(),authorization_details_types_supported:N(v()).optional(),dpop_signing_alg_values_supported:N(v()).optional(),dpop_bound_access_tokens_required:ge().optional()}),s0=Ye({issuer:v(),authorization_endpoint:at,token_endpoint:at,registration_endpoint:at.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),response_modes_supported:N(v()).optional(),grant_types_supported:N(v()).optional(),token_endpoint_auth_methods_supported:N(v()).optional(),token_endpoint_auth_signing_alg_values_supported:N(v()).optional(),service_documentation:at.optional(),revocation_endpoint:at.optional(),revocation_endpoint_auth_methods_supported:N(v()).optional(),revocation_endpoint_auth_signing_alg_values_supported:N(v()).optional(),introspection_endpoint:v().optional(),introspection_endpoint_auth_methods_supported:N(v()).optional(),introspection_endpoint_auth_signing_alg_values_supported:N(v()).optional(),code_challenge_methods_supported:N(v()).optional(),client_id_metadata_document_supported:ge().optional()}),Rk=Ye({issuer:v(),authorization_endpoint:at,token_endpoint:at,userinfo_endpoint:at.optional(),jwks_uri:at,registration_endpoint:at.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),response_modes_supported:N(v()).optional(),grant_types_supported:N(v()).optional(),acr_values_supported:N(v()).optional(),subject_types_supported:N(v()),id_token_signing_alg_values_supported:N(v()),id_token_encryption_alg_values_supported:N(v()).optional(),id_token_encryption_enc_values_supported:N(v()).optional(),userinfo_signing_alg_values_supported:N(v()).optional(),userinfo_encryption_alg_values_supported:N(v()).optional(),userinfo_encryption_enc_values_supported:N(v()).optional(),request_object_signing_alg_values_supported:N(v()).optional(),request_object_encryption_alg_values_supported:N(v()).optional(),request_object_encryption_enc_values_supported:N(v()).optional(),token_endpoint_auth_methods_supported:N(v()).optional(),token_endpoint_auth_signing_alg_values_supported:N(v()).optional(),display_values_supported:N(v()).optional(),claim_types_supported:N(v()).optional(),claims_supported:N(v()).optional(),service_documentation:v().optional(),claims_locales_supported:N(v()).optional(),ui_locales_supported:N(v()).optional(),claims_parameter_supported:ge().optional(),request_parameter_supported:ge().optional(),request_uri_parameter_supported:ge().optional(),require_request_uri_registration:ge().optional(),op_policy_uri:at.optional(),op_tos_uri:at.optional(),client_id_metadata_document_supported:ge().optional()}),Pk=C({...Rk.shape,...s0.pick({code_challenge_methods_supported:!0}).shape}),Ok=C({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:Gf().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),Ak=C({error:v(),error_description:v().optional(),error_uri:v().optional()}),o0=at.optional().or(j("").transform(()=>{})),Mk=C({redirect_uris:N(at),token_endpoint_auth_method:v().optional(),grant_types:N(v()).optional(),response_types:N(v()).optional(),client_name:v().optional(),client_uri:at.optional(),logo_uri:o0,scope:v().optional(),contacts:N(v()).optional(),tos_uri:o0,policy_uri:v().optional(),jwks_uri:at.optional(),jwks:ht().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),Nk=C({client_id:v(),client_secret:v().optional(),client_id_issued_at:L().optional(),client_secret_expires_at:L().optional()}).strip(),Lk=Mk.merge(Nk);C({error:v(),error_description:v().optional()}).strip(),C({token:v(),token_type_hint:v().optional()}).strip();function jk(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function qk({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}class rt extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class ic extends rt{}ic.errorCode="invalid_request";let Ga=class extends rt{};Ga.errorCode="invalid_client";let Wa=class extends rt{};Wa.errorCode="invalid_grant";let Ka=class extends rt{};Ka.errorCode="unauthorized_client";class lc extends rt{}lc.errorCode="unsupported_grant_type";class cc extends rt{}cc.errorCode="invalid_scope";class uc extends rt{}uc.errorCode="access_denied";let Hn=class extends rt{};Hn.errorCode="server_error";class dc extends rt{}dc.errorCode="temporarily_unavailable";class pc extends rt{}pc.errorCode="unsupported_response_type";class fc extends rt{}fc.errorCode="unsupported_token_type";class hc extends rt{}hc.errorCode="invalid_token";class mc extends rt{}mc.errorCode="method_not_allowed";class gc extends rt{}gc.errorCode="too_many_requests";class Ya extends rt{}Ya.errorCode="invalid_client_metadata";class vc extends rt{}vc.errorCode="insufficient_scope";class _c extends rt{}_c.errorCode="invalid_target";const zk={[ic.errorCode]:ic,[Ga.errorCode]:Ga,[Wa.errorCode]:Wa,[Ka.errorCode]:Ka,[lc.errorCode]:lc,[cc.errorCode]:cc,[uc.errorCode]:uc,[Hn.errorCode]:Hn,[dc.errorCode]:dc,[pc.errorCode]:pc,[fc.errorCode]:fc,[hc.errorCode]:hc,[mc.errorCode]:mc,[gc.errorCode]:gc,[Ya.errorCode]:Ya,[vc.errorCode]:vc,[_c.errorCode]:_c};let zt=class extends Error{constructor(e){super(e??"Unauthorized")}};function Dk(t){return["client_secret_basic","client_secret_post","none"].includes(t)}const yc="code",wc="S256";function Uk(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Dk(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Zk(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":Fk(s,o,r);return;case"client_secret_post":Vk(s,o,n);return;case"none":Hk(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Fk(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Vk(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Hk(t,e){e.set("client_id",t)}async function a0(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=Ak.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=zk[s]||Hn;return new i(o||"",a)}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Hn(s)}}async function mn(t,e){var r,n;try{return await bc(t,e)}catch(s){if(s instanceof Ga||s instanceof Ka)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await bc(t,e);if(s instanceof Wa)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await bc(t,e);throw s}}async function bc(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){var a,i;let l,c;try{l=await Gk(e,{resourceMetadataUrl:s},o),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",e));const u=await Jk(e,t,l),p=await Xk(c,{fetchFn:o});let h=await Promise.resolve(t.clientInformation());if(!h){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const _=p?.client_id_metadata_document_supported===!0,g=t.clientMetadataUrl;if(g&&!Bk(g))throw new Ya(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${g}`);if(_&&g)h={client_id:g},await((a=t.saveClientInformation)===null||a===void 0?void 0:a.call(t,h));else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const k=await s6(c,{metadata:p,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(k),h=k}}const d=!t.redirectUrl;if(r!==void 0||d){const _=await n6(t,c,{metadata:p,resource:u,authorizationCode:r,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}const f=await t.tokens();if(f?.refresh_token)try{const _=await r6(c,{metadata:p,clientInformation:h,refreshToken:f.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof rt)||_ instanceof Hn))throw _}const w=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:y}=await e6(c,{metadata:p,clientInformation:h,state:w,redirectUrl:t.redirectUrl,scope:n||((i=l?.scopes_supported)===null||i===void 0?void 0:i.join(" "))||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(y),await t.redirectToAuthorization(m),"REDIRECT"}function Bk(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Jk(t,e,r){const n=jk(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!qk({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 Qa(t){const e=t.headers.get("WWW-Authenticate");if(!e)return{};const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const s=kc(t,"resource_metadata")||void 0;let o;if(s)try{o=new URL(s)}catch{}const a=kc(t,"scope")||void 0,i=kc(t,"error")||void 0;return{resourceMetadataUrl:o,scope:a,error:i}}function kc(t,e){const r=t.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),s=r.match(n);return s?s[1]||s[2]:null}async function Gk(t,e,r=fetch){var n,s;const o=await Yk(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await((n=o?.body)===null||n===void 0?void 0:n.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await((s=o.body)===null||s===void 0?void 0:s.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Ik.parse(await o.json())}async function Sc(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Sc(t,void 0,r):void 0;throw n}}function Wk(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function i0(t,e,r=fetch){return await Sc(t,{"MCP-Protocol-Version":e},r)}function Kk(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Yk(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!==null&&s!==void 0?s:js;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=Wk(e,a.pathname);l=new URL(u,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:a),l.search=a.search}let c=await i0(l,i,r);if(!n?.metadataUrl&&Kk(c,a.pathname)){const u=new URL(`/.well-known/${e}`,a);c=await i0(u,i,r)}return c}function Qk(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function Xk(t,{fetchFn:e=fetch,protocolVersion:r=js}={}){var n;const s={"MCP-Protocol-Version":r,Accept:"application/json"},o=Qk(t);for(const{url:a,type:i}of o){const l=await Sc(a,s,e);if(l){if(!l.ok){if(await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?s0.parse(await l.json()):Pk.parse(await l.json())}}}async function e6(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(yc))throw new Error(`Incompatible auth server: does not support response type ${yc}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(wc))throw new Error(`Incompatible auth server: does not support code challenge method ${wc}`)}else i=new URL("/authorize",t);const l=await n0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",yc),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",wc),i.searchParams.set("redirect_uri",String(n)),o&&i.searchParams.set("state",o),s&&i.searchParams.set("scope",s),s?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function t6(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function l0(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:a}){var i;const l=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",o.href),s)await s(c,r,l,e);else if(n){const p=(i=e?.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],h=Uk(n,p);Zk(h,n,c,r)}const u=await(a??fetch)(l,{method:"POST",headers:c,body:r});if(!u.ok)throw await a0(u);return Ok.parse(await u.json())}async function r6(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await l0(t,{metadata:e,tokenRequestParams:i,clientInformation:r,addClientAuthentication:o,resource:s,fetchFn:a});return{refresh_token:n,...l}}async function n6(t,e,{metadata:r,resource:n,authorizationCode:s,fetchFn:o}={}){const a=t.clientMetadata.scope;let i;if(t.prepareTokenRequest&&(i=await t.prepareTokenRequest(a)),!i){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await t.codeVerifier();i=t6(s,c,t.redirectUrl)}const l=await t.clientInformation();return l0(e,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function s6(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await a0(o);return Lk.parse(await o.json())}class o6 extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}}class Ys{constructor(e,r){this._url=e,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=r0(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new zt("No auth provider");let r;try{r=await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new zt;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const s=await this._authProvider.tokens();s&&(r.Authorization=`Bearer ${s.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Ja((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;const s=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,a)=>{this._eventSource=new Ba(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await s(i,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:p,scope:h}=Qa(u);this._resourceMetadataUrl=p,this._scope=h}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(o,a);return}const c=new o6(i.code,i.message,i);a(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){a(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let p;try{p=$r.parse(JSON.parse(u.data))}catch(h){(l=this.onerror)===null||l===void 0||l.call(this,h);return}(c=this.onmessage)===null||c===void 0||c.call(this,p)}})}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(e){if(!this._authProvider)throw new zt("No auth provider");if(await mn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,s,o;if(!this._endpoint)throw new Error("Not connected");try{const a=await this._commonHeaders();a.set("content-type","application/json");const i={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,i);if(!l.ok){const c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){const{resourceMetadataUrl:u,scope:p}=Qa(l);if(this._resourceMetadataUrl=u,this._scope=p,await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((s=l.body)===null||s===void 0?void 0:s.cancel())}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}setProtocolVersion(e){this._protocolVersion=e}}class Bn extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(o){s=Yh({onEvent:a=>{o.enqueue(a)},onError(a){e==="terminate"?o.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(o){s.feed(o)}})}}const a6={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Jn extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Qs{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=r0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:a6}async _authThenStart(){var e;if(!this._authProvider)throw new zt("No auth provider");let r;try{r=await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new zt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const s=await this._authProvider.tokens();s&&(r.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Ja((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,s,o;const{resumptionToken:a}=e;try{const i=await this._commonHeaders();i.set("Accept","text/event-stream"),a&&i.set("last-event-id",a);const l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:i,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((s=l.body)===null||s===void 0?void 0:s.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new Jn(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),s)}_scheduleReconnection(e,r=0){var n;const s=this._reconnectionOptions.maxRetries;if(r>=s){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:o}=r;let a,i=!1,l=!1;(async()=>{var u,p,h,d;try{const f=e.pipeThrough(new TextDecoderStream).pipeThrough(new Bn({onRetry:y=>{this._serverRetryMs=y}})).getReader();for(;;){const{value:y,done:_}=await f.read();if(_)break;if(y.id&&(a=y.id,i=!0,s?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{const g=$r.parse(JSON.parse(y.data));qs(g)&&(l=!0,o!==void 0&&(g.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,g)}catch(g){(p=this.onerror)===null||p===void 0||p.call(this,g)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(f){if((h=this.onerror)===null||h===void 0||h.call(this,new Error(`SSE stream disconnected: ${f}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(y){(d=this.onerror)===null||d===void 0||d.call(this,new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new zt("No auth provider");if(await mn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,s,o,a,i,l,c;try{const{resumptionToken:u,onresumptiontoken:p}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:yl(e)?e.id:void 0}).catch(g=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,g)});return}const h=await this._commonHeaders();h.set("content-type","application/json"),h.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:h,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((s=this._fetch)!==null&&s!==void 0?s:fetch)(this._url,d),w=f.headers.get("mcp-session-id");if(w&&(this._sessionId=w),!f.ok){const g=await f.text().catch(()=>null);if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Jn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:b,scope:k}=Qa(f);if(this._resourceMetadataUrl=b,this._scope=k,await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this._hasCompletedAuthFlow=!0,this.send(e)}if(f.status===403&&this._authProvider){const{resourceMetadataUrl:b,scope:k,error:S}=Qa(f);if(S==="insufficient_scope"){const T=f.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===T)throw new Jn(403,"Server returned 403 after trying upscoping");if(k&&(this._scope=k),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=T??void 0,await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zt;return this.send(e)}}throw new Jn(f.status,`Error POSTing to endpoint: ${g}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,f.status===202){await((o=f.body)===null||o===void 0?void 0:o.cancel()),S9(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(g=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,g)});return}const y=(Array.isArray(e)?e:[e]).filter(g=>"method"in g&&"id"in g&&g.id!==void 0).length>0,_=f.headers.get("content-type");if(y)if(_?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:p},!1);else if(_?.includes("application/json")){const g=await f.json(),b=Array.isArray(g)?g.map(k=>$r.parse(k)):[$r.parse(g)];for(const k of b)(a=this.onmessage)===null||a===void 0||a.call(this,k)}else throw await((i=f.body)===null||i===void 0?void 0:i.cancel()),new Jn(-1,`Unexpected content type: ${_}`);else await((l=f.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,s;if(this._sessionId)try{const o=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,a);if(await((n=i.body)===null||n===void 0?void 0:n.cancel()),!i.ok&&i.status!==405)throw new Jn(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(o){throw(s=this.onerror)===null||s===void 0||s.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}}const i6="mcp";class c0{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,i6),this._socket.onerror=n=>{var s;const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),(s=this.onerror)===null||s===void 0||s.call(this,o)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var s,o;let a;try{a=$r.parse(JSON.parse(n.data))}catch(i){(s=this.onerror)===null||s===void 0||s.call(this,i);return}(o=this.onmessage)===null||o===void 0||o.call(this,a)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,n)=>{var s;if(!this._socket){n(new Error("Not connected"));return}(s=this._socket)===null||s===void 0||s.send(JSON.stringify(e)),r()})}}function Xa(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Xa=function(){return t},Xa()}(function(t,e){const r=Qe,n=Qe,s=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(n(429))/5)+parseInt(n(423))/6*(-parseInt(n(418))/7)+-parseInt(n(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(Xa,650197);const u0=()=>{const t=Qe,e={EGhzU:function(r,n){return r!==n},kIrDB:"undefined",llYQe:function(r,n){return r!==n},PZfJg:function(r,n){return r(n)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},l6=(t,e,r)=>{const n=Qe,s=Qe,o={};o[n(410)]=s(398),o.dBkaX=function(i,l){return i===l},o[s(393)]="function";const a=o;typeof window!==a[s(410)]?t.postMessage(e,"*",r):s(428)in t&&a.dBkaX(typeof t.postMessage,a[n(393)])&&t.postMessage(e,r)},c6=(t,e)=>{const r=Qe,n=Qe,s={};s.MbsGh="addEventListener",s.PPniK=function(a,i){return a===i},s[r(419)]=n(412),s[n(404)]="onmessage",s[r(397)]="undefined";const o=s;o.MbsGh in t&&o.PPniK(typeof t[r(427)],o.wRKyh)?t[r(427)](r(400),e):o.thraG in t&&typeof t[n(413)]!==o[n(397)]&&(t.onmessage=e)};class Xs{constructor(e){const r=Qe;this[r(406)]=e}async start(){const e=Qe,r=Qe;this[e(406)]&&(this[e(406)][e(413)]=n=>{var s,o;const a=e,i=r;try{const l=$r[a(402)](n.data[a(400)]);(s=this[a(413)])==null||s.call(this,l,n[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(o=this[i(408)])==null||o.call(this,c)}},this._port[e(396)]=n=>{var s;const o=r,a=r,i=new Error(o(394)+JSON[a(395)](n));(s=this.onerror)==null||s.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const n={lEyuq:function(s){return s()},YihNw:function(s,o){return s(o)}};return new Promise((s,o)=>{var a;const i=Qe,l=Qe;try{const c={};c[i(403)]=r?.[i(403)];const u={};u[l(400)]=e,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),n.lEyuq(s)}catch(c){const u=c instanceof Error?c:new Error(n.YihNw(String,c));(a=this[l(408)])==null||a.call(this,u),o(u)}})}async close(){var e,r;const n=Qe,s=Qe;(e=this._port)==null||e[n(431)](),this._port=void 0,(r=this[s(420)])==null||r.call(this)}}class Tc extends Xs{constructor(e,r=u0()){const n=Qe,s=Qe,o={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[n(391)]=e,this[s(401)]=r;const a=new MessageChannel;this[s(406)]=a.port1,o[s(426)](l6,this[n(401)],{endpoint:this[s(391)]},[a[s(414)]])}}class Cc extends Xs{constructor(e,r=u0()){const n=Qe,s={mOWMr:function(o,a){return o===a},kgkem:function(o,a,i){return o(a,i)}};super(),this._endpoint=e,this._globalObject=r,this[n(432)]=new Promise(o=>{const a=n,i=n;s[a(392)](c6,this[i(401)],l=>{const c=i,u=i;l.data&&s[c(425)](l.data[u(422)],this[u(391)])&&(this[u(406)]=l.ports[-1*4852+1*1601+3251],o())})})}async listen(){return this[Qe(432)]}}function Qe(t,e){const r=Xa();return Qe=function(n,s){return n=n-(17*-491+-669+9407),r[n]},Qe(t,e)}const u6=()=>{const t=new MessageChannel;return[new Xs(t.port1),new Xs(t.port2)]};(function(t,e){const r=Fe,n=Fe,s=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(n(357))/5+-parseInt(n(389))/6*(-parseInt(r(396))/7)+parseInt(n(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ei,-763475+-52067*10+1724410);const d6=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a[s(345)]="tools/list",a.rqstG="tools/call",a.WqUnk="resources/list",a[s(329)]=o(358),a[s(365)]=s(335),a.ookoz="resources/unsubscribe",a[s(385)]=s(340),a.VTIWq="prompts/list",a.SkoRK=s(376),a.QUtUV=s(388),a.XtowM=o(332);const i=a,{id:l,method:c,params:u}=r;let p={};switch(c){case i[o(345)]:p=await e.listTools(u);break;case i.rqstG:p=await e.callTool(u);break;case i[s(334)]:p=await e[s(350)](u);break;case i[o(329)]:p=await e.listResourceTemplates(u);break;case s(372):p=await e[s(383)](u);break;case i.HgYgW:p=await e.subscribeResource(u);break;case i.ookoz:p=await e.unsubscribeResource(u);break;case i[s(385)]:p=await e.getPrompt(u);break;case i.VTIWq:p=await e.listPrompts(u);break;case i[s(344)]:p=await e[s(376)]();break;case i.QUtUV:p=await e.complete(u);break;case s(390):p=await e[s(336)](u?.level);break}const h={};h[s(361)]=p,h[s(394)]=i[s(364)],h.id=l,await((n=t?.transport)==null?void 0:n[s(392)](h))},p6=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a.jQBBS="sampling/createMessage",a.EZqgC="elicitation/create",a[s(370)]=o(376),a.aVeaL=o(332);const i=a,{id:l,method:c,params:u}=r;let p={};switch(c){case s(368):const d={};d.method=c,d[o(367)]=u,p=await e.request(d,Fl);break;case i[o(391)]:const f={};f.method=c,f[o(367)]=u,p=await e[o(381)](f,Da);break;case i.EZqgC:const w={};w.method=c,w.params=u,p=await e.request(w,Fs);break;case i[o(370)]:const m={};m.method=c,p=await e[o(381)](m,Zr);break}const h={};return h[o(361)]=p,h.jsonrpc=i[o(387)],h.id=l,await((n=t?.[s(371)])==null?void 0:n.send(h)),p},f6=(t,e)=>{const r=Fe,n={gXsjT:function(o,a){return o===a},oegpC:r(351),lZOUC:function(o,a,i,l){return o(a,i,l)},ifIKG:"2.0"},s=t._onrequest;t._onrequest=async(o,a)=>{var i,l,c,u,p;const h=r,d=r,{id:f,method:w}=o;try{n[h(333)](w,n.oegpC)?await s[h(386)](t,o,a):await n.lZOUC(d6,t,e,o)}catch(m){const{code:y,message:_,data:g}=m;try{if(y){const b={};b.code=y,b.message=_,b.data=g;const k={};k.error=b,k[h(394)]=n[d(331)],k.id=f,await((i=t?.transport)==null?void 0:i.send(k))}else(c=(l=t?.[d(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(b){(p=(u=t?.[h(371)])==null?void 0:u.onerror)==null||p.call(u,b)}}}},h6=(t,e)=>{const r=Fe,n=Fe,s={};s[r(363)]=function(a,i){return a!==i},s[r(398)]=r(353),s.hzhyg="notifications/cancelled";const o=s;t._onnotification=async a=>{var i,l;const c=r,u=n,{method:p,params:h}=a;if(o[c(363)](p,o[u(398)])&&(o[c(363)](p,o.hzhyg)||h?.forward))try{await e.notification(a)}catch(d){(l=(i=t?.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},m6=(t,e)=>async r=>{var n,s,o,a,i;const l=Fe,c=Fe,u={};u.SEmWX=l(332);const p=u;try{return await p6(t,e,r)}catch(h){const{code:d,message:f,data:w}=h;try{if(d){const m={};m[c(377)]=d,m.message=f,m.data=w;const y={};y[c(348)]=m,y.jsonrpc=p[l(338)],y.id=r.id,await((n=t?.transport)==null?void 0:n[c(392)](y))}else(o=(s=t?.transport)==null?void 0:s[c(339)])==null||o.call(s,h)}catch(m){(i=(a=t?.[l(371)])==null?void 0:a[c(339)])==null||i.call(a,m)}}},g6=(t,e)=>async r=>{var n,s,o;const a=Fe,i=Fe,l={};l.dtUgZ=function(h,d){return h!==d},l.jgCIb=a(353),l.uUjKY="2.0";const c=l,{method:u,params:p}=r;if(c.dtUgZ(u,c.jgCIb)&&(u!==a(400)||p?.forward))try{const h={...r};h[a(394)]=c[i(352)],await((n=e?.[a(371)])==null?void 0:n[a(392)](h))}catch(h){(o=(s=t?.[a(371)])==null?void 0:s[i(339)])==null||o.call(s,h)}};function Fe(t,e){const r=ei();return Fe=function(n,s){return n=n-(-1017+-1439*-1+-97),r[n]},Fe(t,e)}const v6=(t,e)=>async r=>{var n,s,o,a,i,l;const c=Fe,u=Fe,p={};p[c(401)]=u(332);const h=p;try{await((n=e?.transport)==null?void 0:n.send(r))}catch(d){const{code:f,message:w,data:m}=d;try{if(f){const y={};y.code=f,y[c(399)]=w,y.data=m;const _={};_[c(348)]=y,_[c(394)]=h.OhJjz,_.id=r.id,await((s=t?.[c(371)])==null?void 0:s.send(_))}else(a=(o=t?.transport)==null?void 0:o[u(339)])==null||a.call(o,d)}catch(y){(l=(i=t?.transport)==null?void 0:i.onerror)==null||l.call(i,y)}}},$c=()=>{const t=Fe,e=Fe,r={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},n=[],s=(c,u)=>{const p=Fe,h=Fe;if(u){const d=[];for(const f of n)try{d.push(f(c,u))}catch{}for(const f of d)if(r[p(379)](f,null))return f}else for(const d of n)try{r[h(343)](d,c)}catch{}},o=c=>{const u=Fe;r[u(384)](typeof c,u(369))&&!n.includes(c)&&n.push(c)},a=c=>{const u=n.indexOf(c);u!==-1&&n.splice(u,1*-6854+-264+7119)},i=()=>{const c=Fe;n[c(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=s,l[e(330)]=o,l.removeListener=a,l[t(359)]=i,l},_6=t=>{const e=Fe,r=Fe,n={xwPeb:function(s){return s()},Mfvzm:function(s){return s()}};{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(326)]($c);t._onresponse=s,t[e(395)]=o,t.removeResponseListener=a,t.clearResponseListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[r(326)]($c);t[r(328)]=s,t.addRequestListener=o,t[r(354)]=a,t[r(341)]=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(375)]($c);t[e(342)]=s,t[e(327)]=o,t.removeNotificationListener=a,t.clearNotificationListener=i}};function ei(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return ei=function(){return t},ei()}const y6=(t,{beforeInit:e,afterInit:r}={})=>{const n=Fe,s=Fe,o={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:n(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},a=new Map(t._notificationHandlers);t[n(393)][n(402)](),t._notificationHandlers[n(402)](),o.tqDZP(typeof e,o[n(380)])&&e(),o[n(362)](t._onresponse.name,o[n(360)])&&(t[s(349)]=t._onresponse),o[n(347)](_6,t),t.addResponseListener(i=>{const l=s;t.originalOnResponse[l(386)](t,i)}),o.tqDZP(typeof r,o[s(380)])&&o[n(397)](r),t[s(327)](i=>{const{method:l}=i,c=a.get(l);o.tqDZP(typeof c,o.cjSoZ)&&c(i)})},w6=lr,b6=lr;(function(t,e){const r=lr,n=lr,s=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(n(398))/4+parseInt(r(390))/5*(parseInt(n(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(n(395))/9)+parseInt(n(399))/10*(parseInt(n(385))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ti,-1*-881393+2*180895+1*-644809);function lr(t,e){const r=ti();return lr=function(n,s){return n=n-(-1861+-499*4+4241),r[n]},lr(t,e)}function ti(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return ti=function(){return t},ti()}const k6=()=>{const t=lr,e=lr,r={};r.REzPF=function(s,o){return s&o},r.suJHI=function(s,o){return s===o},r[t(386)]=function(s,o){return s&o},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():n.dHTfU.replace(/[xy]/g,s=>{const o=t,a=t,i=n[o(392)](crypto[o(384)](new Uint8Array(8663+2*-4331))[741*2+-1385*-2+4252*-1],15);return(n.suJHI(s,"x")?i:n[a(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},S6=t=>{const e=lr,r=lr,n=new Uint8Array(t);return crypto.getRandomValues(n),Array[e(401)](n,s=>s[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},Vr={};Vr[w6(391)]=k6,Vr[b6(396)]=S6;const Pt=cr;(function(t,e){const r=cr,n=cr,s=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(n(499))/2)+parseInt(n(543))/3*(parseInt(n(514))/4)+parseInt(r(502))/5*(parseInt(n(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ri,1472653*1+-2*-897917+-2275789);const T6=(t,e)=>{const r=cr,n=cr,s={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};f6(t,e),h6(t,e);const o=m6(e,t),a=s[r(510)](v6,e,t),i=s[n(549)](g6,e,t);e[n(537)](o),e[r(519)](a),e.addNotificationListener(i),t[n(556)]=()=>{const l=n;e.removeRequestListener(o),e[l(530)](a),e[l(529)](i)}},Ec=(t,e,r)=>{const n=cr,s={pMiva:function(i,l){return i instanceof l},TeTEy:n(546),fyZbd:function(i,l,c){return i(l,c)}},o=()=>{var i;const l=n;s.pMiva(r,Ys)&&((i=r._eventSource)==null||i.addEventListener(s[l(547)],()=>{var c;const u=l;(c=r[u(509)])==null||c[u(546)]()})),T6(t,e)},a={};a.afterInit=o,s.fyZbd(y6,e,a)},d0=(t,e=Vr.randomUUID())=>{const r=cr,n=cr,s={OfssH:function(u,p,h){return u(p,h)}},o={};o[r(528)]=e;const a=o,i={};i[r(528)]=e;const l={};l[n(558)]=i,l[r(534)]=r(524);const c={requestInit:l,eventSourceInit:{async fetch(u,p){const h=r,d=n,f=new Headers(p?.[h(558)]||{});Object.entries(a)[d(498)](([m,y])=>{f[d(527)](m,y)});const w={...p};return w[d(558)]=f,s.OfssH(fetch,u,w)},withCredentials:!0}};return t&&(c.requestInit[r(558)].Authorization=r(533)+t,a.Authorization="Bearer "+t),c},p0=(t,e=Vr[Pt(517)]())=>{const r=Pt,n=Pt,s={};s.nwQhY="include";const o=s,a={};a["stream-session-id"]=e;const i={};i.headers=a,i.credentials=o[r(520)];const l={};l[r(544)]=i;const c=l;return t&&(c.requestInit.headers[n(552)]=n(533)+t),c},xc=async(t,e,r)=>{const n=Pt,s=Pt,o={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},a=o.CFfFC(r);try{return await t[n(538)](a),a}catch(i){if(i instanceof zt){const l=await e();return await a[s(505)](l),await o[n(525)](xc,t,e,r)}else throw i}};function cr(t,e){const r=ri();return cr=function(n,s){return n=n-498,r[n]},cr(t,e)}const f0=(t,e)=>{const r=Pt,n=Pt,s={};s.RsKXs=function(a,i){return a in i},s.PBhps="waitForOAuthCode",s[r(535)]="function",s[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const o=s;if(o.RsKXs(o[n(551)],t))return t[n(523)];if(typeof e===o.yTKoP)return e;throw new Error(o.RZhOv)},C6=async t=>{const e=Pt,r=Pt,n={TFSRn:function(I,A,P){return I(A,P)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(I){return I()},WIVYl:function(I,A,P,D){return I(A,P,D)},jniGY:"sessionId"},{client:s,url:o,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:p}=t,h={};h.authProvider=l,h.requestInit=c,h.eventSourceInit=u;const d=h,f=i||Vr.randomUUID(),w=n[e(506)](d0,a,f);if(c){const I={...w.requestInit,...c};I.headers={...w[e(544)].headers,...c.headers},d.requestInit=I}else d[r(544)]=w.requestInit;if(u){const I={...w[e(559)],...u};d.eventSourceInit=I}else d.eventSourceInit=w.eventSourceInit;const m={};m.listChanged=!0;const y={};y.roots=m,y.sampling={},y[e(511)]={};const _=y,g={};g[r(536)]=n.HwvVa,g.version=e(526);const b={};b.capabilities=_;const k=new Bs(g,b),S=()=>new Ys(new URL(o),d);let T=n[r(504)](S);if(l){const I=n[e(506)](f0,l,p);T=await n[r(513)](xc,k,I,S)}else await k[e(538)](T);n[r(513)](Ec,k,s,T),T[r(557)]=T[r(542)].searchParams[r(532)](n.jniGY);const x={};return x.transport=T,x.sessionId=T[e(557)],x};function ri(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return ri=function(){return t},ri()}const $6=async t=>{const e=Pt,r=Pt,n={Vajmx:e(500),biJOc:function(I){return I()},zXcpO:function(I,A,P){return I(A,P)},zDnjZ:function(I,A,P,D){return I(A,P,D)},FQMAh:function(I,A,P,D){return I(A,P,D)}},{client:s,url:o,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:p}=t,h={};h.authProvider=l,h.requestInit=c,h.reconnectionOptions=u;const d=h,f=i||Vr.randomUUID(),w=p0(a,f);if(c){const I={...w.requestInit,...c};I.headers={...w.requestInit.headers,...c.headers},d[e(544)]=I}else d.requestInit=w.requestInit;const m={};m.listChanged=!0;const y={};y[r(550)]=m,y.sampling={},y.elicitation={};const _=y,g={};g[e(536)]=n[r(508)],g[e(555)]="1.0.0";const b={};b.capabilities=_;const k=new Bs(g,b),S=()=>new Qs(new URL(o),d);let T=n[e(503)](S);if(l){const I=n[e(501)](f0,l,p);T=await n.zDnjZ(xc,k,I,S)}else await k.connect(T);n.FQMAh(Ec,k,s,T);const x={};return x.transport=T,x[r(557)]=T.sessionId,x},E6=async t=>{const e=Pt,r=Pt,n={QgzDy:e(540),jkaVB:function(y,_,g,b){return y(_,g,b)}},{client:s,url:o,token:a,sessionId:i}=t,l={};l.listChanged=!0;const c={};c[e(550)]=l,c[e(515)]={},c[r(511)]={};const u=c,p={};p.name=n[r(548)],p[r(555)]=r(526);const h={};h.capabilities=u;const d=new Bs(p,h),f=i||Vr[r(517)](),w=new c0(new URL(o+e(522)+f+r(554)+a));await d.connect(w),n.jkaVB(Ec,d,s,w);const m={};return m[e(512)]=w,m[r(557)]=f,m},eo=Ct,ni=Ct;function Ct(t,e){const r=si();return Ct=function(n,s){return n=n-(-16761+51*337),r[n]},Ct(t,e)}(function(t,e){const r=Ct,n=Ct,s=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(n(449))/5)+-parseInt(n(455))/6+-parseInt(r(427))/7+-parseInt(n(438))/8*(parseInt(n(459))/9)+parseInt(r(430))/10*(parseInt(n(436))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(si,-220880+1*-333337+-2*-384996);function si(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return si=function(){return t},si()}const x6=()=>Vr.randomBytes(3485*1+-261+-3184);class I6{constructor(e){const r=Ct,n=Ct;this._callBackPromise={};const{clientMetadata:s,state:o,redirectCallback:a,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=s,this[r(454)]=s[r(445)][0],this._state=o||x6(),this._redirectCallback=a||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[n(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,n,s,o,a,i;const l=Ct,c=Ct,u={qITTp:function(f,w,m){return f(w,m)},qcFPW:l(452)},p=await u.qITTp(fetch,e,{method:u[l(453)]});!p.ok&&((n=(r=this._callBackPromise).reject)==null||n.call(r,c(446)+p.statusText));const h=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!h.ok){(o=(s=this[l(433)]).reject)==null||o.call(s,"Failed to fetch auth code: "+h.statusText);return}const d=await h[l(431)]();(i=(a=this[c(433)])[l(456)])==null||i.call(a,d[l(432)])}async getAuthCodeByStateFunction(e,r){const n=Ct,s=Ct,o={};o.tuSmb=n(429);const a=o,i={};i[n(460)]=a.tuSmb;const l={};return l[s(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=Ct,r=this[e(433)];return()=>new Promise((n,s)=>{const o=e;r.resolve=n,r[o(434)]=s})}get redirectUrl(){return this[Ct(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[eo(447)](){return this[eo(444)]}[ni(435)](e){const r=eo;this[r(444)]=e}[ni(457)](){return this[ni(439)]}saveTokens(e){this._tokens=e}[ni(450)](e){this[eo(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[eo(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=ai,n=ai,s=t();;)try{var o=parseInt(r(361))/1*(parseInt(n(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(n(354))/6*(parseInt(r(360))/7)+parseInt(n(362))/8+parseInt(n(364))/9+-parseInt(n(356))/10*(parseInt(r(355))/11);if(o===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(oi,-73523*-3+1*-407717+530518);function oi(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return oi=function(){return t},oi()}function ai(t,e){var r=oi();return ai=function(n,s){n=n-(-1*-642+503*-5+2227);var o=r[n];return o},ai(t,e)}class R6{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}class P6 extends Uh{constructor(e,r){var n,s;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ja.options.map((o,a)=>[o,a])),this.isMessageIgnored=(o,a)=>{const i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._instructions=r?.instructions,this._jsonSchemaValidator=(s=r?.jsonSchemaValidator)!==null&&s!==void 0?s:new Jh,this.setRequestHandler(nh,o=>this._oninitialize(o)),this.setNotificationHandler(bl,()=>{var o;return(o=this.oninitialized)===null||o===void 0?void 0:o.call(this)}),this._capabilities.logging&&this.setRequestHandler(qa,async(o,a)=>{var i;const l=a.sessionId||((i=a.requestInfo)===null||i===void 0?void 0:i.headers["mcp-session-id"])||void 0,{level:c}=o.params,u=ja.safeParse(c);return u.success&&this._loggingLevels.set(l,u.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new R6(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fh(this._capabilities,e)}setRequestHandler(e,r){var n,s,o;const a=zn(e),i=a?.method;if(!i)throw new Error("Schema is missing a method literal");let l;if(qt(i)){const u=i,p=(n=u._zod)===null||n===void 0?void 0:n.def;l=(s=p?.value)!==null&&s!==void 0?s:u.value}else{const u=i,p=u._def;l=(o=p?.value)!==null&&o!==void 0?o:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");if(l==="tools/call"){const u=async(p,h)=>{const d=Ht(La,p);if(!d.success){const y=d.error instanceof Error?d.error.message:String(d.error);throw new ne(ae.InvalidParams,`Invalid tools/call request: ${y}`)}const{params:f}=d.data,w=await Promise.resolve(r(p,h));if(f.task){const y=Ht(Ln,w);if(!y.success){const _=y.error instanceof Error?y.error.message:String(y.error);throw new ne(ae.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}const m=Ht(qn,w);if(!m.success){const y=m.error instanceof Error?m.error.message:String(m.error);throw new ne(ae.InvalidParams,`Invalid tools/call result: ${y}`)}return m.data};return super.setRequestHandler(e,u)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){var r,n,s;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((s=this._clientCapabilities)===null||s===void 0)&&s.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){var r,n;switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!(!((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.elicitation)===null||n===void 0)&&n.url))throw new Error(`Client does not support URL elicitation (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){var r,n;Wh((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,e,"Client")}assertTaskHandlerCapability(e){var r;this._capabilities&&Gh((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,e,"Server")}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Wf.includes(r)?r:js,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Zr)}async createMessage(e,r){var n,s;if((e.tools||e.toolChoice)&&!(!((s=(n=this._clientCapabilities)===null||n===void 0?void 0:n.sampling)===null||s===void 0)&&s.tools))throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const o=e.messages[e.messages.length-1],a=Array.isArray(o.content)?o.content:[o.content],i=a.some(p=>p.type==="tool_result"),l=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=l?Array.isArray(l.content)?l.content:[l.content]:[],u=c.some(p=>p.type==="tool_use");if(i){if(a.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){const p=new Set(c.filter(d=>d.type==="tool_use").map(d=>d.id)),h=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(p.size!==h.size||![...p].every(d=>h.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Sh,r):this.request({method:"sampling/createMessage",params:e},Da,r)}async elicitInput(e,r){var n,s,o,a,i;switch((n=e.mode)!==null&&n!==void 0?n:"form"){case"url":{if(!(!((o=(s=this._clientCapabilities)===null||s===void 0?void 0:s.elicitation)===null||o===void 0)&&o.url))throw new Error("Client does not support url elicitation.");const c=e;return this.request({method:"elicitation/create",params:c},Fs,r)}case"form":{if(!(!((i=(a=this._clientCapabilities)===null||a===void 0?void 0:a.elicitation)===null||i===void 0)&&i.form))throw new Error("Client does not support form elicitation.");const c=e.mode==="form"?e:{...e,mode:"form"},u=await this.request({method:"elicitation/create",params:c},Fs,r);if(u.action==="accept"&&u.content&&c.requestedSchema)try{const h=this._jsonSchemaValidator.getValidator(c.requestedSchema)(u.content);if(!h.valid)throw new ne(ae.InvalidParams,`Elicitation response content does not match requested schema: ${h.errorMessage}`)}catch(p){throw p instanceof ne?p:new ne(ae.InternalError,`Error validating elicitation response: ${p instanceof Error?p.message:String(p)}`)}return u}}}createElicitationCompletionNotifier(e,r){var n,s;if(!(!((s=(n=this._clientCapabilities)===null||n===void 0?void 0:n.elicitation)===null||s===void 0)&&s.url))throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Fl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const Ic=Symbol.for("mcp.completable");function O6(t,e){return Object.defineProperty(t,Ic,{value:{complete:e},enumerable:!1,writable:!1,configurable:!1}),t}function A6(t){return!!t&&typeof t=="object"&&Ic in t}function M6(t){const e=t[Ic];return e?.complete}var h0;(function(t){t.Completable="McpCompletable"})(h0||(h0={}));const m0=1e6,Rc=1e6,g0=1e4,N6=1e6;class xr{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){xr.validateLength(e,m0,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let n="",s=0,o=0;for(;s<e.length;)if(e[s]==="{"){n&&(r.push(n),n="");const a=e.indexOf("}",s);if(a===-1)throw new Error("Unclosed template expression");if(o++,o>g0)throw new Error(`Template contains too many expressions (max ${g0})`);const i=e.slice(s+1,a),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),p=u[0];for(const h of u)xr.validateLength(h,Rc,"Variable name");r.push({name:p,operator:l,names:u,exploded:c}),s=a+1}else n+=e[s],s++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return xr.validateLength(e,Rc,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const a=e.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(c.toString(),e.operator);return`${l}=${u}`}).filter(l=>l.length>0);return a.length===0?"":(e.operator==="?"?"?":"&")+a.join("&")}if(e.names.length>1){const a=e.names.map(i=>r[i]).filter(i=>i!==void 0);return a.length===0?"":a.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=r[e.name];if(n===void 0)return"";const o=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let r="",n=!1;for(const s of this.parts){if(typeof s=="string"){r+=s;continue}const o=this.expandPart(s,e);o&&((s.operator==="?"||s.operator==="&")&&n?r+=o.replace("?","&"):r+=o,(s.operator==="?"||s.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const o of e.names)xr.validateLength(o,Rc,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){const a=e.names[o],i=o===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n;const s=e.name;switch(e.operator){case"":n=e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:s}),r}match(e){xr.validateLength(e,m0,"URI");let r="^";const n=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const l=this.partToRegExp(i);for(const{pattern:c,name:u}of l)r+=c,n.push({name:u,exploded:i.exploded})}r+="$",xr.validateLength(r,N6,"Generated regex pattern");const s=new RegExp(r),o=e.match(s);if(!o)return null;const a={};for(let i=0;i<n.length;i++){const{name:l,exploded:c}=n[i],u=o[i+1],p=l.replace("*","");c&&u.includes(",")?a[p]=u.split(","):a[p]=u}return a}}const L6=/^[A-Za-z0-9._-]{1,128}$/;function j6(t){const e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!L6.test(t)){const r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function q6(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(const r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function v0(t){const e=j6(t);return q6(t,e.warnings),e.isValid}class z6{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){const s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}class _0{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new P6(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new z6(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Hr(zl)),this.server.assertCanSetRequestHandler(Hr(La)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zl,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const n={name:e,title:r.title,description:r.description,inputSchema:(()=>{const s=Hs(r.inputSchema);return s?qh(s,{strictUnions:!0,pipeStrategy:"input"}):U6})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const s=Hs(r.outputSchema);s&&(n.outputSchema=qh(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(La,async(e,r)=>{var n;try{const s=this._registeredTools[e.params.name];if(!s)throw new ne(ae.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new ne(ae.InvalidParams,`Tool ${e.params.name} disabled`);const o=!!e.params.task,a=(n=s.execution)===null||n===void 0?void 0:n.taskSupport,i="createTask"in s.handler;if((a==="required"||a==="optional")&&!i)throw new ne(ae.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!o)throw new ne(ae.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(s,e,r);const l=await this.validateToolInput(s,e.params.arguments,e.params.name),c=await this.executeToolHandler(s,l,r);return o||await this.validateToolOutput(s,c,e.params.name),c}catch(s){if(s instanceof ne&&s.code===ae.UrlElicitationRequired)throw s;return this.createToolError(s instanceof Error?s.message:String(s))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;const s=Hs(e.inputSchema),o=s??e.inputSchema,a=await Vl(o,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Hl(i);throw new ne(ae.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new ne(ae.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const s=Hs(e.outputSchema),o=await Vl(s,r.structuredContent);if(!o.success){const a="error"in o?o.error:"Unknown error",i=Hl(a);throw new ne(ae.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(e,r,n){const s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(e.inputSchema){const i=s;return await Promise.resolve(i.createTask(r,a))}else{const i=s;return await Promise.resolve(i.createTask(a))}}if(e.inputSchema){const a=s;return await Promise.resolve(a(r,n))}else{const a=s;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(e,r,n){var s;if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(e,r.params.arguments,r.params.name),a=e.handler,i={...n,taskStore:n.taskStore},l=o?await Promise.resolve(a.createTask(o,i)):await Promise.resolve(a.createTask(i)),c=l.task.taskId;let u=l.task;const p=(s=u.pollInterval)!==null&&s!==void 0?s:5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(d=>setTimeout(d,p));const h=await n.taskStore.getTask(c);if(!h)throw new ne(ae.InternalError,`Task ${c} not found during polling`);u=h}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Hr(Zl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Zl,async e=>{switch(e.params.ref.type){case"ref/prompt":return w4(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return b4(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ne(ae.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const n=this._registeredPrompts[r.name];if(!n)throw new ne(ae.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ne(ae.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return to;const s=zn(n.argsSchema),o=s?.[e.params.argument.name];if(!A6(o))return to;const a=M6(o);if(!a)return to;const i=await a(e.params.argument.value,e.params.context);return b0(i)}async handleResourceCompletion(e,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return to;throw new ne(ae.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return to;const o=await s(e.params.argument.value,e.params.context);return b0(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Hr(Na)),this.server.assertCanSetRequestHandler(Hr(Rl)),this.server.assertCanSetRequestHandler(Hr(Ol)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Na,async(e,r)=>{const n=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),s=[];for(const o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;const a=await o.resourceTemplate.listCallback(r);for(const i of a.resources)s.push({...o.metadata,...i})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Rl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ol,async(e,r)=>{const n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new ne(ae.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(const o of Object.values(this._registeredResourceTemplates)){const a=o.resourceTemplate.uriTemplate.match(n.toString());if(a)return o.readCallback(n,a,r)}throw new ne(ae.InvalidParams,`Resource ${n} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Hr(Al)),this.server.assertCanSetRequestHandler(Hr(Ml)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Al,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?F6(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ml,async(e,r)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new ne(ae.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new ne(ae.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const s=Hs(n.argsSchema),o=await Vl(s,e.params.arguments);if(!o.success){const l="error"in o?o.error:"Unknown error",c=Hl(l);throw new ne(ae.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}const a=o.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const s=n.callback;return await Promise.resolve(s(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());const o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const a=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){const a={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,s,o){const a={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,a}_createRegisteredPrompt(e,r,n,s,o){const a={title:r,description:n,argsSchema:s===void 0?void 0:Vs(s),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=Vs(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,a}_createRegisteredTool(e,r,n,s,o,a,i,l,c){v0(e);const u={title:r,description:n,inputSchema:w0(s),outputSchema:w0(o),annotations:a,execution:i,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&v0(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Vs(p.paramsSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const l=r[0];Pc(l)?(s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Pc(r[0])&&(a=r.shift())):typeof l=="object"&&l!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,n,s,o,a,{taskSupport:"forbidden"},void 0,i)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:o,inputSchema:a,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(e,s,o,a,i,l,{taskSupport:"forbidden"},c,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());const o=r[0],a=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:o,argsSchema:a}=r,i=this._createRegisteredPrompt(e,s,o,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class D6{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new xr(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){var r;return(r=this._callbacks.complete)===null||r===void 0?void 0:r[e]}}const U6={type:"object",properties:{}};function y0(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Z6(t){return"_def"in t||"_zod"in t||y0(t)}function Pc(t){return typeof t!="object"||t===null||Z6(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(y0)}function w0(t){if(t)return Pc(t)?Vs(t):t}function F6(t){const e=zn(t);return e?Object.entries(e).map(([r,n])=>{const s=$4(n),o=E4(n);return{name:r,description:s,required:!o}}):[]}function Hr(t){const e=zn(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");const n=xh(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function b0(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const to={completion:{values:[],hasMore:!1}};function V6(t){var e;return t.title!==void 0&&t.title!==""?t.title:"annotations"in t&&(!((e=t.annotations)===null||e===void 0)&&e.title)?t.annotations.title:t.name}class ro{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new ro,r=new ro;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(var e;this._messageQueue.length>0;){const r=this._messageQueue.shift();(e=this.onmessage)===null||e===void 0||e.call(this,r.message,r.extra)}}async close(){var e;const r=this._otherTransport;this._otherTransport=void 0,await r?.close(),(e=this.onclose)===null||e===void 0||e.call(this)}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r?.authInfo}})}}class H6{constructor(e,r){const n={name:"web-mcp-server",version:"1.0.0"},s={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new _0(e||n,r||{capabilities:s}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=o=>{this.onerror?.(o)},this.server.server.setRequestHandler(qa,async()=>({}))}async connect(e){return typeof e.start=="function"?(this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new Cc(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,n){return this.server.registerTool(e,r,n)}registerPrompt(e,r,n){return this.server.registerPrompt(e,r,n)}registerResource(e,r,n,s){return typeof r=="string"?this.server.registerResource(e,r,n,s):this.server.registerResource(e,r,n,s)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(e,r){return await this.server.server.createMessage(e,r)}async elicitInput(e,r){return await this.server.server.elicitInput(e,r)}async listRoots(e,r){return await this.server.server.listRoots(e,r)}async sendLoggingMessage(e){return await this.server.server.sendLoggingMessage(e)}async sendResourceUpdated(e){return await this.server.server.sendResourceUpdated(e)}request(e,r,n){return this.server.server.request(e,r,n)}async notification(e,r){return await this.server.server.notification(e,r)}setRequestHandler(e,r){this.server.server.setRequestHandler(e,r)}removeRequestHandler(e){this.server.server.removeRequestHandler(e)}setNotificationHandler(e,r){this.server.server.setNotificationHandler(e,r)}removeNotificationHandler(e){this.server.server.removeNotificationHandler(e)}onSubscribe(e){this.server.server.setRequestHandler(fh,e)}onUnsubscribe(e){this.server.server.setRequestHandler(hh,e)}onSetLogLevel(e){this.server.server.setRequestHandler(qa,e)}onListResources(e){this.server.server.setRequestHandler(Na,e)}onRootsListChanged(e){this.server.server.setNotificationHandler($h,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const B6=(t,e)=>new Cc(t,e),J6=()=>u6(),G6=t=>t instanceof Cc,W6=t=>t instanceof _0;class k0{constructor(e,r){const n={name:"web-mcp-client",version:"1.0.0"},s={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Bs(e||n,r||{capabilities:s}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=o=>{this.onerror?.(o)}}async connect(e){if(typeof e.start=="function")return this.transport=e,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:s,type:o,agent:a,onError:i}=e;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:s};let p;return await(async()=>{const{transport:d,sessionId:f}=o==="sse"?await C6(u):o==="socket"?await E6(u):await $6(u);d.onerror=async w=>{i?.(w)},p={transport:d,sessionId:f}})(),p}const l=new URL(r);let c;if(o==="channel"&&(c=new Tc(r),await this.client.connect(c)),o==="sse"){const u=d0(n,s);c=new Ys(l,u),await this.client.connect(c)}if(o==="socket"&&(c=new c0(new URL(`${r}?sessionId=${s}&token=${n}`)),c.sessionId=s,await this.client.connect(c)),typeof c>"u"){const u=p0(n,s);c=new Qs(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(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,qn,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,n){return this.client.request(e,r,n)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler(Ul,e)}onCreateMessage(e){this.client.setRequestHandler(Dl,e)}onListRoots(e){this.client.setRequestHandler(Ch,e)}onToolListChanged(e){this.client.setNotificationHandler(bh,e)}onPromptListChanged(e){this.client.setNotificationHandler(_h,e)}onResourceListChanged(e){this.client.setNotificationHandler(ph,e)}onResourceUpdated(e){this.client.setNotificationHandler(mh,e)}onLoggingMessage(e){this.client.setNotificationHandler(kh,e)}async onPagehide(e){e.persisted||(S0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const K6=(t,e)=>new Ys(t,e),Y6=(t,e)=>new Qs(t,e),Q6=(t,e)=>new Tc(t,e),X6=t=>t instanceof Ys,S0=t=>t instanceof Qs,e5=t=>t instanceof Tc,t5=t=>t instanceof Bs,Gn=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},T0=(t,e,r)=>{const n=async function(s){s.source===window&&s.data.type===t&&s.data.direction===r&&await e(s.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},Oc=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(s=>{chrome.tabs.sendMessage(s.id,{type:t,data:e,direction:r,tabId:s.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},Ac=(t,e,r,n)=>{const s=(o,a,i)=>{if(o.type===t&&o.direction===r&&(!n||n&&o.tabId===n)){const{data:l}=o;e(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(s),()=>chrome.runtime.onMessage.removeListener(s)};class Mc{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=Ac("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=$r.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){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(e,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 s=n.tabIds[n.tabIds.length-1];Oc("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:s,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const C0=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});class r5{constructor(e=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||C0(),this._messageListener1=T0("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(r=>{console.error("【Page Svr Transport】 notifyRegistration失败:",r)})},"content->page"),this._messageListener2=T0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=$r.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Gn("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Gn("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&e.result?.content&&Gn("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{Gn("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(e))}}}class n5{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||C0(),this.tabId=r,Ac("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(n=>{console.log("【Content Svr Transport】 notifyRegistration 失败",n)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");Ac("mcp-client-to-server",e=>{if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const r=$r.parse(e.mcpMessage);this.onmessage?.(r),e.mcpMessage.params?.name&&Gn("update-page-app-message",{status:"run",message:e.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),Oc("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&e.result?.content&&Gn("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(e){this._isStarted&&(this._lastRegistration=e,Oc("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(e))}}}var Wn={},Nc,$0;function s5(){return $0||($0=1,Nc=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Nc}var Lc={},Br={},E0;function gn(){if(E0)return Br;E0=1;let t;const e=[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 Br.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},Br.getSymbolTotalCodewords=function(n){return e[n]},Br.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Br.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Br.isKanjiModeEnabled=function(){return typeof t<"u"},Br.toSJIS=function(n){return t(n)},Br}var jc={},x0;function qc(){return x0||(x0=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,s){if(t.isValid(n))return n;try{return e(n)}catch{return s}}})(jc)),jc}var zc,I0;function o5(){if(I0)return zc;I0=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},zc=t,zc}var Dc,R0;function a5(){if(R0)return Dc;R0=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,r,n,s){const o=e*this.size+r;this.data[o]=n,s&&(this.reservedBit[o]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},Dc=t,Dc}var Uc={},P0;function i5(){return P0||(P0=1,(function(t){const e=gn().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const s=Math.floor(n/7)+2,o=e(n),a=o===145?26:Math.ceil((o-13)/(2*s-2))*2,i=[o-7];for(let l=1;l<s-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},t.getPositions=function(n){const s=[],o=t.getRowColCoords(n),a=o.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||s.push([o[i],o[l]]);return s}})(Uc)),Uc}var Zc={},O0;function l5(){if(O0)return Zc;O0=1;const t=gn().getSymbolSize,e=7;return Zc.getPositions=function(n){const s=t(n);return[[0,0],[s-e,0],[0,s-e]]},Zc}var Fc={},A0;function c5(){return A0||(A0=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const o=s.size;let a=0,i=0,l=0,c=null,u=null;for(let p=0;p<o;p++){i=l=0,c=u=null;for(let h=0;h<o;h++){let d=s.get(p,h);d===c?i++:(i>=5&&(a+=e.N1+(i-5)),c=d,i=1),d=s.get(h,p),d===u?l++:(l>=5&&(a+=e.N1+(l-5)),u=d,l=1)}i>=5&&(a+=e.N1+(i-5)),l>=5&&(a+=e.N1+(l-5))}return a},t.getPenaltyN2=function(s){const o=s.size;let a=0;for(let i=0;i<o-1;i++)for(let l=0;l<o-1;l++){const c=s.get(i,l)+s.get(i,l+1)+s.get(i+1,l)+s.get(i+1,l+1);(c===4||c===0)&&a++}return a*e.N2},t.getPenaltyN3=function(s){const o=s.size;let a=0,i=0,l=0;for(let c=0;c<o;c++){i=l=0;for(let u=0;u<o;u++)i=i<<1&2047|s.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|s.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*e.N3},t.getPenaltyN4=function(s){let o=0;const a=s.data.length;for(let l=0;l<a;l++)o+=s.data[l];return Math.abs(Math.ceil(o*100/a/5)-10)*e.N4};function r(n,s,o){switch(n){case t.Patterns.PATTERN000:return(s+o)%2===0;case t.Patterns.PATTERN001:return s%2===0;case t.Patterns.PATTERN010:return o%3===0;case t.Patterns.PATTERN011:return(s+o)%3===0;case t.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case t.Patterns.PATTERN101:return s*o%2+s*o%3===0;case t.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case t.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}t.applyMask=function(s,o){const a=o.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)o.isReserved(l,i)||o.xor(l,i,r(s,l,i))},t.getBestMask=function(s,o){const a=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){o(c),t.applyMask(c,s);const u=t.getPenaltyN1(s)+t.getPenaltyN2(s)+t.getPenaltyN3(s)+t.getPenaltyN4(s);t.applyMask(c,s),u<l&&(l=u,i=c)}return i}})(Fc)),Fc}var ii={},M0;function N0(){if(M0)return ii;M0=1;const t=qc(),e=[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 ii.getBlocksCount=function(s,o){switch(o){case t.L:return e[(s-1)*4+0];case t.M:return e[(s-1)*4+1];case t.Q:return e[(s-1)*4+2];case t.H:return e[(s-1)*4+3];default:return}},ii.getTotalCodewordsCount=function(s,o){switch(o){case t.L:return r[(s-1)*4+0];case t.M:return r[(s-1)*4+1];case t.Q:return r[(s-1)*4+2];case t.H:return r[(s-1)*4+3];default:return}},ii}var Vc={},no={},L0;function u5(){if(L0)return no;L0=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let s=0;s<255;s++)t[s]=n,e[n]=s,n<<=1,n&256&&(n^=285);for(let s=255;s<512;s++)t[s]=t[s-255]})(),no.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},no.exp=function(n){return t[n]},no.mul=function(n,s){return n===0||s===0?0:t[e[n]+e[s]]},no}var j0;function d5(){return j0||(j0=1,(function(t){const e=u5();t.mul=function(n,s){const o=new Uint8Array(n.length+s.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<s.length;i++)o[a+i]^=e.mul(n[a],s[i]);return o},t.mod=function(n,s){let o=new Uint8Array(n);for(;o.length-s.length>=0;){const a=o[0];for(let l=0;l<s.length;l++)o[l]^=e.mul(s[l],a);let i=0;for(;i<o.length&&o[i]===0;)i++;o=o.slice(i)}return o},t.generateECPolynomial=function(n){let s=new Uint8Array([1]);for(let o=0;o<n;o++)s=t.mul(s,new Uint8Array([1,e.exp(o)]));return s}})(Vc)),Vc}var Hc,q0;function p5(){if(q0)return Hc;q0=1;const t=d5();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const s=new Uint8Array(n.length+this.degree);s.set(n);const o=t.mod(s,this.genPoly),a=this.degree-o.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(o,a),i}return o},Hc=e,Hc}var Bc={},Jc={},Gc={},z0;function D0(){return z0||(z0=1,Gc.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),Gc}var ur={},U0;function Z0(){if(U0)return ur;U0=1;const t="[0-9]+",e="[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
44
- ]))+`;ur.KANJI=new RegExp(r,"g"),ur.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ur.BYTE=new RegExp(n,"g"),ur.NUMERIC=new RegExp(t,"g"),ur.ALPHANUMERIC=new RegExp(e,"g");const s=new RegExp("^"+r+"$"),o=new RegExp("^"+t+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ur.testKanji=function(l){return s.test(l)},ur.testNumeric=function(l){return o.test(l)},ur.testAlphanumeric=function(l){return a.test(l)},ur}var F0;function vn(){return F0||(F0=1,(function(t){const e=D0(),r=Z0();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(o,a){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!e.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?o.ccBits[0]:a<27?o.ccBits[1]:o.ccBits[2]},t.getBestModeForData=function(o){return r.testNumeric(o)?t.NUMERIC:r.testAlphanumeric(o)?t.ALPHANUMERIC:r.testKanji(o)?t.KANJI:t.BYTE},t.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},t.isValid=function(o){return o&&o.bit&&o.ccBits};function n(s){if(typeof s!="string")throw new Error("Param is not a string");switch(s.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+s)}}t.from=function(o,a){if(t.isValid(o))return o;try{return n(o)}catch{return a}}})(Jc)),Jc}var V0;function f5(){return V0||(V0=1,(function(t){const e=gn(),r=N0(),n=qc(),s=vn(),o=D0(),a=7973,i=e.getBCHDigit(a);function l(h,d,f){for(let w=1;w<=40;w++)if(d<=t.getCapacity(w,f,h))return w}function c(h,d){return s.getCharCountIndicator(h,d)+4}function u(h,d){let f=0;return h.forEach(function(w){const m=c(w.mode,d);f+=m+w.getBitsLength()}),f}function p(h,d){for(let f=1;f<=40;f++)if(u(h,f)<=t.getCapacity(f,d,s.MIXED))return f}t.from=function(d,f){return o.isValid(d)?parseInt(d,10):f},t.getCapacity=function(d,f,w){if(!o.isValid(d))throw new Error("Invalid QR Code version");typeof w>"u"&&(w=s.BYTE);const m=e.getSymbolTotalCodewords(d),y=r.getTotalCodewordsCount(d,f),_=(m-y)*8;if(w===s.MIXED)return _;const g=_-c(w,d);switch(w){case s.NUMERIC:return Math.floor(g/10*3);case s.ALPHANUMERIC:return Math.floor(g/11*2);case s.KANJI:return Math.floor(g/13);case s.BYTE:default:return Math.floor(g/8)}},t.getBestVersionForData=function(d,f){let w;const m=n.from(f,n.M);if(Array.isArray(d)){if(d.length>1)return p(d,m);if(d.length===0)return 1;w=d[0]}else w=d;return l(w.mode,w.getLength(),m)},t.getEncodedBits=function(d){if(!o.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;e.getBCHDigit(f)-i>=0;)f^=a<<e.getBCHDigit(f)-i;return d<<12|f}})(Bc)),Bc}var Wc={},H0;function h5(){if(H0)return Wc;H0=1;const t=gn(),e=1335,r=21522,n=t.getBCHDigit(e);return Wc.getEncodedBits=function(o,a){const i=o.bit<<3|a;let l=i<<10;for(;t.getBCHDigit(l)-n>=0;)l^=e<<t.getBCHDigit(l)-n;return(i<<10|l)^r},Wc}var Kc={},Yc,B0;function m5(){if(B0)return Yc;B0=1;const t=vn();function e(r){this.mode=t.NUMERIC,this.data=r.toString()}return e.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){let s,o,a;for(s=0;s+3<=this.data.length;s+=3)o=this.data.substr(s,3),a=parseInt(o,10),n.put(a,10);const i=this.data.length-s;i>0&&(o=this.data.substr(s),a=parseInt(o,10),n.put(a,i*3+1))},Yc=e,Yc}var Qc,J0;function g5(){if(J0)return Qc;J0=1;const t=vn(),e=["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=t.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(s){return 11*Math.floor(s/2)+6*(s%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(s){let o;for(o=0;o+2<=this.data.length;o+=2){let a=e.indexOf(this.data[o])*45;a+=e.indexOf(this.data[o+1]),s.put(a,11)}this.data.length%2&&s.put(e.indexOf(this.data[o]),6)},Qc=r,Qc}var Xc,G0;function v5(){if(G0)return Xc;G0=1;const t=vn();function e(r){this.mode=t.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return e.getBitsLength=function(n){return n*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(r){for(let n=0,s=this.data.length;n<s;n++)r.put(this.data[n],8)},Xc=e,Xc}var eu,W0;function _5(){if(W0)return eu;W0=1;const t=vn(),e=gn();function r(n){this.mode=t.KANJI,this.data=n}return r.getBitsLength=function(s){return s*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 s;for(s=0;s<this.data.length;s++){let o=e.toSJIS(this.data[s]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[s]+`
45
- Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},eu=r,eu}var tu={exports:{}},K0;function y5(){return K0||(K0=1,(function(t){var e={single_source_shortest_paths:function(r,n,s){var o={},a={};a[n]=0;var i=e.PriorityQueue.make();i.push(n,0);for(var l,c,u,p,h,d,f,w,m;!i.empty();){l=i.pop(),c=l.value,p=l.cost,h=r[c]||{};for(u in h)h.hasOwnProperty(u)&&(d=h[u],f=p+d,w=a[u],m=typeof a[u]>"u",(m||w>f)&&(a[u]=f,i.push(u,f),o[u]=c))}if(typeof s<"u"&&typeof a[s]>"u"){var y=["Could not find a path from ",n," to ",s,"."].join("");throw new Error(y)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var s=[],o=n;o;)s.push(o),r[o],o=r[o];return s.reverse(),s},find_path:function(r,n,s){var o=e.single_source_shortest_paths(r,n,s);return e.extract_shortest_path_from_predecessor_list(o,s)},PriorityQueue:{make:function(r){var n=e.PriorityQueue,s={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(s[o]=n[o]);return s.queue=[],s.sorter=r.sorter||n.default_sorter,s},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var s={value:r,cost:n};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(tu)),tu.exports}var Y0;function w5(){return Y0||(Y0=1,(function(t){const e=vn(),r=m5(),n=g5(),s=v5(),o=_5(),a=Z0(),i=gn(),l=y5();function c(y){return unescape(encodeURIComponent(y)).length}function u(y,_,g){const b=[];let k;for(;(k=y.exec(g))!==null;)b.push({data:k[0],index:k.index,mode:_,length:k[0].length});return b}function p(y){const _=u(a.NUMERIC,e.NUMERIC,y),g=u(a.ALPHANUMERIC,e.ALPHANUMERIC,y);let b,k;return i.isKanjiModeEnabled()?(b=u(a.BYTE,e.BYTE,y),k=u(a.KANJI,e.KANJI,y)):(b=u(a.BYTE_KANJI,e.BYTE,y),k=[]),_.concat(g,b,k).sort(function(T,x){return T.index-x.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function h(y,_){switch(_){case e.NUMERIC:return r.getBitsLength(y);case e.ALPHANUMERIC:return n.getBitsLength(y);case e.KANJI:return o.getBitsLength(y);case e.BYTE:return s.getBitsLength(y)}}function d(y){return y.reduce(function(_,g){const b=_.length-1>=0?_[_.length-1]:null;return b&&b.mode===g.mode?(_[_.length-1].data+=g.data,_):(_.push(g),_)},[])}function f(y){const _=[];for(let g=0;g<y.length;g++){const b=y[g];switch(b.mode){case e.NUMERIC:_.push([b,{data:b.data,mode:e.ALPHANUMERIC,length:b.length},{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.ALPHANUMERIC:_.push([b,{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.KANJI:_.push([b,{data:b.data,mode:e.BYTE,length:c(b.data)}]);break;case e.BYTE:_.push([{data:b.data,mode:e.BYTE,length:c(b.data)}])}}return _}function w(y,_){const g={},b={start:{}};let k=["start"];for(let S=0;S<y.length;S++){const T=y[S],x=[];for(let I=0;I<T.length;I++){const A=T[I],P=""+S+I;x.push(P),g[P]={node:A,lastCount:0},b[P]={};for(let D=0;D<k.length;D++){const U=k[D];g[U]&&g[U].node.mode===A.mode?(b[U][P]=h(g[U].lastCount+A.length,A.mode)-h(g[U].lastCount,A.mode),g[U].lastCount+=A.length):(g[U]&&(g[U].lastCount=A.length),b[U][P]=h(A.length,A.mode)+4+e.getCharCountIndicator(A.mode,_))}}k=x}for(let S=0;S<k.length;S++)b[k[S]].end=0;return{map:b,table:g}}function m(y,_){let g;const b=e.getBestModeForData(y);if(g=e.from(_,b),g!==e.BYTE&&g.bit<b.bit)throw new Error('"'+y+'" cannot be encoded with mode '+e.toString(g)+`.
46
- Suggested mode is: `+e.toString(b));switch(g===e.KANJI&&!i.isKanjiModeEnabled()&&(g=e.BYTE),g){case e.NUMERIC:return new r(y);case e.ALPHANUMERIC:return new n(y);case e.KANJI:return new o(y);case e.BYTE:return new s(y)}}t.fromArray=function(_){return _.reduce(function(g,b){return typeof b=="string"?g.push(m(b,null)):b.data&&g.push(m(b.data,b.mode)),g},[])},t.fromString=function(_,g){const b=p(_,i.isKanjiModeEnabled()),k=f(b),S=w(k,g),T=l.find_path(S.map,"start","end"),x=[];for(let I=1;I<T.length-1;I++)x.push(S.table[T[I]].node);return t.fromArray(d(x))},t.rawSplit=function(_){return t.fromArray(p(_,i.isKanjiModeEnabled()))}})(Kc)),Kc}var Q0;function b5(){if(Q0)return Lc;Q0=1;const t=gn(),e=qc(),r=o5(),n=a5(),s=i5(),o=l5(),a=c5(),i=N0(),l=p5(),c=f5(),u=h5(),p=vn(),h=w5();function d(S,T){const x=S.size,I=o.getPositions(T);for(let A=0;A<I.length;A++){const P=I[A][0],D=I[A][1];for(let U=-1;U<=7;U++)if(!(P+U<=-1||x<=P+U))for(let V=-1;V<=7;V++)D+V<=-1||x<=D+V||(U>=0&&U<=6&&(V===0||V===6)||V>=0&&V<=6&&(U===0||U===6)||U>=2&&U<=4&&V>=2&&V<=4?S.set(P+U,D+V,!0,!0):S.set(P+U,D+V,!1,!0))}}function f(S){const T=S.size;for(let x=8;x<T-8;x++){const I=x%2===0;S.set(x,6,I,!0),S.set(6,x,I,!0)}}function w(S,T){const x=s.getPositions(T);for(let I=0;I<x.length;I++){const A=x[I][0],P=x[I][1];for(let D=-2;D<=2;D++)for(let U=-2;U<=2;U++)D===-2||D===2||U===-2||U===2||D===0&&U===0?S.set(A+D,P+U,!0,!0):S.set(A+D,P+U,!1,!0)}}function m(S,T){const x=S.size,I=c.getEncodedBits(T);let A,P,D;for(let U=0;U<18;U++)A=Math.floor(U/3),P=U%3+x-8-3,D=(I>>U&1)===1,S.set(A,P,D,!0),S.set(P,A,D,!0)}function y(S,T,x){const I=S.size,A=u.getEncodedBits(T,x);let P,D;for(P=0;P<15;P++)D=(A>>P&1)===1,P<6?S.set(P,8,D,!0):P<8?S.set(P+1,8,D,!0):S.set(I-15+P,8,D,!0),P<8?S.set(8,I-P-1,D,!0):P<9?S.set(8,15-P-1+1,D,!0):S.set(8,15-P-1,D,!0);S.set(I-8,8,1,!0)}function _(S,T){const x=S.size;let I=-1,A=x-1,P=7,D=0;for(let U=x-1;U>0;U-=2)for(U===6&&U--;;){for(let V=0;V<2;V++)if(!S.isReserved(A,U-V)){let se=!1;D<T.length&&(se=(T[D]>>>P&1)===1),S.set(A,U-V,se),P--,P===-1&&(D++,P=7)}if(A+=I,A<0||x<=A){A-=I,I=-I;break}}}function g(S,T,x){const I=new r;x.forEach(function(V){I.put(V.mode.bit,4),I.put(V.getLength(),p.getCharCountIndicator(V.mode,S)),V.write(I)});const A=t.getSymbolTotalCodewords(S),P=i.getTotalCodewordsCount(S,T),D=(A-P)*8;for(I.getLengthInBits()+4<=D&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const U=(D-I.getLengthInBits())/8;for(let V=0;V<U;V++)I.put(V%2?17:236,8);return b(I,S,T)}function b(S,T,x){const I=t.getSymbolTotalCodewords(T),A=i.getTotalCodewordsCount(T,x),P=I-A,D=i.getBlocksCount(T,x),U=I%D,V=D-U,se=Math.floor(I/D),fe=Math.floor(P/D),de=fe+1,re=se-fe,_e=new l(re);let H=0;const O=new Array(D),F=new Array(D);let q=0;const E=new Uint8Array(S.buffer);for(let ye=0;ye<D;ye++){const pe=ye<V?fe:de;O[ye]=E.slice(H,H+pe),F[ye]=_e.encode(O[ye]),H+=pe,q=Math.max(q,pe)}const R=new Uint8Array(I);let $=0,B,W;for(B=0;B<q;B++)for(W=0;W<D;W++)B<O[W].length&&(R[$++]=O[W][B]);for(B=0;B<re;B++)for(W=0;W<D;W++)R[$++]=F[W][B];return R}function k(S,T,x,I){let A;if(Array.isArray(S))A=h.fromArray(S);else if(typeof S=="string"){let se=T;if(!se){const fe=h.rawSplit(S);se=c.getBestVersionForData(fe,x)}A=h.fromString(S,se||40)}else throw new Error("Invalid data");const P=c.getBestVersionForData(A,x);if(!P)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=P;else if(T<P)throw new Error(`
43
+ `&&n++}}return[e,r]}class Yh extends Event{constructor(e,r){var n,s;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(s=r?.message)!=null?s:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(Qh(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Qh(this),r)}}function Sk(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Yl(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Yl).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Yl(t.cause)}`:t.message:`${t}`}function Qh(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var Xh=t=>{throw TypeError(t)},Ql=(t,e,r)=>e.has(t)||Xh("Cannot "+r),Ie=(t,e,r)=>(Ql(t,e,"read from private field"),r?r.call(t):e.get(t)),tt=(t,e,r)=>e.has(t)?Xh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),We=(t,e,r,n)=>(Ql(t,e,"write to private field"),e.set(t,r),r),Er=(t,e,r)=>(Ql(t,e,"access private method"),r),Tt,hn,Dn,Va,Ha,Js,Un,Gs,Fr,Zn,Fn,Vn,Ws,Gt,Xl,ec,tc,e0,rc,nc,Ks,sc,oc;class Ba extends EventTarget{constructor(e,r){var n,s;super(),tt(this,Gt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,tt(this,Tt),tt(this,hn),tt(this,Dn),tt(this,Va),tt(this,Ha),tt(this,Js),tt(this,Un),tt(this,Gs,null),tt(this,Fr),tt(this,Zn),tt(this,Fn,null),tt(this,Vn,null),tt(this,Ws,null),tt(this,ec,async o=>{var a;Ie(this,Zn).reset();const{body:i,redirected:l,status:c,headers:u}=o;if(c===204){Er(this,Gt,Ks).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?We(this,Dn,new URL(o.url)):We(this,Dn,void 0),c!==200){Er(this,Gt,Ks).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Er(this,Gt,Ks).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ie(this,Tt)===this.CLOSED)return;We(this,Tt,this.OPEN);const p=new Event("open");if((a=Ie(this,Ws))==null||a.call(this,p),this.dispatchEvent(p),typeof i!="object"||!i||!("getReader"in i)){Er(this,Gt,Ks).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const h=new TextDecoder,d=i.getReader();let f=!0;do{const{done:w,value:m}=await d.read();m&&Ie(this,Zn).feed(h.decode(m,{stream:!w})),w&&(f=!1,Ie(this,Zn).reset(),Er(this,Gt,sc).call(this))}while(f)}),tt(this,tc,o=>{We(this,Fr,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Er(this,Gt,sc).call(this,Yl(o))}),tt(this,rc,o=>{typeof o.id=="string"&&We(this,Gs,o.id);const a=new MessageEvent(o.event||"message",{data:o.data,origin:Ie(this,Dn)?Ie(this,Dn).origin:Ie(this,hn).origin,lastEventId:o.id||""});Ie(this,Vn)&&(!o.event||o.event==="message")&&Ie(this,Vn).call(this,a),this.dispatchEvent(a)}),tt(this,nc,o=>{We(this,Js,o)}),tt(this,oc,()=>{We(this,Un,void 0),Ie(this,Tt)===this.CONNECTING&&Er(this,Gt,Xl).call(this)});try{if(e instanceof URL)We(this,hn,e);else if(typeof e=="string")We(this,hn,new URL(e,Tk()));else throw new Error("Invalid URL")}catch{throw Sk("An invalid or illegal string was specified")}We(this,Zn,Kh({onEvent:Ie(this,rc),onRetry:Ie(this,nc)})),We(this,Tt,this.CONNECTING),We(this,Js,3e3),We(this,Ha,(n=r?.fetch)!=null?n:globalThis.fetch),We(this,Va,(s=r?.withCredentials)!=null?s:!1),Er(this,Gt,Xl).call(this)}get readyState(){return Ie(this,Tt)}get url(){return Ie(this,hn).href}get withCredentials(){return Ie(this,Va)}get onerror(){return Ie(this,Fn)}set onerror(e){We(this,Fn,e)}get onmessage(){return Ie(this,Vn)}set onmessage(e){We(this,Vn,e)}get onopen(){return Ie(this,Ws)}set onopen(e){We(this,Ws,e)}addEventListener(e,r,n){const s=r;super.addEventListener(e,s,n)}removeEventListener(e,r,n){const s=r;super.removeEventListener(e,s,n)}close(){Ie(this,Un)&&clearTimeout(Ie(this,Un)),Ie(this,Tt)!==this.CLOSED&&(Ie(this,Fr)&&Ie(this,Fr).abort(),We(this,Tt,this.CLOSED),We(this,Fr,void 0))}}Tt=new WeakMap,hn=new WeakMap,Dn=new WeakMap,Va=new WeakMap,Ha=new WeakMap,Js=new WeakMap,Un=new WeakMap,Gs=new WeakMap,Fr=new WeakMap,Zn=new WeakMap,Fn=new WeakMap,Vn=new WeakMap,Ws=new WeakMap,Gt=new WeakSet,Xl=function(){We(this,Tt,this.CONNECTING),We(this,Fr,new AbortController),Ie(this,Ha)(Ie(this,hn),Er(this,Gt,e0).call(this)).then(Ie(this,ec)).catch(Ie(this,tc))},ec=new WeakMap,tc=new WeakMap,e0=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ie(this,Gs)?{"Last-Event-ID":Ie(this,Gs)}:void 0},cache:"no-store",signal:(t=Ie(this,Fr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},rc=new WeakMap,nc=new WeakMap,Ks=function(t,e){var r;Ie(this,Tt)!==this.CLOSED&&We(this,Tt,this.CLOSED);const n=new Yh("error",{code:e,message:t});(r=Ie(this,Fn))==null||r.call(this,n),this.dispatchEvent(n)},sc=function(t,e){var r;if(Ie(this,Tt)===this.CLOSED)return;We(this,Tt,this.CONNECTING);const n=new Yh("error",{code:e,message:t});(r=Ie(this,Fn))==null||r.call(this,n),this.dispatchEvent(n),We(this,Un,setTimeout(Ie(this,oc),Ie(this,Js)))},oc=new WeakMap,Ba.CONNECTING=0,Ba.OPEN=1,Ba.CLOSED=2;function Tk(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function Ja(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function t0(t=fetch,e){return e?async(r,n)=>{const s={...e,...n,headers:n?.headers?{...Ja(e.headers),...Ja(n.headers)}:e.headers};return t(r,s)}:t}let ac;ac=globalThis.crypto;async function Ck(t){return(await ac).getRandomValues(new Uint8Array(t))}async function $k(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length;let n="";for(;n.length<t;){const s=await Ck(t-n.length);for(const o of s)o<r&&(n+=e[o%e.length])}return n}async function Ek(t){return await $k(t)}async function xk(t){const e=await(await ac).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function r0(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await Ek(t),r=await xk(e);return{code_verifier:e,code_challenge:r}}const at=b3().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Bf.custom,message:"URL must be parseable",fatal:!0}),Fp}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ik=Ye({resource:v().url(),authorization_servers:N(at).optional(),jwks_uri:v().url().optional(),scopes_supported:N(v()).optional(),bearer_methods_supported:N(v()).optional(),resource_signing_alg_values_supported:N(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ge().optional(),authorization_details_types_supported:N(v()).optional(),dpop_signing_alg_values_supported:N(v()).optional(),dpop_bound_access_tokens_required:ge().optional()}),n0=Ye({issuer:v(),authorization_endpoint:at,token_endpoint:at,registration_endpoint:at.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),response_modes_supported:N(v()).optional(),grant_types_supported:N(v()).optional(),token_endpoint_auth_methods_supported:N(v()).optional(),token_endpoint_auth_signing_alg_values_supported:N(v()).optional(),service_documentation:at.optional(),revocation_endpoint:at.optional(),revocation_endpoint_auth_methods_supported:N(v()).optional(),revocation_endpoint_auth_signing_alg_values_supported:N(v()).optional(),introspection_endpoint:v().optional(),introspection_endpoint_auth_methods_supported:N(v()).optional(),introspection_endpoint_auth_signing_alg_values_supported:N(v()).optional(),code_challenge_methods_supported:N(v()).optional(),client_id_metadata_document_supported:ge().optional()}),Rk=Ye({issuer:v(),authorization_endpoint:at,token_endpoint:at,userinfo_endpoint:at.optional(),jwks_uri:at,registration_endpoint:at.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),response_modes_supported:N(v()).optional(),grant_types_supported:N(v()).optional(),acr_values_supported:N(v()).optional(),subject_types_supported:N(v()),id_token_signing_alg_values_supported:N(v()),id_token_encryption_alg_values_supported:N(v()).optional(),id_token_encryption_enc_values_supported:N(v()).optional(),userinfo_signing_alg_values_supported:N(v()).optional(),userinfo_encryption_alg_values_supported:N(v()).optional(),userinfo_encryption_enc_values_supported:N(v()).optional(),request_object_signing_alg_values_supported:N(v()).optional(),request_object_encryption_alg_values_supported:N(v()).optional(),request_object_encryption_enc_values_supported:N(v()).optional(),token_endpoint_auth_methods_supported:N(v()).optional(),token_endpoint_auth_signing_alg_values_supported:N(v()).optional(),display_values_supported:N(v()).optional(),claim_types_supported:N(v()).optional(),claims_supported:N(v()).optional(),service_documentation:v().optional(),claims_locales_supported:N(v()).optional(),ui_locales_supported:N(v()).optional(),claims_parameter_supported:ge().optional(),request_parameter_supported:ge().optional(),request_uri_parameter_supported:ge().optional(),require_request_uri_registration:ge().optional(),op_policy_uri:at.optional(),op_tos_uri:at.optional(),client_id_metadata_document_supported:ge().optional()}),Pk=C({...Rk.shape,...n0.pick({code_challenge_methods_supported:!0}).shape}),Ok=C({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:Jf().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),Ak=C({error:v(),error_description:v().optional(),error_uri:v().optional()}),s0=at.optional().or(j("").transform(()=>{})),Mk=C({redirect_uris:N(at),token_endpoint_auth_method:v().optional(),grant_types:N(v()).optional(),response_types:N(v()).optional(),client_name:v().optional(),client_uri:at.optional(),logo_uri:s0,scope:v().optional(),contacts:N(v()).optional(),tos_uri:s0,policy_uri:v().optional(),jwks_uri:at.optional(),jwks:ht().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),Nk=C({client_id:v(),client_secret:v().optional(),client_id_issued_at:L().optional(),client_secret_expires_at:L().optional()}).strip(),Lk=Mk.merge(Nk);C({error:v(),error_description:v().optional()}).strip(),C({token:v(),token_type_hint:v().optional()}).strip();function jk(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function qk({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}class rt extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class ic extends rt{}ic.errorCode="invalid_request";let Ga=class extends rt{};Ga.errorCode="invalid_client";let Wa=class extends rt{};Wa.errorCode="invalid_grant";let Ka=class extends rt{};Ka.errorCode="unauthorized_client";class lc extends rt{}lc.errorCode="unsupported_grant_type";class cc extends rt{}cc.errorCode="invalid_scope";class uc extends rt{}uc.errorCode="access_denied";let Hn=class extends rt{};Hn.errorCode="server_error";class dc extends rt{}dc.errorCode="temporarily_unavailable";class pc extends rt{}pc.errorCode="unsupported_response_type";class fc extends rt{}fc.errorCode="unsupported_token_type";class hc extends rt{}hc.errorCode="invalid_token";class mc extends rt{}mc.errorCode="method_not_allowed";class gc extends rt{}gc.errorCode="too_many_requests";class Ya extends rt{}Ya.errorCode="invalid_client_metadata";class vc extends rt{}vc.errorCode="insufficient_scope";class _c extends rt{}_c.errorCode="invalid_target";const zk={[ic.errorCode]:ic,[Ga.errorCode]:Ga,[Wa.errorCode]:Wa,[Ka.errorCode]:Ka,[lc.errorCode]:lc,[cc.errorCode]:cc,[uc.errorCode]:uc,[Hn.errorCode]:Hn,[dc.errorCode]:dc,[pc.errorCode]:pc,[fc.errorCode]:fc,[hc.errorCode]:hc,[mc.errorCode]:mc,[gc.errorCode]:gc,[Ya.errorCode]:Ya,[vc.errorCode]:vc,[_c.errorCode]:_c};let zt=class extends Error{constructor(e){super(e??"Unauthorized")}};function Dk(t){return["client_secret_basic","client_secret_post","none"].includes(t)}const yc="code",wc="S256";function Uk(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Dk(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Zk(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":Fk(s,o,r);return;case"client_secret_post":Vk(s,o,n);return;case"none":Hk(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Fk(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Vk(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Hk(t,e){e.set("client_id",t)}async function o0(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=Ak.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=zk[s]||Hn;return new i(o||"",a)}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Hn(s)}}async function mn(t,e){var r,n;try{return await bc(t,e)}catch(s){if(s instanceof Ga||s instanceof Ka)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await bc(t,e);if(s instanceof Wa)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await bc(t,e);throw s}}async function bc(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){var a,i;let l,c;try{l=await Gk(e,{resourceMetadataUrl:s},o),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",e));const u=await Jk(e,t,l),p=await Xk(c,{fetchFn:o});let h=await Promise.resolve(t.clientInformation());if(!h){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const _=p?.client_id_metadata_document_supported===!0,g=t.clientMetadataUrl;if(g&&!Bk(g))throw new Ya(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${g}`);if(_&&g)h={client_id:g},await((a=t.saveClientInformation)===null||a===void 0?void 0:a.call(t,h));else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const k=await s6(c,{metadata:p,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(k),h=k}}const d=!t.redirectUrl;if(r!==void 0||d){const _=await n6(t,c,{metadata:p,resource:u,authorizationCode:r,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}const f=await t.tokens();if(f?.refresh_token)try{const _=await r6(c,{metadata:p,clientInformation:h,refreshToken:f.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof rt)||_ instanceof Hn))throw _}const w=t.state?await t.state():void 0,{authorizationUrl:m,codeVerifier:y}=await e6(c,{metadata:p,clientInformation:h,state:w,redirectUrl:t.redirectUrl,scope:n||((i=l?.scopes_supported)===null||i===void 0?void 0:i.join(" "))||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(y),await t.redirectToAuthorization(m),"REDIRECT"}function Bk(t){if(!t)return!1;try{const e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Jk(t,e,r){const n=jk(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!qk({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 Qa(t){const e=t.headers.get("WWW-Authenticate");if(!e)return{};const[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const s=kc(t,"resource_metadata")||void 0;let o;if(s)try{o=new URL(s)}catch{}const a=kc(t,"scope")||void 0,i=kc(t,"error")||void 0;return{resourceMetadataUrl:o,scope:a,error:i}}function kc(t,e){const r=t.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),s=r.match(n);return s?s[1]||s[2]:null}async function Gk(t,e,r=fetch){var n,s;const o=await Yk(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await((n=o?.body)===null||n===void 0?void 0:n.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await((s=o.body)===null||s===void 0?void 0:s.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Ik.parse(await o.json())}async function Sc(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Sc(t,void 0,r):void 0;throw n}}function Wk(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function a0(t,e,r=fetch){return await Sc(t,{"MCP-Protocol-Version":e},r)}function Kk(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Yk(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!==null&&s!==void 0?s:js;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=Wk(e,a.pathname);l=new URL(u,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:a),l.search=a.search}let c=await a0(l,i,r);if(!n?.metadataUrl&&Kk(c,a.pathname)){const u=new URL(`/.well-known/${e}`,a);c=await a0(u,i,r)}return c}function Qk(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function Xk(t,{fetchFn:e=fetch,protocolVersion:r=js}={}){var n;const s={"MCP-Protocol-Version":r,Accept:"application/json"},o=Qk(t);for(const{url:a,type:i}of o){const l=await Sc(a,s,e);if(l){if(!l.ok){if(await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return i==="oauth"?n0.parse(await l.json()):Pk.parse(await l.json())}}}async function e6(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(yc))throw new Error(`Incompatible auth server: does not support response type ${yc}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(wc))throw new Error(`Incompatible auth server: does not support code challenge method ${wc}`)}else i=new URL("/authorize",t);const l=await r0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",yc),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",wc),i.searchParams.set("redirect_uri",String(n)),o&&i.searchParams.set("state",o),s&&i.searchParams.set("scope",s),s?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function t6(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function i0(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:a}){var i;const l=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",o.href),s)await s(c,r,l,e);else if(n){const p=(i=e?.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],h=Uk(n,p);Zk(h,n,c,r)}const u=await(a??fetch)(l,{method:"POST",headers:c,body:r});if(!u.ok)throw await o0(u);return Ok.parse(await u.json())}async function r6(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await i0(t,{metadata:e,tokenRequestParams:i,clientInformation:r,addClientAuthentication:o,resource:s,fetchFn:a});return{refresh_token:n,...l}}async function n6(t,e,{metadata:r,resource:n,authorizationCode:s,fetchFn:o}={}){const a=t.clientMetadata.scope;let i;if(t.prepareTokenRequest&&(i=await t.prepareTokenRequest(a)),!i){if(!s)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await t.codeVerifier();i=t6(s,c,t.redirectUrl)}const l=await t.clientInformation();return i0(e,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function s6(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await o0(o);return Lk.parse(await o.json())}class o6 extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}}class Ys{constructor(e,r){this._url=e,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=t0(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new zt("No auth provider");let r;try{r=await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new zt;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const s=await this._authProvider.tokens();s&&(r.Authorization=`Bearer ${s.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Ja((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;const s=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,a)=>{this._eventSource=new Ba(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await s(i,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){const{resourceMetadataUrl:p,scope:h}=Qa(u);this._resourceMetadataUrl=p,this._scope=h}return u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(o,a);return}const c=new o6(i.code,i.message,i);a(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){a(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let p;try{p=$r.parse(JSON.parse(u.data))}catch(h){(l=this.onerror)===null||l===void 0||l.call(this,h);return}(c=this.onmessage)===null||c===void 0||c.call(this,p)}})}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(e){if(!this._authProvider)throw new zt("No auth provider");if(await mn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,s,o;if(!this._endpoint)throw new Error("Not connected");try{const a=await this._commonHeaders();a.set("content-type","application/json");const i={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,i);if(!l.ok){const c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){const{resourceMetadataUrl:u,scope:p}=Qa(l);if(this._resourceMetadataUrl=u,this._scope=p,await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((s=l.body)===null||s===void 0?void 0:s.cancel())}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}setProtocolVersion(e){this._protocolVersion=e}}class Bn extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(o){s=Kh({onEvent:a=>{o.enqueue(a)},onError(a){e==="terminate"?o.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(o){s.feed(o)}})}}const a6={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Jn extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Qs{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=t0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:a6}async _authThenStart(){var e;if(!this._authProvider)throw new zt("No auth provider");let r;try{r=await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new zt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const s=await this._authProvider.tokens();s&&(r.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const n=Ja((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,s,o;const{resumptionToken:a}=e;try{const i=await this._commonHeaders();i.set("Accept","text/event-stream"),a&&i.set("last-event-id",a);const l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:i,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((s=l.body)===null||s===void 0?void 0:s.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new Jn(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),s)}_scheduleReconnection(e,r=0){var n;const s=this._reconnectionOptions.maxRetries;if(r>=s){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:o}=r;let a,i=!1,l=!1;(async()=>{var u,p,h,d;try{const f=e.pipeThrough(new TextDecoderStream).pipeThrough(new Bn({onRetry:y=>{this._serverRetryMs=y}})).getReader();for(;;){const{value:y,done:_}=await f.read();if(_)break;if(y.id&&(a=y.id,i=!0,s?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{const g=$r.parse(JSON.parse(y.data));qs(g)&&(l=!0,o!==void 0&&(g.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,g)}catch(g){(p=this.onerror)===null||p===void 0||p.call(this,g)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(f){if((h=this.onerror)===null||h===void 0||h.call(this,new Error(`SSE stream disconnected: ${f}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:s,replayMessageId:o},0)}catch(y){(d=this.onerror)===null||d===void 0||d.call(this,new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new zt("No auth provider");if(await mn(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,s,o,a,i,l,c;try{const{resumptionToken:u,onresumptiontoken:p}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:yl(e)?e.id:void 0}).catch(g=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,g)});return}const h=await this._commonHeaders();h.set("content-type","application/json"),h.set("accept","application/json, text/event-stream");const d={...this._requestInit,method:"POST",headers:h,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},f=await((s=this._fetch)!==null&&s!==void 0?s:fetch)(this._url,d),w=f.headers.get("mcp-session-id");if(w&&(this._sessionId=w),!f.ok){const g=await f.text().catch(()=>null);if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Jn(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:b,scope:k}=Qa(f);if(this._resourceMetadataUrl=b,this._scope=k,await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new zt;return this._hasCompletedAuthFlow=!0,this.send(e)}if(f.status===403&&this._authProvider){const{resourceMetadataUrl:b,scope:k,error:S}=Qa(f);if(S==="insufficient_scope"){const T=f.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===T)throw new Jn(403,"Server returned 403 after trying upscoping");if(k&&(this._scope=k),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=T??void 0,await mn(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new zt;return this.send(e)}}throw new Jn(f.status,`Error POSTing to endpoint: ${g}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,f.status===202){await((o=f.body)===null||o===void 0?void 0:o.cancel()),S9(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(g=>{var b;return(b=this.onerror)===null||b===void 0?void 0:b.call(this,g)});return}const y=(Array.isArray(e)?e:[e]).filter(g=>"method"in g&&"id"in g&&g.id!==void 0).length>0,_=f.headers.get("content-type");if(y)if(_?.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:p},!1);else if(_?.includes("application/json")){const g=await f.json(),b=Array.isArray(g)?g.map(k=>$r.parse(k)):[$r.parse(g)];for(const k of b)(a=this.onmessage)===null||a===void 0||a.call(this,k)}else throw await((i=f.body)===null||i===void 0?void 0:i.cancel()),new Jn(-1,`Unexpected content type: ${_}`);else await((l=f.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,s;if(this._sessionId)try{const o=await this._commonHeaders(),a={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,a);if(await((n=i.body)===null||n===void 0?void 0:n.cancel()),!i.ok&&i.status!==405)throw new Jn(i.status,`Failed to terminate session: ${i.statusText}`);this._sessionId=void 0}catch(o){throw(s=this.onerror)===null||s===void 0||s.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}}const i6="mcp";class l0{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,i6),this._socket.onerror=n=>{var s;const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),(s=this.onerror)===null||s===void 0||s.call(this,o)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var n;(n=this.onclose)===null||n===void 0||n.call(this)},this._socket.onmessage=n=>{var s,o;let a;try{a=$r.parse(JSON.parse(n.data))}catch(i){(s=this.onerror)===null||s===void 0||s.call(this,i);return}(o=this.onmessage)===null||o===void 0||o.call(this,a)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,n)=>{var s;if(!this._socket){n(new Error("Not connected"));return}(s=this._socket)===null||s===void 0||s.send(JSON.stringify(e)),r()})}}function Xa(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Xa=function(){return t},Xa()}(function(t,e){const r=Qe,n=Qe,s=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(n(429))/5)+parseInt(n(423))/6*(-parseInt(n(418))/7)+-parseInt(n(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(Xa,650197);const c0=()=>{const t=Qe,e={EGhzU:function(r,n){return r!==n},kIrDB:"undefined",llYQe:function(r,n){return r!==n},PZfJg:function(r,n){return r(n)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},l6=(t,e,r)=>{const n=Qe,s=Qe,o={};o[n(410)]=s(398),o.dBkaX=function(i,l){return i===l},o[s(393)]="function";const a=o;typeof window!==a[s(410)]?t.postMessage(e,"*",r):s(428)in t&&a.dBkaX(typeof t.postMessage,a[n(393)])&&t.postMessage(e,r)},c6=(t,e)=>{const r=Qe,n=Qe,s={};s.MbsGh="addEventListener",s.PPniK=function(a,i){return a===i},s[r(419)]=n(412),s[n(404)]="onmessage",s[r(397)]="undefined";const o=s;o.MbsGh in t&&o.PPniK(typeof t[r(427)],o.wRKyh)?t[r(427)](r(400),e):o.thraG in t&&typeof t[n(413)]!==o[n(397)]&&(t.onmessage=e)};class Xs{constructor(e){const r=Qe;this[r(406)]=e}async start(){const e=Qe,r=Qe;this[e(406)]&&(this[e(406)][e(413)]=n=>{var s,o;const a=e,i=r;try{const l=$r[a(402)](n.data[a(400)]);(s=this[a(413)])==null||s.call(this,l,n[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(o=this[i(408)])==null||o.call(this,c)}},this._port[e(396)]=n=>{var s;const o=r,a=r,i=new Error(o(394)+JSON[a(395)](n));(s=this.onerror)==null||s.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const n={lEyuq:function(s){return s()},YihNw:function(s,o){return s(o)}};return new Promise((s,o)=>{var a;const i=Qe,l=Qe;try{const c={};c[i(403)]=r?.[i(403)];const u={};u[l(400)]=e,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),n.lEyuq(s)}catch(c){const u=c instanceof Error?c:new Error(n.YihNw(String,c));(a=this[l(408)])==null||a.call(this,u),o(u)}})}async close(){var e,r;const n=Qe,s=Qe;(e=this._port)==null||e[n(431)](),this._port=void 0,(r=this[s(420)])==null||r.call(this)}}class Tc extends Xs{constructor(e,r=c0()){const n=Qe,s=Qe,o={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[n(391)]=e,this[s(401)]=r;const a=new MessageChannel;this[s(406)]=a.port1,o[s(426)](l6,this[n(401)],{endpoint:this[s(391)]},[a[s(414)]])}}class Cc extends Xs{constructor(e,r=c0()){const n=Qe,s={mOWMr:function(o,a){return o===a},kgkem:function(o,a,i){return o(a,i)}};super(),this._endpoint=e,this._globalObject=r,this[n(432)]=new Promise(o=>{const a=n,i=n;s[a(392)](c6,this[i(401)],l=>{const c=i,u=i;l.data&&s[c(425)](l.data[u(422)],this[u(391)])&&(this[u(406)]=l.ports[-1*4852+1*1601+3251],o())})})}async listen(){return this[Qe(432)]}}function Qe(t,e){const r=Xa();return Qe=function(n,s){return n=n-(17*-491+-669+9407),r[n]},Qe(t,e)}const u6=()=>{const t=new MessageChannel;return[new Xs(t.port1),new Xs(t.port2)]};(function(t,e){const r=Fe,n=Fe,s=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(n(357))/5+-parseInt(n(389))/6*(-parseInt(r(396))/7)+parseInt(n(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ei,-763475+-52067*10+1724410);const d6=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a[s(345)]="tools/list",a.rqstG="tools/call",a.WqUnk="resources/list",a[s(329)]=o(358),a[s(365)]=s(335),a.ookoz="resources/unsubscribe",a[s(385)]=s(340),a.VTIWq="prompts/list",a.SkoRK=s(376),a.QUtUV=s(388),a.XtowM=o(332);const i=a,{id:l,method:c,params:u}=r;let p={};switch(c){case i[o(345)]:p=await e.listTools(u);break;case i.rqstG:p=await e.callTool(u);break;case i[s(334)]:p=await e[s(350)](u);break;case i[o(329)]:p=await e.listResourceTemplates(u);break;case s(372):p=await e[s(383)](u);break;case i.HgYgW:p=await e.subscribeResource(u);break;case i.ookoz:p=await e.unsubscribeResource(u);break;case i[s(385)]:p=await e.getPrompt(u);break;case i.VTIWq:p=await e.listPrompts(u);break;case i[s(344)]:p=await e[s(376)]();break;case i.QUtUV:p=await e.complete(u);break;case s(390):p=await e[s(336)](u?.level);break}const h={};h[s(361)]=p,h[s(394)]=i[s(364)],h.id=l,await((n=t?.transport)==null?void 0:n[s(392)](h))},p6=async(t,e,r)=>{var n;const s=Fe,o=Fe,a={};a.jQBBS="sampling/createMessage",a.EZqgC="elicitation/create",a[s(370)]=o(376),a.aVeaL=o(332);const i=a,{id:l,method:c,params:u}=r;let p={};switch(c){case s(368):const d={};d.method=c,d[o(367)]=u,p=await e.request(d,Fl);break;case i[o(391)]:const f={};f.method=c,f[o(367)]=u,p=await e[o(381)](f,Da);break;case i.EZqgC:const w={};w.method=c,w.params=u,p=await e.request(w,Fs);break;case i[o(370)]:const m={};m.method=c,p=await e[o(381)](m,Zr);break}const h={};return h[o(361)]=p,h.jsonrpc=i[o(387)],h.id=l,await((n=t?.[s(371)])==null?void 0:n.send(h)),p},f6=(t,e)=>{const r=Fe,n={gXsjT:function(o,a){return o===a},oegpC:r(351),lZOUC:function(o,a,i,l){return o(a,i,l)},ifIKG:"2.0"},s=t._onrequest;t._onrequest=async(o,a)=>{var i,l,c,u,p;const h=r,d=r,{id:f,method:w}=o;try{n[h(333)](w,n.oegpC)?await s[h(386)](t,o,a):await n.lZOUC(d6,t,e,o)}catch(m){const{code:y,message:_,data:g}=m;try{if(y){const b={};b.code=y,b.message=_,b.data=g;const k={};k.error=b,k[h(394)]=n[d(331)],k.id=f,await((i=t?.transport)==null?void 0:i.send(k))}else(c=(l=t?.[d(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(b){(p=(u=t?.[h(371)])==null?void 0:u.onerror)==null||p.call(u,b)}}}},h6=(t,e)=>{const r=Fe,n=Fe,s={};s[r(363)]=function(a,i){return a!==i},s[r(398)]=r(353),s.hzhyg="notifications/cancelled";const o=s;t._onnotification=async a=>{var i,l;const c=r,u=n,{method:p,params:h}=a;if(o[c(363)](p,o[u(398)])&&(o[c(363)](p,o.hzhyg)||h?.forward))try{await e.notification(a)}catch(d){(l=(i=t?.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},m6=(t,e)=>async r=>{var n,s,o,a,i;const l=Fe,c=Fe,u={};u.SEmWX=l(332);const p=u;try{return await p6(t,e,r)}catch(h){const{code:d,message:f,data:w}=h;try{if(d){const m={};m[c(377)]=d,m.message=f,m.data=w;const y={};y[c(348)]=m,y.jsonrpc=p[l(338)],y.id=r.id,await((n=t?.transport)==null?void 0:n[c(392)](y))}else(o=(s=t?.transport)==null?void 0:s[c(339)])==null||o.call(s,h)}catch(m){(i=(a=t?.[l(371)])==null?void 0:a[c(339)])==null||i.call(a,m)}}},g6=(t,e)=>async r=>{var n,s,o;const a=Fe,i=Fe,l={};l.dtUgZ=function(h,d){return h!==d},l.jgCIb=a(353),l.uUjKY="2.0";const c=l,{method:u,params:p}=r;if(c.dtUgZ(u,c.jgCIb)&&(u!==a(400)||p?.forward))try{const h={...r};h[a(394)]=c[i(352)],await((n=e?.[a(371)])==null?void 0:n[a(392)](h))}catch(h){(o=(s=t?.[a(371)])==null?void 0:s[i(339)])==null||o.call(s,h)}};function Fe(t,e){const r=ei();return Fe=function(n,s){return n=n-(-1017+-1439*-1+-97),r[n]},Fe(t,e)}const v6=(t,e)=>async r=>{var n,s,o,a,i,l;const c=Fe,u=Fe,p={};p[c(401)]=u(332);const h=p;try{await((n=e?.transport)==null?void 0:n.send(r))}catch(d){const{code:f,message:w,data:m}=d;try{if(f){const y={};y.code=f,y[c(399)]=w,y.data=m;const _={};_[c(348)]=y,_[c(394)]=h.OhJjz,_.id=r.id,await((s=t?.[c(371)])==null?void 0:s.send(_))}else(a=(o=t?.transport)==null?void 0:o[u(339)])==null||a.call(o,d)}catch(y){(l=(i=t?.transport)==null?void 0:i.onerror)==null||l.call(i,y)}}},$c=()=>{const t=Fe,e=Fe,r={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},n=[],s=(c,u)=>{const p=Fe,h=Fe;if(u){const d=[];for(const f of n)try{d.push(f(c,u))}catch{}for(const f of d)if(r[p(379)](f,null))return f}else for(const d of n)try{r[h(343)](d,c)}catch{}},o=c=>{const u=Fe;r[u(384)](typeof c,u(369))&&!n.includes(c)&&n.push(c)},a=c=>{const u=n.indexOf(c);u!==-1&&n.splice(u,1*-6854+-264+7119)},i=()=>{const c=Fe;n[c(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=s,l[e(330)]=o,l.removeListener=a,l[t(359)]=i,l},_6=t=>{const e=Fe,r=Fe,n={xwPeb:function(s){return s()},Mfvzm:function(s){return s()}};{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(326)]($c);t._onresponse=s,t[e(395)]=o,t.removeResponseListener=a,t.clearResponseListener=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[r(326)]($c);t[r(328)]=s,t.addRequestListener=o,t[r(354)]=a,t[r(341)]=i}{const{handleListener:s,addListener:o,removeListener:a,clearListener:i}=n[e(375)]($c);t[e(342)]=s,t[e(327)]=o,t.removeNotificationListener=a,t.clearNotificationListener=i}};function ei(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return ei=function(){return t},ei()}const y6=(t,{beforeInit:e,afterInit:r}={})=>{const n=Fe,s=Fe,o={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:n(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},a=new Map(t._notificationHandlers);t[n(393)][n(402)](),t._notificationHandlers[n(402)](),o.tqDZP(typeof e,o[n(380)])&&e(),o[n(362)](t._onresponse.name,o[n(360)])&&(t[s(349)]=t._onresponse),o[n(347)](_6,t),t.addResponseListener(i=>{const l=s;t.originalOnResponse[l(386)](t,i)}),o.tqDZP(typeof r,o[s(380)])&&o[n(397)](r),t[s(327)](i=>{const{method:l}=i,c=a.get(l);o.tqDZP(typeof c,o.cjSoZ)&&c(i)})},w6=lr,b6=lr;(function(t,e){const r=lr,n=lr,s=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(n(398))/4+parseInt(r(390))/5*(parseInt(n(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(n(395))/9)+parseInt(n(399))/10*(parseInt(n(385))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ti,-1*-881393+2*180895+1*-644809);function lr(t,e){const r=ti();return lr=function(n,s){return n=n-(-1861+-499*4+4241),r[n]},lr(t,e)}function ti(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return ti=function(){return t},ti()}const k6=()=>{const t=lr,e=lr,r={};r.REzPF=function(s,o){return s&o},r.suJHI=function(s,o){return s===o},r[t(386)]=function(s,o){return s&o},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():n.dHTfU.replace(/[xy]/g,s=>{const o=t,a=t,i=n[o(392)](crypto[o(384)](new Uint8Array(8663+2*-4331))[741*2+-1385*-2+4252*-1],15);return(n.suJHI(s,"x")?i:n[a(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},S6=t=>{const e=lr,r=lr,n=new Uint8Array(t);return crypto.getRandomValues(n),Array[e(401)](n,s=>s[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},Vr={};Vr[w6(391)]=k6,Vr[b6(396)]=S6;const Pt=cr;(function(t,e){const r=cr,n=cr,s=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(n(499))/2)+parseInt(n(543))/3*(parseInt(n(514))/4)+parseInt(r(502))/5*(parseInt(n(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(ri,1472653*1+-2*-897917+-2275789);const T6=(t,e)=>{const r=cr,n=cr,s={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};f6(t,e),h6(t,e);const o=m6(e,t),a=s[r(510)](v6,e,t),i=s[n(549)](g6,e,t);e[n(537)](o),e[r(519)](a),e.addNotificationListener(i),t[n(556)]=()=>{const l=n;e.removeRequestListener(o),e[l(530)](a),e[l(529)](i)}},Ec=(t,e,r)=>{const n=cr,s={pMiva:function(i,l){return i instanceof l},TeTEy:n(546),fyZbd:function(i,l,c){return i(l,c)}},o=()=>{var i;const l=n;s.pMiva(r,Ys)&&((i=r._eventSource)==null||i.addEventListener(s[l(547)],()=>{var c;const u=l;(c=r[u(509)])==null||c[u(546)]()})),T6(t,e)},a={};a.afterInit=o,s.fyZbd(y6,e,a)},u0=(t,e=Vr.randomUUID())=>{const r=cr,n=cr,s={OfssH:function(u,p,h){return u(p,h)}},o={};o[r(528)]=e;const a=o,i={};i[r(528)]=e;const l={};l[n(558)]=i,l[r(534)]=r(524);const c={requestInit:l,eventSourceInit:{async fetch(u,p){const h=r,d=n,f=new Headers(p?.[h(558)]||{});Object.entries(a)[d(498)](([m,y])=>{f[d(527)](m,y)});const w={...p};return w[d(558)]=f,s.OfssH(fetch,u,w)},withCredentials:!0}};return t&&(c.requestInit[r(558)].Authorization=r(533)+t,a.Authorization="Bearer "+t),c},d0=(t,e=Vr[Pt(517)]())=>{const r=Pt,n=Pt,s={};s.nwQhY="include";const o=s,a={};a["stream-session-id"]=e;const i={};i.headers=a,i.credentials=o[r(520)];const l={};l[r(544)]=i;const c=l;return t&&(c.requestInit.headers[n(552)]=n(533)+t),c},xc=async(t,e,r)=>{const n=Pt,s=Pt,o={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},a=o.CFfFC(r);try{return await t[n(538)](a),a}catch(i){if(i instanceof zt){const l=await e();return await a[s(505)](l),await o[n(525)](xc,t,e,r)}else throw i}};function cr(t,e){const r=ri();return cr=function(n,s){return n=n-498,r[n]},cr(t,e)}const p0=(t,e)=>{const r=Pt,n=Pt,s={};s.RsKXs=function(a,i){return a in i},s.PBhps="waitForOAuthCode",s[r(535)]="function",s[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const o=s;if(o.RsKXs(o[n(551)],t))return t[n(523)];if(typeof e===o.yTKoP)return e;throw new Error(o.RZhOv)},C6=async t=>{const e=Pt,r=Pt,n={TFSRn:function(I,A,P){return I(A,P)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(I){return I()},WIVYl:function(I,A,P,D){return I(A,P,D)},jniGY:"sessionId"},{client:s,url:o,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:p}=t,h={};h.authProvider=l,h.requestInit=c,h.eventSourceInit=u;const d=h,f=i||Vr.randomUUID(),w=n[e(506)](u0,a,f);if(c){const I={...w.requestInit,...c};I.headers={...w[e(544)].headers,...c.headers},d.requestInit=I}else d[r(544)]=w.requestInit;if(u){const I={...w[e(559)],...u};d.eventSourceInit=I}else d.eventSourceInit=w.eventSourceInit;const m={};m.listChanged=!0;const y={};y.roots=m,y.sampling={},y[e(511)]={};const _=y,g={};g[r(536)]=n.HwvVa,g.version=e(526);const b={};b.capabilities=_;const k=new Bs(g,b),S=()=>new Ys(new URL(o),d);let T=n[r(504)](S);if(l){const I=n[e(506)](p0,l,p);T=await n[r(513)](xc,k,I,S)}else await k[e(538)](T);n[r(513)](Ec,k,s,T),T[r(557)]=T[r(542)].searchParams[r(532)](n.jniGY);const x={};return x.transport=T,x.sessionId=T[e(557)],x};function ri(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return ri=function(){return t},ri()}const $6=async t=>{const e=Pt,r=Pt,n={Vajmx:e(500),biJOc:function(I){return I()},zXcpO:function(I,A,P){return I(A,P)},zDnjZ:function(I,A,P,D){return I(A,P,D)},FQMAh:function(I,A,P,D){return I(A,P,D)}},{client:s,url:o,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:p}=t,h={};h.authProvider=l,h.requestInit=c,h.reconnectionOptions=u;const d=h,f=i||Vr.randomUUID(),w=d0(a,f);if(c){const I={...w.requestInit,...c};I.headers={...w.requestInit.headers,...c.headers},d[e(544)]=I}else d.requestInit=w.requestInit;const m={};m.listChanged=!0;const y={};y[r(550)]=m,y.sampling={},y.elicitation={};const _=y,g={};g[e(536)]=n[r(508)],g[e(555)]="1.0.0";const b={};b.capabilities=_;const k=new Bs(g,b),S=()=>new Qs(new URL(o),d);let T=n[e(503)](S);if(l){const I=n[e(501)](p0,l,p);T=await n.zDnjZ(xc,k,I,S)}else await k.connect(T);n.FQMAh(Ec,k,s,T);const x={};return x.transport=T,x[r(557)]=T.sessionId,x},E6=async t=>{const e=Pt,r=Pt,n={QgzDy:e(540),jkaVB:function(y,_,g,b){return y(_,g,b)}},{client:s,url:o,token:a,sessionId:i}=t,l={};l.listChanged=!0;const c={};c[e(550)]=l,c[e(515)]={},c[r(511)]={};const u=c,p={};p.name=n[r(548)],p[r(555)]=r(526);const h={};h.capabilities=u;const d=new Bs(p,h),f=i||Vr[r(517)](),w=new l0(new URL(o+e(522)+f+r(554)+a));await d.connect(w),n.jkaVB(Ec,d,s,w);const m={};return m[e(512)]=w,m[r(557)]=f,m},eo=Ct,ni=Ct;function Ct(t,e){const r=si();return Ct=function(n,s){return n=n-(-16761+51*337),r[n]},Ct(t,e)}(function(t,e){const r=Ct,n=Ct,s=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(n(449))/5)+-parseInt(n(455))/6+-parseInt(r(427))/7+-parseInt(n(438))/8*(parseInt(n(459))/9)+parseInt(r(430))/10*(parseInt(n(436))/11)===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(si,-220880+1*-333337+-2*-384996);function si(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return si=function(){return t},si()}const x6=()=>Vr.randomBytes(3485*1+-261+-3184);class I6{constructor(e){const r=Ct,n=Ct;this._callBackPromise={};const{clientMetadata:s,state:o,redirectCallback:a,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=s,this[r(454)]=s[r(445)][0],this._state=o||x6(),this._redirectCallback=a||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[n(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,n,s,o,a,i;const l=Ct,c=Ct,u={qITTp:function(f,w,m){return f(w,m)},qcFPW:l(452)},p=await u.qITTp(fetch,e,{method:u[l(453)]});!p.ok&&((n=(r=this._callBackPromise).reject)==null||n.call(r,c(446)+p.statusText));const h=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!h.ok){(o=(s=this[l(433)]).reject)==null||o.call(s,"Failed to fetch auth code: "+h.statusText);return}const d=await h[l(431)]();(i=(a=this[c(433)])[l(456)])==null||i.call(a,d[l(432)])}async getAuthCodeByStateFunction(e,r){const n=Ct,s=Ct,o={};o.tuSmb=n(429);const a=o,i={};i[n(460)]=a.tuSmb;const l={};return l[s(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=Ct,r=this[e(433)];return()=>new Promise((n,s)=>{const o=e;r.resolve=n,r[o(434)]=s})}get redirectUrl(){return this[Ct(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[eo(447)](){return this[eo(444)]}[ni(435)](e){const r=eo;this[r(444)]=e}[ni(457)](){return this[ni(439)]}saveTokens(e){this._tokens=e}[ni(450)](e){this[eo(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[eo(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=ai,n=ai,s=t();;)try{var o=parseInt(r(361))/1*(parseInt(n(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(n(354))/6*(parseInt(r(360))/7)+parseInt(n(362))/8+parseInt(n(364))/9+-parseInt(n(356))/10*(parseInt(r(355))/11);if(o===e)break;s.push(s.shift())}catch{s.push(s.shift())}})(oi,-73523*-3+1*-407717+530518);function oi(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return oi=function(){return t},oi()}function ai(t,e){var r=oi();return ai=function(n,s){n=n-(-1*-642+503*-5+2227);var o=r[n];return o},ai(t,e)}class R6{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}class P6 extends Dh{constructor(e,r){var n,s;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ja.options.map((o,a)=>[o,a])),this.isMessageIgnored=(o,a)=>{const i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._instructions=r?.instructions,this._jsonSchemaValidator=(s=r?.jsonSchemaValidator)!==null&&s!==void 0?s:new Bh,this.setRequestHandler(rh,o=>this._oninitialize(o)),this.setNotificationHandler(bl,()=>{var o;return(o=this.oninitialized)===null||o===void 0?void 0:o.call(this)}),this._capabilities.logging&&this.setRequestHandler(qa,async(o,a)=>{var i;const l=a.sessionId||((i=a.requestInfo)===null||i===void 0?void 0:i.headers["mcp-session-id"])||void 0,{level:c}=o.params,u=ja.safeParse(c);return u.success&&this._loggingLevels.set(l,u.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new R6(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zh(this._capabilities,e)}setRequestHandler(e,r){var n,s,o;const a=zn(e),i=a?.method;if(!i)throw new Error("Schema is missing a method literal");let l;if(qt(i)){const u=i,p=(n=u._zod)===null||n===void 0?void 0:n.def;l=(s=p?.value)!==null&&s!==void 0?s:u.value}else{const u=i,p=u._def;l=(o=p?.value)!==null&&o!==void 0?o:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");if(l==="tools/call"){const u=async(p,h)=>{const d=Ht(La,p);if(!d.success){const y=d.error instanceof Error?d.error.message:String(d.error);throw new ne(ae.InvalidParams,`Invalid tools/call request: ${y}`)}const{params:f}=d.data,w=await Promise.resolve(r(p,h));if(f.task){const y=Ht(Ln,w);if(!y.success){const _=y.error instanceof Error?y.error.message:String(y.error);throw new ne(ae.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}const m=Ht(qn,w);if(!m.success){const y=m.error instanceof Error?m.error.message:String(m.error);throw new ne(ae.InvalidParams,`Invalid tools/call result: ${y}`)}return m.data};return super.setRequestHandler(e,u)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){var r,n,s;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((s=this._clientCapabilities)===null||s===void 0)&&s.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){var r,n;switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!(!((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.elicitation)===null||n===void 0)&&n.url))throw new Error(`Client does not support URL elicitation (required for ${e})`);break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break}}assertTaskCapability(e){var r,n;Gh((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,e,"Client")}assertTaskHandlerCapability(e){var r;this._capabilities&&Jh((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,e,"Server")}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Gf.includes(r)?r:js,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Zr)}async createMessage(e,r){var n,s;if((e.tools||e.toolChoice)&&!(!((s=(n=this._clientCapabilities)===null||n===void 0?void 0:n.sampling)===null||s===void 0)&&s.tools))throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const o=e.messages[e.messages.length-1],a=Array.isArray(o.content)?o.content:[o.content],i=a.some(p=>p.type==="tool_result"),l=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=l?Array.isArray(l.content)?l.content:[l.content]:[],u=c.some(p=>p.type==="tool_use");if(i){if(a.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){const p=new Set(c.filter(d=>d.type==="tool_use").map(d=>d.id)),h=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(p.size!==h.size||![...p].every(d=>h.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},kh,r):this.request({method:"sampling/createMessage",params:e},Da,r)}async elicitInput(e,r){var n,s,o,a,i;switch((n=e.mode)!==null&&n!==void 0?n:"form"){case"url":{if(!(!((o=(s=this._clientCapabilities)===null||s===void 0?void 0:s.elicitation)===null||o===void 0)&&o.url))throw new Error("Client does not support url elicitation.");const c=e;return this.request({method:"elicitation/create",params:c},Fs,r)}case"form":{if(!(!((i=(a=this._clientCapabilities)===null||a===void 0?void 0:a.elicitation)===null||i===void 0)&&i.form))throw new Error("Client does not support form elicitation.");const c=e.mode==="form"?e:{...e,mode:"form"},u=await this.request({method:"elicitation/create",params:c},Fs,r);if(u.action==="accept"&&u.content&&c.requestedSchema)try{const h=this._jsonSchemaValidator.getValidator(c.requestedSchema)(u.content);if(!h.valid)throw new ne(ae.InvalidParams,`Elicitation response content does not match requested schema: ${h.errorMessage}`)}catch(p){throw p instanceof ne?p:new ne(ae.InternalError,`Error validating elicitation response: ${p instanceof Error?p.message:String(p)}`)}return u}}}createElicitationCompletionNotifier(e,r){var n,s;if(!(!((s=(n=this._clientCapabilities)===null||n===void 0?void 0:n.elicitation)===null||s===void 0)&&s.url))throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Fl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const Ic=Symbol.for("mcp.completable");function O6(t,e){return Object.defineProperty(t,Ic,{value:{complete:e},enumerable:!1,writable:!1,configurable:!1}),t}function A6(t){return!!t&&typeof t=="object"&&Ic in t}function M6(t){const e=t[Ic];return e?.complete}var f0;(function(t){t.Completable="McpCompletable"})(f0||(f0={}));const h0=1e6,Rc=1e6,m0=1e4,N6=1e6;class xr{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){xr.validateLength(e,h0,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let n="",s=0,o=0;for(;s<e.length;)if(e[s]==="{"){n&&(r.push(n),n="");const a=e.indexOf("}",s);if(a===-1)throw new Error("Unclosed template expression");if(o++,o>m0)throw new Error(`Template contains too many expressions (max ${m0})`);const i=e.slice(s+1,a),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),p=u[0];for(const h of u)xr.validateLength(h,Rc,"Variable name");r.push({name:p,operator:l,names:u,exploded:c}),s=a+1}else n+=e[s],s++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return xr.validateLength(e,Rc,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const a=e.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(c.toString(),e.operator);return`${l}=${u}`}).filter(l=>l.length>0);return a.length===0?"":(e.operator==="?"?"?":"&")+a.join("&")}if(e.names.length>1){const a=e.names.map(i=>r[i]).filter(i=>i!==void 0);return a.length===0?"":a.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=r[e.name];if(n===void 0)return"";const o=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let r="",n=!1;for(const s of this.parts){if(typeof s=="string"){r+=s;continue}const o=this.expandPart(s,e);o&&((s.operator==="?"||s.operator==="&")&&n?r+=o.replace("?","&"):r+=o,(s.operator==="?"||s.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const o of e.names)xr.validateLength(o,Rc,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){const a=e.names[o],i=o===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n;const s=e.name;switch(e.operator){case"":n=e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:s}),r}match(e){xr.validateLength(e,h0,"URI");let r="^";const n=[];for(const i of this.parts)if(typeof i=="string")r+=this.escapeRegExp(i);else{const l=this.partToRegExp(i);for(const{pattern:c,name:u}of l)r+=c,n.push({name:u,exploded:i.exploded})}r+="$",xr.validateLength(r,N6,"Generated regex pattern");const s=new RegExp(r),o=e.match(s);if(!o)return null;const a={};for(let i=0;i<n.length;i++){const{name:l,exploded:c}=n[i],u=o[i+1],p=l.replace("*","");c&&u.includes(",")?a[p]=u.split(","):a[p]=u}return a}}const L6=/^[A-Za-z0-9._-]{1,128}$/;function j6(t){const e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!L6.test(t)){const r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function q6(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(const r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function g0(t){const e=j6(t);return q6(t,e.warnings),e.isValid}class z6{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){const s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}class v0{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new P6(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new z6(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Hr(zl)),this.server.assertCanSetRequestHandler(Hr(La)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zl,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const n={name:e,title:r.title,description:r.description,inputSchema:(()=>{const s=Hs(r.inputSchema);return s?jh(s,{strictUnions:!0,pipeStrategy:"input"}):U6})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const s=Hs(r.outputSchema);s&&(n.outputSchema=jh(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(La,async(e,r)=>{var n;try{const s=this._registeredTools[e.params.name];if(!s)throw new ne(ae.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new ne(ae.InvalidParams,`Tool ${e.params.name} disabled`);const o=!!e.params.task,a=(n=s.execution)===null||n===void 0?void 0:n.taskSupport,i="createTask"in s.handler;if((a==="required"||a==="optional")&&!i)throw new ne(ae.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!o)throw new ne(ae.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(s,e,r);const l=await this.validateToolInput(s,e.params.arguments,e.params.name),c=await this.executeToolHandler(s,l,r);return o||await this.validateToolOutput(s,c,e.params.name),c}catch(s){if(s instanceof ne&&s.code===ae.UrlElicitationRequired)throw s;return this.createToolError(s instanceof Error?s.message:String(s))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;const s=Hs(e.inputSchema),o=s??e.inputSchema,a=await Vl(o,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Hl(i);throw new ne(ae.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new ne(ae.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const s=Hs(e.outputSchema),o=await Vl(s,r.structuredContent);if(!o.success){const a="error"in o?o.error:"Unknown error",i=Hl(a);throw new ne(ae.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(e,r,n){const s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(e.inputSchema){const i=s;return await Promise.resolve(i.createTask(r,a))}else{const i=s;return await Promise.resolve(i.createTask(a))}}if(e.inputSchema){const a=s;return await Promise.resolve(a(r,n))}else{const a=s;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(e,r,n){var s;if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(e,r.params.arguments,r.params.name),a=e.handler,i={...n,taskStore:n.taskStore},l=o?await Promise.resolve(a.createTask(o,i)):await Promise.resolve(a.createTask(i)),c=l.task.taskId;let u=l.task;const p=(s=u.pollInterval)!==null&&s!==void 0?s:5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(d=>setTimeout(d,p));const h=await n.taskStore.getTask(c);if(!h)throw new ne(ae.InternalError,`Task ${c} not found during polling`);u=h}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Hr(Zl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Zl,async e=>{switch(e.params.ref.type){case"ref/prompt":return w4(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return b4(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ne(ae.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const n=this._registeredPrompts[r.name];if(!n)throw new ne(ae.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ne(ae.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return to;const s=zn(n.argsSchema),o=s?.[e.params.argument.name];if(!A6(o))return to;const a=M6(o);if(!a)return to;const i=await a(e.params.argument.value,e.params.context);return w0(i)}async handleResourceCompletion(e,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return to;throw new ne(ae.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return to;const o=await s(e.params.argument.value,e.params.context);return w0(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Hr(Na)),this.server.assertCanSetRequestHandler(Hr(Rl)),this.server.assertCanSetRequestHandler(Hr(Ol)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Na,async(e,r)=>{const n=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),s=[];for(const o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;const a=await o.resourceTemplate.listCallback(r);for(const i of a.resources)s.push({...o.metadata,...i})}return{resources:[...n,...s]}}),this.server.setRequestHandler(Rl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ol,async(e,r)=>{const n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new ne(ae.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(const o of Object.values(this._registeredResourceTemplates)){const a=o.resourceTemplate.uriTemplate.match(n.toString());if(a)return o.readCallback(n,a,r)}throw new ne(ae.InvalidParams,`Resource ${n} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Hr(Al)),this.server.assertCanSetRequestHandler(Hr(Ml)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Al,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?F6(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ml,async(e,r)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new ne(ae.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new ne(ae.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const s=Hs(n.argsSchema),o=await Vl(s,e.params.arguments);if(!o.success){const l="error"in o?o.error:"Unknown error",c=Hl(l);throw new ne(ae.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}const a=o.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const s=n.callback;return await Promise.resolve(s(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());const o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const a=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){const a={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==n&&(delete this._registeredResources[n],i.uri&&(this._registeredResources[i.uri]=a)),typeof i.name<"u"&&(a.name=i.name),typeof i.title<"u"&&(a.title=i.title),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,s,o){const a={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.template<"u"&&(a.resourceTemplate=i.template),typeof i.metadata<"u"&&(a.metadata=i.metadata),typeof i.callback<"u"&&(a.readCallback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,a}_createRegisteredPrompt(e,r,n,s,o){const a={title:r,description:n,argsSchema:s===void 0?void 0:Vs(s),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=a)),typeof i.title<"u"&&(a.title=i.title),typeof i.description<"u"&&(a.description=i.description),typeof i.argsSchema<"u"&&(a.argsSchema=Vs(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,a}_createRegisteredTool(e,r,n,s,o,a,i,l,c){g0(e);const u={title:r,description:n,inputSchema:y0(s),outputSchema:y0(o),annotations:a,execution:i,_meta:l,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&g0(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Vs(p.paramsSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const l=r[0];Pc(l)?(s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Pc(r[0])&&(a=r.shift())):typeof l=="object"&&l!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,n,s,o,a,{taskSupport:"forbidden"},void 0,i)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:o,inputSchema:a,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(e,s,o,a,i,l,{taskSupport:"forbidden"},c,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());const o=r[0],a=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:o,argsSchema:a}=r,i=this._createRegisteredPrompt(e,s,o,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class D6{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new xr(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){var r;return(r=this._callbacks.complete)===null||r===void 0?void 0:r[e]}}const U6={type:"object",properties:{}};function _0(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Z6(t){return"_def"in t||"_zod"in t||_0(t)}function Pc(t){return typeof t!="object"||t===null||Z6(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(_0)}function y0(t){if(t)return Pc(t)?Vs(t):t}function F6(t){const e=zn(t);return e?Object.entries(e).map(([r,n])=>{const s=$4(n),o=E4(n);return{name:r,description:s,required:!o}}):[]}function Hr(t){const e=zn(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Eh(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function w0(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const to={completion:{values:[],hasMore:!1}};function V6(t){var e;return t.title!==void 0&&t.title!==""?t.title:"annotations"in t&&(!((e=t.annotations)===null||e===void 0)&&e.title)?t.annotations.title:t.name}class ro{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new ro,r=new ro;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(var e;this._messageQueue.length>0;){const r=this._messageQueue.shift();(e=this.onmessage)===null||e===void 0||e.call(this,r.message,r.extra)}}async close(){var e;const r=this._otherTransport;this._otherTransport=void 0,await r?.close(),(e=this.onclose)===null||e===void 0||e.call(this)}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r?.authInfo}})}}class H6{constructor(e,r){const n={name:"web-mcp-server",version:"1.0.0"},s={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new v0(e||n,r||{capabilities:s}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=o=>{this.onerror?.(o)},this.server.server.setRequestHandler(qa,async()=>({}))}async connect(e){return typeof e.start=="function"?(this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new Cc(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,n){return this.server.registerTool(e,r,n)}registerPrompt(e,r,n){return this.server.registerPrompt(e,r,n)}registerResource(e,r,n,s){return typeof r=="string"?this.server.registerResource(e,r,n,s):this.server.registerResource(e,r,n,s)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(e,r){return await this.server.server.createMessage(e,r)}async elicitInput(e,r){return await this.server.server.elicitInput(e,r)}async listRoots(e,r){return await this.server.server.listRoots(e,r)}async sendLoggingMessage(e){return await this.server.server.sendLoggingMessage(e)}async sendResourceUpdated(e){return await this.server.server.sendResourceUpdated(e)}request(e,r,n){return this.server.server.request(e,r,n)}async notification(e,r){return await this.server.server.notification(e,r)}setRequestHandler(e,r){this.server.server.setRequestHandler(e,r)}removeRequestHandler(e){this.server.server.removeRequestHandler(e)}setNotificationHandler(e,r){this.server.server.setNotificationHandler(e,r)}removeNotificationHandler(e){this.server.server.removeNotificationHandler(e)}onSubscribe(e){this.server.server.setRequestHandler(ph,e)}onUnsubscribe(e){this.server.server.setRequestHandler(fh,e)}onSetLogLevel(e){this.server.server.setRequestHandler(qa,e)}onListResources(e){this.server.server.setRequestHandler(Na,e)}onRootsListChanged(e){this.server.server.setNotificationHandler(Ch,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const B6=(t,e)=>new Cc(t,e),J6=()=>u6(),G6=t=>t instanceof Cc,W6=t=>t instanceof v0;class b0{constructor(e,r){const n={name:"web-mcp-client",version:"1.0.0"},s={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Bs(e||n,r||{capabilities:s}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=o=>{this.onerror?.(o)}}async connect(e){if(typeof e.start=="function")return this.transport=e,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:s,type:o,agent:a,onError:i}=e;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:s};let p;return await(async()=>{const{transport:d,sessionId:f}=o==="sse"?await C6(u):o==="socket"?await E6(u):await $6(u);d.onerror=async w=>{i?.(w)},p={transport:d,sessionId:f}})(),p}const l=new URL(r);let c;if(o==="channel"&&(c=new Tc(r),await this.client.connect(c)),o==="sse"){const u=u0(n,s);c=new Ys(l,u),await this.client.connect(c)}if(o==="socket"&&(c=new l0(new URL(`${r}?sessionId=${s}&token=${n}`)),c.sessionId=s,await this.client.connect(c)),typeof c>"u"){const u=d0(n,s);c=new Qs(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(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,qn,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,n){return this.client.request(e,r,n)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler(Ul,e)}onCreateMessage(e){this.client.setRequestHandler(Dl,e)}onListRoots(e){this.client.setRequestHandler(Th,e)}onToolListChanged(e){this.client.setNotificationHandler(wh,e)}onPromptListChanged(e){this.client.setNotificationHandler(vh,e)}onResourceListChanged(e){this.client.setNotificationHandler(dh,e)}onResourceUpdated(e){this.client.setNotificationHandler(hh,e)}onLoggingMessage(e){this.client.setNotificationHandler(bh,e)}async onPagehide(e){e.persisted||(k0(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const K6=(t,e)=>new Ys(t,e),Y6=(t,e)=>new Qs(t,e),Q6=(t,e)=>new Tc(t,e),X6=t=>t instanceof Ys,k0=t=>t instanceof Qs,e5=t=>t instanceof Tc,t5=t=>t instanceof Bs,Gn=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},S0=(t,e,r)=>{const n=async function(s){s.source===window&&s.data.type===t&&s.data.direction===r&&await e(s.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},Oc=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(s=>{chrome.tabs.sendMessage(s.id,{type:t,data:e,direction:r,tabId:s.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},Ac=(t,e,r,n)=>{const s=(o,a,i)=>{if(o.type===t&&o.direction===r&&(!n||n&&o.tabId===n)){const{data:l}=o;e(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(s),()=>chrome.runtime.onMessage.removeListener(s)};class T0{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=Ac("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=$r.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){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(e,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 s=n.tabIds[n.tabIds.length-1];Oc("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:s,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const C0=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});class r5{constructor(e=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||C0(),this._messageListener1=S0("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(r=>{console.error("【Page Svr Transport】 notifyRegistration失败:",r)})},"content->page"),this._messageListener2=S0("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=$r.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Gn("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Gn("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&e.result?.content&&Gn("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{Gn("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(e))}}}class n5{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||C0(),this.tabId=r,Ac("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(n=>{console.log("【Content Svr Transport】 notifyRegistration 失败",n)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");Ac("mcp-client-to-server",e=>{if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const r=$r.parse(e.mcpMessage);this.onmessage?.(r),e.mcpMessage.params?.name&&Gn("update-page-app-message",{status:"run",message:e.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),Oc("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&e.result?.content&&Gn("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(e){this._isStarted&&(this._lastRegistration=e,Oc("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(e))}}}var Wn={},Mc,$0;function s5(){return $0||($0=1,Mc=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Mc}var Nc={},Br={},E0;function gn(){if(E0)return Br;E0=1;let t;const e=[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 Br.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},Br.getSymbolTotalCodewords=function(n){return e[n]},Br.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Br.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Br.isKanjiModeEnabled=function(){return typeof t<"u"},Br.toSJIS=function(n){return t(n)},Br}var Lc={},x0;function jc(){return x0||(x0=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,s){if(t.isValid(n))return n;try{return e(n)}catch{return s}}})(Lc)),Lc}var qc,I0;function o5(){if(I0)return qc;I0=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},qc=t,qc}var zc,R0;function a5(){if(R0)return zc;R0=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,r,n,s){const o=e*this.size+r;this.data[o]=n,s&&(this.reservedBit[o]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},zc=t,zc}var Dc={},P0;function i5(){return P0||(P0=1,(function(t){const e=gn().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const s=Math.floor(n/7)+2,o=e(n),a=o===145?26:Math.ceil((o-13)/(2*s-2))*2,i=[o-7];for(let l=1;l<s-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},t.getPositions=function(n){const s=[],o=t.getRowColCoords(n),a=o.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||s.push([o[i],o[l]]);return s}})(Dc)),Dc}var Uc={},O0;function l5(){if(O0)return Uc;O0=1;const t=gn().getSymbolSize,e=7;return Uc.getPositions=function(n){const s=t(n);return[[0,0],[s-e,0],[0,s-e]]},Uc}var Zc={},A0;function c5(){return A0||(A0=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const o=s.size;let a=0,i=0,l=0,c=null,u=null;for(let p=0;p<o;p++){i=l=0,c=u=null;for(let h=0;h<o;h++){let d=s.get(p,h);d===c?i++:(i>=5&&(a+=e.N1+(i-5)),c=d,i=1),d=s.get(h,p),d===u?l++:(l>=5&&(a+=e.N1+(l-5)),u=d,l=1)}i>=5&&(a+=e.N1+(i-5)),l>=5&&(a+=e.N1+(l-5))}return a},t.getPenaltyN2=function(s){const o=s.size;let a=0;for(let i=0;i<o-1;i++)for(let l=0;l<o-1;l++){const c=s.get(i,l)+s.get(i,l+1)+s.get(i+1,l)+s.get(i+1,l+1);(c===4||c===0)&&a++}return a*e.N2},t.getPenaltyN3=function(s){const o=s.size;let a=0,i=0,l=0;for(let c=0;c<o;c++){i=l=0;for(let u=0;u<o;u++)i=i<<1&2047|s.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|s.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*e.N3},t.getPenaltyN4=function(s){let o=0;const a=s.data.length;for(let l=0;l<a;l++)o+=s.data[l];return Math.abs(Math.ceil(o*100/a/5)-10)*e.N4};function r(n,s,o){switch(n){case t.Patterns.PATTERN000:return(s+o)%2===0;case t.Patterns.PATTERN001:return s%2===0;case t.Patterns.PATTERN010:return o%3===0;case t.Patterns.PATTERN011:return(s+o)%3===0;case t.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case t.Patterns.PATTERN101:return s*o%2+s*o%3===0;case t.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case t.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}t.applyMask=function(s,o){const a=o.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)o.isReserved(l,i)||o.xor(l,i,r(s,l,i))},t.getBestMask=function(s,o){const a=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){o(c),t.applyMask(c,s);const u=t.getPenaltyN1(s)+t.getPenaltyN2(s)+t.getPenaltyN3(s)+t.getPenaltyN4(s);t.applyMask(c,s),u<l&&(l=u,i=c)}return i}})(Zc)),Zc}var ii={},M0;function N0(){if(M0)return ii;M0=1;const t=jc(),e=[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 ii.getBlocksCount=function(s,o){switch(o){case t.L:return e[(s-1)*4+0];case t.M:return e[(s-1)*4+1];case t.Q:return e[(s-1)*4+2];case t.H:return e[(s-1)*4+3];default:return}},ii.getTotalCodewordsCount=function(s,o){switch(o){case t.L:return r[(s-1)*4+0];case t.M:return r[(s-1)*4+1];case t.Q:return r[(s-1)*4+2];case t.H:return r[(s-1)*4+3];default:return}},ii}var Fc={},no={},L0;function u5(){if(L0)return no;L0=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let s=0;s<255;s++)t[s]=n,e[n]=s,n<<=1,n&256&&(n^=285);for(let s=255;s<512;s++)t[s]=t[s-255]})(),no.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},no.exp=function(n){return t[n]},no.mul=function(n,s){return n===0||s===0?0:t[e[n]+e[s]]},no}var j0;function d5(){return j0||(j0=1,(function(t){const e=u5();t.mul=function(n,s){const o=new Uint8Array(n.length+s.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<s.length;i++)o[a+i]^=e.mul(n[a],s[i]);return o},t.mod=function(n,s){let o=new Uint8Array(n);for(;o.length-s.length>=0;){const a=o[0];for(let l=0;l<s.length;l++)o[l]^=e.mul(s[l],a);let i=0;for(;i<o.length&&o[i]===0;)i++;o=o.slice(i)}return o},t.generateECPolynomial=function(n){let s=new Uint8Array([1]);for(let o=0;o<n;o++)s=t.mul(s,new Uint8Array([1,e.exp(o)]));return s}})(Fc)),Fc}var Vc,q0;function p5(){if(q0)return Vc;q0=1;const t=d5();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const s=new Uint8Array(n.length+this.degree);s.set(n);const o=t.mod(s,this.genPoly),a=this.degree-o.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(o,a),i}return o},Vc=e,Vc}var Hc={},Bc={},Jc={},z0;function D0(){return z0||(z0=1,Jc.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),Jc}var ur={},U0;function Z0(){if(U0)return ur;U0=1;const t="[0-9]+",e="[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
44
+ ]))+`;ur.KANJI=new RegExp(r,"g"),ur.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ur.BYTE=new RegExp(n,"g"),ur.NUMERIC=new RegExp(t,"g"),ur.ALPHANUMERIC=new RegExp(e,"g");const s=new RegExp("^"+r+"$"),o=new RegExp("^"+t+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ur.testKanji=function(l){return s.test(l)},ur.testNumeric=function(l){return o.test(l)},ur.testAlphanumeric=function(l){return a.test(l)},ur}var F0;function vn(){return F0||(F0=1,(function(t){const e=D0(),r=Z0();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(o,a){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!e.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?o.ccBits[0]:a<27?o.ccBits[1]:o.ccBits[2]},t.getBestModeForData=function(o){return r.testNumeric(o)?t.NUMERIC:r.testAlphanumeric(o)?t.ALPHANUMERIC:r.testKanji(o)?t.KANJI:t.BYTE},t.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},t.isValid=function(o){return o&&o.bit&&o.ccBits};function n(s){if(typeof s!="string")throw new Error("Param is not a string");switch(s.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+s)}}t.from=function(o,a){if(t.isValid(o))return o;try{return n(o)}catch{return a}}})(Bc)),Bc}var V0;function f5(){return V0||(V0=1,(function(t){const e=gn(),r=N0(),n=jc(),s=vn(),o=D0(),a=7973,i=e.getBCHDigit(a);function l(h,d,f){for(let w=1;w<=40;w++)if(d<=t.getCapacity(w,f,h))return w}function c(h,d){return s.getCharCountIndicator(h,d)+4}function u(h,d){let f=0;return h.forEach(function(w){const m=c(w.mode,d);f+=m+w.getBitsLength()}),f}function p(h,d){for(let f=1;f<=40;f++)if(u(h,f)<=t.getCapacity(f,d,s.MIXED))return f}t.from=function(d,f){return o.isValid(d)?parseInt(d,10):f},t.getCapacity=function(d,f,w){if(!o.isValid(d))throw new Error("Invalid QR Code version");typeof w>"u"&&(w=s.BYTE);const m=e.getSymbolTotalCodewords(d),y=r.getTotalCodewordsCount(d,f),_=(m-y)*8;if(w===s.MIXED)return _;const g=_-c(w,d);switch(w){case s.NUMERIC:return Math.floor(g/10*3);case s.ALPHANUMERIC:return Math.floor(g/11*2);case s.KANJI:return Math.floor(g/13);case s.BYTE:default:return Math.floor(g/8)}},t.getBestVersionForData=function(d,f){let w;const m=n.from(f,n.M);if(Array.isArray(d)){if(d.length>1)return p(d,m);if(d.length===0)return 1;w=d[0]}else w=d;return l(w.mode,w.getLength(),m)},t.getEncodedBits=function(d){if(!o.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;e.getBCHDigit(f)-i>=0;)f^=a<<e.getBCHDigit(f)-i;return d<<12|f}})(Hc)),Hc}var Gc={},H0;function h5(){if(H0)return Gc;H0=1;const t=gn(),e=1335,r=21522,n=t.getBCHDigit(e);return Gc.getEncodedBits=function(o,a){const i=o.bit<<3|a;let l=i<<10;for(;t.getBCHDigit(l)-n>=0;)l^=e<<t.getBCHDigit(l)-n;return(i<<10|l)^r},Gc}var Wc={},Kc,B0;function m5(){if(B0)return Kc;B0=1;const t=vn();function e(r){this.mode=t.NUMERIC,this.data=r.toString()}return e.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){let s,o,a;for(s=0;s+3<=this.data.length;s+=3)o=this.data.substr(s,3),a=parseInt(o,10),n.put(a,10);const i=this.data.length-s;i>0&&(o=this.data.substr(s),a=parseInt(o,10),n.put(a,i*3+1))},Kc=e,Kc}var Yc,J0;function g5(){if(J0)return Yc;J0=1;const t=vn(),e=["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=t.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(s){return 11*Math.floor(s/2)+6*(s%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(s){let o;for(o=0;o+2<=this.data.length;o+=2){let a=e.indexOf(this.data[o])*45;a+=e.indexOf(this.data[o+1]),s.put(a,11)}this.data.length%2&&s.put(e.indexOf(this.data[o]),6)},Yc=r,Yc}var Qc,G0;function v5(){if(G0)return Qc;G0=1;const t=vn();function e(r){this.mode=t.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return e.getBitsLength=function(n){return n*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(r){for(let n=0,s=this.data.length;n<s;n++)r.put(this.data[n],8)},Qc=e,Qc}var Xc,W0;function _5(){if(W0)return Xc;W0=1;const t=vn(),e=gn();function r(n){this.mode=t.KANJI,this.data=n}return r.getBitsLength=function(s){return s*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 s;for(s=0;s<this.data.length;s++){let o=e.toSJIS(this.data[s]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[s]+`
45
+ Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},Xc=r,Xc}var eu={exports:{}},K0;function y5(){return K0||(K0=1,(function(t){var e={single_source_shortest_paths:function(r,n,s){var o={},a={};a[n]=0;var i=e.PriorityQueue.make();i.push(n,0);for(var l,c,u,p,h,d,f,w,m;!i.empty();){l=i.pop(),c=l.value,p=l.cost,h=r[c]||{};for(u in h)h.hasOwnProperty(u)&&(d=h[u],f=p+d,w=a[u],m=typeof a[u]>"u",(m||w>f)&&(a[u]=f,i.push(u,f),o[u]=c))}if(typeof s<"u"&&typeof a[s]>"u"){var y=["Could not find a path from ",n," to ",s,"."].join("");throw new Error(y)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var s=[],o=n;o;)s.push(o),r[o],o=r[o];return s.reverse(),s},find_path:function(r,n,s){var o=e.single_source_shortest_paths(r,n,s);return e.extract_shortest_path_from_predecessor_list(o,s)},PriorityQueue:{make:function(r){var n=e.PriorityQueue,s={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(s[o]=n[o]);return s.queue=[],s.sorter=r.sorter||n.default_sorter,s},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var s={value:r,cost:n};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(eu)),eu.exports}var Y0;function w5(){return Y0||(Y0=1,(function(t){const e=vn(),r=m5(),n=g5(),s=v5(),o=_5(),a=Z0(),i=gn(),l=y5();function c(y){return unescape(encodeURIComponent(y)).length}function u(y,_,g){const b=[];let k;for(;(k=y.exec(g))!==null;)b.push({data:k[0],index:k.index,mode:_,length:k[0].length});return b}function p(y){const _=u(a.NUMERIC,e.NUMERIC,y),g=u(a.ALPHANUMERIC,e.ALPHANUMERIC,y);let b,k;return i.isKanjiModeEnabled()?(b=u(a.BYTE,e.BYTE,y),k=u(a.KANJI,e.KANJI,y)):(b=u(a.BYTE_KANJI,e.BYTE,y),k=[]),_.concat(g,b,k).sort(function(T,x){return T.index-x.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function h(y,_){switch(_){case e.NUMERIC:return r.getBitsLength(y);case e.ALPHANUMERIC:return n.getBitsLength(y);case e.KANJI:return o.getBitsLength(y);case e.BYTE:return s.getBitsLength(y)}}function d(y){return y.reduce(function(_,g){const b=_.length-1>=0?_[_.length-1]:null;return b&&b.mode===g.mode?(_[_.length-1].data+=g.data,_):(_.push(g),_)},[])}function f(y){const _=[];for(let g=0;g<y.length;g++){const b=y[g];switch(b.mode){case e.NUMERIC:_.push([b,{data:b.data,mode:e.ALPHANUMERIC,length:b.length},{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.ALPHANUMERIC:_.push([b,{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.KANJI:_.push([b,{data:b.data,mode:e.BYTE,length:c(b.data)}]);break;case e.BYTE:_.push([{data:b.data,mode:e.BYTE,length:c(b.data)}])}}return _}function w(y,_){const g={},b={start:{}};let k=["start"];for(let S=0;S<y.length;S++){const T=y[S],x=[];for(let I=0;I<T.length;I++){const A=T[I],P=""+S+I;x.push(P),g[P]={node:A,lastCount:0},b[P]={};for(let D=0;D<k.length;D++){const U=k[D];g[U]&&g[U].node.mode===A.mode?(b[U][P]=h(g[U].lastCount+A.length,A.mode)-h(g[U].lastCount,A.mode),g[U].lastCount+=A.length):(g[U]&&(g[U].lastCount=A.length),b[U][P]=h(A.length,A.mode)+4+e.getCharCountIndicator(A.mode,_))}}k=x}for(let S=0;S<k.length;S++)b[k[S]].end=0;return{map:b,table:g}}function m(y,_){let g;const b=e.getBestModeForData(y);if(g=e.from(_,b),g!==e.BYTE&&g.bit<b.bit)throw new Error('"'+y+'" cannot be encoded with mode '+e.toString(g)+`.
46
+ Suggested mode is: `+e.toString(b));switch(g===e.KANJI&&!i.isKanjiModeEnabled()&&(g=e.BYTE),g){case e.NUMERIC:return new r(y);case e.ALPHANUMERIC:return new n(y);case e.KANJI:return new o(y);case e.BYTE:return new s(y)}}t.fromArray=function(_){return _.reduce(function(g,b){return typeof b=="string"?g.push(m(b,null)):b.data&&g.push(m(b.data,b.mode)),g},[])},t.fromString=function(_,g){const b=p(_,i.isKanjiModeEnabled()),k=f(b),S=w(k,g),T=l.find_path(S.map,"start","end"),x=[];for(let I=1;I<T.length-1;I++)x.push(S.table[T[I]].node);return t.fromArray(d(x))},t.rawSplit=function(_){return t.fromArray(p(_,i.isKanjiModeEnabled()))}})(Wc)),Wc}var Q0;function b5(){if(Q0)return Nc;Q0=1;const t=gn(),e=jc(),r=o5(),n=a5(),s=i5(),o=l5(),a=c5(),i=N0(),l=p5(),c=f5(),u=h5(),p=vn(),h=w5();function d(S,T){const x=S.size,I=o.getPositions(T);for(let A=0;A<I.length;A++){const P=I[A][0],D=I[A][1];for(let U=-1;U<=7;U++)if(!(P+U<=-1||x<=P+U))for(let V=-1;V<=7;V++)D+V<=-1||x<=D+V||(U>=0&&U<=6&&(V===0||V===6)||V>=0&&V<=6&&(U===0||U===6)||U>=2&&U<=4&&V>=2&&V<=4?S.set(P+U,D+V,!0,!0):S.set(P+U,D+V,!1,!0))}}function f(S){const T=S.size;for(let x=8;x<T-8;x++){const I=x%2===0;S.set(x,6,I,!0),S.set(6,x,I,!0)}}function w(S,T){const x=s.getPositions(T);for(let I=0;I<x.length;I++){const A=x[I][0],P=x[I][1];for(let D=-2;D<=2;D++)for(let U=-2;U<=2;U++)D===-2||D===2||U===-2||U===2||D===0&&U===0?S.set(A+D,P+U,!0,!0):S.set(A+D,P+U,!1,!0)}}function m(S,T){const x=S.size,I=c.getEncodedBits(T);let A,P,D;for(let U=0;U<18;U++)A=Math.floor(U/3),P=U%3+x-8-3,D=(I>>U&1)===1,S.set(A,P,D,!0),S.set(P,A,D,!0)}function y(S,T,x){const I=S.size,A=u.getEncodedBits(T,x);let P,D;for(P=0;P<15;P++)D=(A>>P&1)===1,P<6?S.set(P,8,D,!0):P<8?S.set(P+1,8,D,!0):S.set(I-15+P,8,D,!0),P<8?S.set(8,I-P-1,D,!0):P<9?S.set(8,15-P-1+1,D,!0):S.set(8,15-P-1,D,!0);S.set(I-8,8,1,!0)}function _(S,T){const x=S.size;let I=-1,A=x-1,P=7,D=0;for(let U=x-1;U>0;U-=2)for(U===6&&U--;;){for(let V=0;V<2;V++)if(!S.isReserved(A,U-V)){let se=!1;D<T.length&&(se=(T[D]>>>P&1)===1),S.set(A,U-V,se),P--,P===-1&&(D++,P=7)}if(A+=I,A<0||x<=A){A-=I,I=-I;break}}}function g(S,T,x){const I=new r;x.forEach(function(V){I.put(V.mode.bit,4),I.put(V.getLength(),p.getCharCountIndicator(V.mode,S)),V.write(I)});const A=t.getSymbolTotalCodewords(S),P=i.getTotalCodewordsCount(S,T),D=(A-P)*8;for(I.getLengthInBits()+4<=D&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const U=(D-I.getLengthInBits())/8;for(let V=0;V<U;V++)I.put(V%2?17:236,8);return b(I,S,T)}function b(S,T,x){const I=t.getSymbolTotalCodewords(T),A=i.getTotalCodewordsCount(T,x),P=I-A,D=i.getBlocksCount(T,x),U=I%D,V=D-U,se=Math.floor(I/D),fe=Math.floor(P/D),de=fe+1,re=se-fe,_e=new l(re);let H=0;const O=new Array(D),F=new Array(D);let q=0;const E=new Uint8Array(S.buffer);for(let ye=0;ye<D;ye++){const pe=ye<V?fe:de;O[ye]=E.slice(H,H+pe),F[ye]=_e.encode(O[ye]),H+=pe,q=Math.max(q,pe)}const R=new Uint8Array(I);let $=0,B,W;for(B=0;B<q;B++)for(W=0;W<D;W++)B<O[W].length&&(R[$++]=O[W][B]);for(B=0;B<re;B++)for(W=0;W<D;W++)R[$++]=F[W][B];return R}function k(S,T,x,I){let A;if(Array.isArray(S))A=h.fromArray(S);else if(typeof S=="string"){let se=T;if(!se){const fe=h.rawSplit(S);se=c.getBestVersionForData(fe,x)}A=h.fromString(S,se||40)}else throw new Error("Invalid data");const P=c.getBestVersionForData(A,x);if(!P)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=P;else if(T<P)throw new Error(`
47
47
  The chosen QR Code version cannot contain this amount of data.
48
48
  Minimum version required to store current data is: `+P+`.
49
- `);const D=g(T,x,A),U=t.getSymbolSize(T),V=new n(U);return d(V,T),f(V),w(V,T),y(V,x,0),T>=7&&m(V,T),_(V,D),isNaN(I)&&(I=a.getBestMask(V,y.bind(null,V,x))),a.applyMask(I,V),y(V,x,I),{modules:V,version:T,errorCorrectionLevel:x,maskPattern:I,segments:A}}return Lc.create=function(T,x){if(typeof T>"u"||T==="")throw new Error("No input text");let I=e.M,A,P;return typeof x<"u"&&(I=e.from(x.errorCorrectionLevel,e.M),A=c.from(x.version),P=a.from(x.maskPattern),x.toSJISFunc&&t.setToSJISFunction(x.toSJISFunc)),k(T,A,I,P)},Lc}var ru={},nu={},X0;function em(){return X0||(X0=1,(function(t){function e(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(o){return[o,o]}))),n.length===6&&n.push("F","F");const s=parseInt(n.join(""),16);return{r:s>>24&255,g:s>>16&255,b:s>>8&255,a:s&255,hex:"#"+n.slice(0,6).join("")}}t.getOptions=function(n){n||(n={}),n.color||(n.color={});const s=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:o,scale:o?4:a,margin:s,color:{dark:e(n.color.dark||"#000000ff"),light:e(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},t.getScale=function(n,s){return s.width&&s.width>=n+s.margin*2?s.width/(n+s.margin*2):s.scale},t.getImageWidth=function(n,s){const o=t.getScale(n,s);return Math.floor((n+s.margin*2)*o)},t.qrToImageData=function(n,s,o){const a=s.modules.size,i=s.modules.data,l=t.getScale(a,o),c=Math.floor((a+o.margin*2)*l),u=o.margin*l,p=[o.color.light,o.color.dark];for(let h=0;h<c;h++)for(let d=0;d<c;d++){let f=(h*c+d)*4,w=o.color.light;if(h>=u&&d>=u&&h<c-u&&d<c-u){const m=Math.floor((h-u)/l),y=Math.floor((d-u)/l);w=p[i[m*a+y]?1:0]}n[f++]=w.r,n[f++]=w.g,n[f++]=w.b,n[f]=w.a}}})(nu)),nu}var tm;function k5(){return tm||(tm=1,(function(t){const e=em();function r(s,o,a){s.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=a,o.width=a,o.style.height=a+"px",o.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(o,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=e.getOptions(l);const u=e.getImageWidth(o.modules.size,l),p=c.getContext("2d"),h=p.createImageData(u,u);return e.qrToImageData(h.data,o,l),r(p,c,u),p.putImageData(h,0,0),c},t.renderToDataURL=function(o,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=t.render(o,a,l),u=l.type||"image/png",p=l.rendererOpts||{};return c.toDataURL(u,p.quality)}})(ru)),ru}var su={},rm;function S5(){if(rm)return su;rm=1;const t=em();function e(s,o){const a=s.a/255,i=o+'="'+s.hex+'"';return a<1?i+" "+o+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(s,o,a){let i=s+o;return typeof a<"u"&&(i+=" "+a),i}function n(s,o,a){let i="",l=0,c=!1,u=0;for(let p=0;p<s.length;p++){const h=Math.floor(p%o),d=Math.floor(p/o);!h&&!c&&(c=!0),s[p]?(u++,p>0&&h>0&&s[p-1]||(i+=c?r("M",h+a,.5+d+a):r("m",l,0),l=0,c=!1),h+1<o&&s[p+1]||(i+=r("h",u),u=0)):l++}return i}return su.render=function(o,a,i){const l=t.getOptions(a),c=o.modules.size,u=o.modules.data,p=c+l.margin*2,h=l.color.light.a?"<path "+e(l.color.light,"fill")+' d="M0 0h'+p+"v"+p+'H0z"/>':"",d="<path "+e(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',f='viewBox="0 0 '+p+" "+p+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+f+' shape-rendering="crispEdges">'+h+d+`</svg>
50
- `;return typeof i=="function"&&i(null,m),m},su}var nm;function T5(){if(nm)return Wn;nm=1;const t=s5(),e=b5(),r=k5(),n=S5();function s(o,a,i,l,c){const u=[].slice.call(arguments,1),p=u.length,h=typeof u[p-1]=="function";if(!h&&!t())throw new Error("Callback required as last argument");if(h){if(p<2)throw new Error("Too few arguments provided");p===2?(c=i,i=a,a=l=void 0):p===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(p<1)throw new Error("Too few arguments provided");return p===1?(i=a,a=l=void 0):p===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(d,f){try{const w=e.create(i,l);d(o(w,a,l))}catch(w){f(w)}})}try{const d=e.create(i,l);c(null,o(d,a,l))}catch(d){c(d)}}return Wn.create=e.create,Wn.toCanvas=s.bind(null,r.render),Wn.toDataURL=s.bind(null,r.renderToDataURL),Wn.toString=s.bind(null,function(o,a,i){return n.render(o,i)}),Wn}var C5=T5();const sm=tn(C5);class om{constructor(e,{size:r=200,margin:n=4,color:s="#000",bgColor:o="#fff"}){this.value=e,this.size=r,this.margin=n,this.color=s,this.bgColor=o}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return sm.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return sm.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const $5={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class E5{constructor(e,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof e=="string"?document.querySelector(e):e,!this.el)throw new Error("Tooltip: invalid element");this.opts={...$5,...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 e=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),e==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const e=this.opts.trigger;e==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):e==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):e==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const e=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=`
49
+ `);const D=g(T,x,A),U=t.getSymbolSize(T),V=new n(U);return d(V,T),f(V),w(V,T),y(V,x,0),T>=7&&m(V,T),_(V,D),isNaN(I)&&(I=a.getBestMask(V,y.bind(null,V,x))),a.applyMask(I,V),y(V,x,I),{modules:V,version:T,errorCorrectionLevel:x,maskPattern:I,segments:A}}return Nc.create=function(T,x){if(typeof T>"u"||T==="")throw new Error("No input text");let I=e.M,A,P;return typeof x<"u"&&(I=e.from(x.errorCorrectionLevel,e.M),A=c.from(x.version),P=a.from(x.maskPattern),x.toSJISFunc&&t.setToSJISFunction(x.toSJISFunc)),k(T,A,I,P)},Nc}var tu={},ru={},X0;function em(){return X0||(X0=1,(function(t){function e(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(o){return[o,o]}))),n.length===6&&n.push("F","F");const s=parseInt(n.join(""),16);return{r:s>>24&255,g:s>>16&255,b:s>>8&255,a:s&255,hex:"#"+n.slice(0,6).join("")}}t.getOptions=function(n){n||(n={}),n.color||(n.color={});const s=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:o,scale:o?4:a,margin:s,color:{dark:e(n.color.dark||"#000000ff"),light:e(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},t.getScale=function(n,s){return s.width&&s.width>=n+s.margin*2?s.width/(n+s.margin*2):s.scale},t.getImageWidth=function(n,s){const o=t.getScale(n,s);return Math.floor((n+s.margin*2)*o)},t.qrToImageData=function(n,s,o){const a=s.modules.size,i=s.modules.data,l=t.getScale(a,o),c=Math.floor((a+o.margin*2)*l),u=o.margin*l,p=[o.color.light,o.color.dark];for(let h=0;h<c;h++)for(let d=0;d<c;d++){let f=(h*c+d)*4,w=o.color.light;if(h>=u&&d>=u&&h<c-u&&d<c-u){const m=Math.floor((h-u)/l),y=Math.floor((d-u)/l);w=p[i[m*a+y]?1:0]}n[f++]=w.r,n[f++]=w.g,n[f++]=w.b,n[f]=w.a}}})(ru)),ru}var tm;function k5(){return tm||(tm=1,(function(t){const e=em();function r(s,o,a){s.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=a,o.width=a,o.style.height=a+"px",o.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(o,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=e.getOptions(l);const u=e.getImageWidth(o.modules.size,l),p=c.getContext("2d"),h=p.createImageData(u,u);return e.qrToImageData(h.data,o,l),r(p,c,u),p.putImageData(h,0,0),c},t.renderToDataURL=function(o,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=t.render(o,a,l),u=l.type||"image/png",p=l.rendererOpts||{};return c.toDataURL(u,p.quality)}})(tu)),tu}var nu={},rm;function S5(){if(rm)return nu;rm=1;const t=em();function e(s,o){const a=s.a/255,i=o+'="'+s.hex+'"';return a<1?i+" "+o+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(s,o,a){let i=s+o;return typeof a<"u"&&(i+=" "+a),i}function n(s,o,a){let i="",l=0,c=!1,u=0;for(let p=0;p<s.length;p++){const h=Math.floor(p%o),d=Math.floor(p/o);!h&&!c&&(c=!0),s[p]?(u++,p>0&&h>0&&s[p-1]||(i+=c?r("M",h+a,.5+d+a):r("m",l,0),l=0,c=!1),h+1<o&&s[p+1]||(i+=r("h",u),u=0)):l++}return i}return nu.render=function(o,a,i){const l=t.getOptions(a),c=o.modules.size,u=o.modules.data,p=c+l.margin*2,h=l.color.light.a?"<path "+e(l.color.light,"fill")+' d="M0 0h'+p+"v"+p+'H0z"/>':"",d="<path "+e(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',f='viewBox="0 0 '+p+" "+p+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+f+' shape-rendering="crispEdges">'+h+d+`</svg>
50
+ `;return typeof i=="function"&&i(null,m),m},nu}var nm;function T5(){if(nm)return Wn;nm=1;const t=s5(),e=b5(),r=k5(),n=S5();function s(o,a,i,l,c){const u=[].slice.call(arguments,1),p=u.length,h=typeof u[p-1]=="function";if(!h&&!t())throw new Error("Callback required as last argument");if(h){if(p<2)throw new Error("Too few arguments provided");p===2?(c=i,i=a,a=l=void 0):p===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(p<1)throw new Error("Too few arguments provided");return p===1?(i=a,a=l=void 0):p===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(d,f){try{const w=e.create(i,l);d(o(w,a,l))}catch(w){f(w)}})}try{const d=e.create(i,l);c(null,o(d,a,l))}catch(d){c(d)}}return Wn.create=e.create,Wn.toCanvas=s.bind(null,r.render),Wn.toDataURL=s.bind(null,r.renderToDataURL),Wn.toString=s.bind(null,function(o,a,i){return n.render(o,i)}),Wn}var C5=T5();const sm=tn(C5);class om{constructor(e,{size:r=200,margin:n=4,color:s="#000",bgColor:o="#fff"}){this.value=e,this.size=r,this.margin=n,this.color=s,this.bgColor=o}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return sm.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return sm.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const $5={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class E5{constructor(e,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof e=="string"?document.querySelector(e):e,!this.el)throw new Error("Tooltip: invalid element");this.opts={...$5,...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 e=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),e==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const e=this.opts.trigger;e==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):e==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):e==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const e=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=`
51
51
  <div class="${this.opts.className}__arrow"></div>
52
52
  <div class="${this.opts.className}__inner">${e}</div>
53
53
  `}reposition(){const e=this.placementList(this.opts.placement);for(const r of e){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(e){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),s=window.pageYOffset||document.documentElement.scrollTop,o=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=e.split("-");let c=0,u=0;return i==="top"?c=r.top+s-n.height-a:i==="bottom"?c=r.bottom+s+a:i==="left"?u=r.left+o-n.width-a:i==="right"&&(u=r.right+o+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+o:l==="end"?u=r.right+o-n.width:u=(r.left+r.right)/2+o-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+s:l==="end"?c=r.bottom+s-n.height:c=(r.top+r.bottom)/2+s-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:e,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${e}px`,left:`${r}px`})}checkViewport({top:e,left:r}){const s=window.innerWidth,o=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&e>=5&&r+a.width<=s-5&&e+a.height<=o-5}placementList(e){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[e.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=e=>{const r=e.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 am="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(am))return;const t=document.createElement("style");t.id=am,t.textContent=`
@@ -546,12 +546,12 @@ Minimum version required to store current data is: `+P+`.
546
546
  }
547
547
  }
548
548
  `,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const N5=(t={})=>new M5(t);var cm="vercel.ai.error",L5=Symbol.for(cm),um,j5=class w_ extends Error{constructor({name:e,message:r,cause:n}){super(r),this[um]=!0,this.name=e,this.cause=n}static isInstance(e){return w_.hasMarker(e,cm)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}};um=L5;var ve=j5,dm="AI_APICallError",pm=`vercel.ai.error.${dm}`,q5=Symbol.for(pm),fm,Ve=class extends ve{constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:o,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:dm,message:t,cause:a}),this[fm]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=o,this.isRetryable=i,this.data=l}static isInstance(t){return ve.hasMarker(t,pm)}};fm=q5;var hm="AI_EmptyResponseBodyError",mm=`vercel.ai.error.${hm}`,z5=Symbol.for(mm),gm,vm=class extends ve{constructor({message:t="Empty response body"}={}){super({name:hm,message:t}),this[gm]=!0}static isInstance(t){return ve.hasMarker(t,mm)}};gm=z5;function Kn(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var _m="AI_InvalidArgumentError",ym=`vercel.ai.error.${_m}`,D5=Symbol.for(ym),wm,li=class extends ve{constructor({message:e,cause:r,argument:n}){super({name:_m,message:e,cause:r}),this[wm]=!0,this.argument=n}static isInstance(e){return ve.hasMarker(e,ym)}};wm=D5;var bm="AI_InvalidPromptError",km=`vercel.ai.error.${bm}`,U5=Symbol.for(km),Sm,_n=class extends ve{constructor({prompt:t,message:e,cause:r}){super({name:bm,message:`Invalid prompt: ${e}`,cause:r}),this[Sm]=!0,this.prompt=t}static isInstance(t){return ve.hasMarker(t,km)}};Sm=U5;var Tm="AI_InvalidResponseDataError",Cm=`vercel.ai.error.${Tm}`,Z5=Symbol.for(Cm),$m,so=class extends ve{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Tm,message:e}),this[$m]=!0,this.data=t}static isInstance(t){return ve.hasMarker(t,Cm)}};$m=Z5;var Em="AI_JSONParseError",xm=`vercel.ai.error.${Em}`,F5=Symbol.for(xm),Im,Jr=class extends ve{constructor({text:t,cause:e}){super({name:Em,message:`JSON parsing failed: Text: ${t}.
549
- Error message: ${Kn(e)}`,cause:e}),this[Im]=!0,this.text=t}static isInstance(t){return ve.hasMarker(t,xm)}};Im=F5;var Rm="AI_LoadAPIKeyError",Pm=`vercel.ai.error.${Rm}`,V5=Symbol.for(Pm),Om,Gr=class extends ve{constructor({message:t}){super({name:Rm,message:t}),this[Om]=!0}static isInstance(t){return ve.hasMarker(t,Pm)}};Om=V5;var Am="AI_NoSuchModelError",Mm=`vercel.ai.error.${Am}`,H5=Symbol.for(Mm),Nm,Lm=class extends ve{constructor({errorName:t=Am,modelId:e,modelType:r,message:n=`No such ${r}: ${e}`}){super({name:t,message:n}),this[Nm]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return ve.hasMarker(t,Mm)}};Nm=H5;var jm="AI_TooManyEmbeddingValuesForCallError",qm=`vercel.ai.error.${jm}`,B5=Symbol.for(qm),zm,J5=class extends ve{constructor(t){super({name:jm,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[zm]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return ve.hasMarker(t,qm)}};zm=B5;var Dm="AI_TypeValidationError",Um=`vercel.ai.error.${Dm}`,G5=Symbol.for(Um),Zm,W5=class ad extends ve{constructor({value:e,cause:r}){super({name:Dm,message:`Type validation failed: Value: ${JSON.stringify(e)}.
550
- Error message: ${Kn(r)}`,cause:r}),this[Zm]=!0,this.value=e}static isInstance(e){return ve.hasMarker(e,Um)}static wrap({value:e,cause:r}){return ad.isInstance(r)&&r.value===e?r:new ad({value:e,cause:r})}};Zm=G5;var dr=W5,Fm="AI_UnsupportedFunctionalityError",Vm=`vercel.ai.error.${Fm}`,K5=Symbol.for(Vm),Hm,Wt=class extends ve{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:Fm,message:e}),this[Hm]=!0,this.functionality=t}static isInstance(t){return ve.hasMarker(t,Vm)}};Hm=K5;function Yn(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function Y5(t,e){if(t==null)return Promise.resolve();const r=e?.abortSignal;return new Promise((n,s)=>{if(r?.aborted){s(Bm());return}const o=setTimeout(()=>{a(),n()},t),a=()=>{clearTimeout(o),r?.removeEventListener("abort",i)},i=()=>{a(),s(Bm())};r?.addEventListener("abort",i)})}function Bm(){return new DOMException("Delay was aborted","AbortError")}var ci=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((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function oo(t){return Object.fromEntries([...t.headers])}var ao=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new li({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},io=ao();function ou(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function yn(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Q5=["fetch failed","failed to fetch"];function Jm({error:t,url:e,requestBodyValues:r}){if(yn(t))return t;if(t instanceof TypeError&&Q5.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new Ve({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function lo(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function X5(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function Wr(t,...e){const r=new Headers(X5(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var Gm="3.0.18",eS=()=>globalThis.fetch,Wm=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:s,fetch:o=eS()})=>{try{const a=await o(t,{method:"GET",headers:Wr(e,`ai-sdk/provider-utils/${Gm}`,lo()),signal:s}),i=oo(a);if(!a.ok){let l;try{l=await n({response:a,url:t,requestBodyValues:{}})}catch(c){throw yn(c)||Ve.isInstance(c)?c:new Ve({message:"Failed to process error response",cause:c,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(yn(l)||Ve.isInstance(l))?l:new Ve({message:"Failed to process successful response",cause:l,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw Jm({error:a,url:t,requestBodyValues:{}})}};function tS({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([n,s])=>{const o=n.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:o.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:n})=>t.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(e))}function rS({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Gr({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Gr({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function ui({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var nS=/"__proto__"\s*:/,sS=/"constructor"\s*:/;function Km(t){const e=JSON.parse(t);return e===null||typeof e!="object"||nS.test(t)===!1&&sS.test(t)===!1?e:oS(e)}function oS(t){let e=[t];for(;e.length;){const r=e;e=[];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 s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function au(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return Km(t)}try{return Km(t)}finally{Error.stackTraceLimit=e}}var di=Symbol.for("vercel.ai.validator");function aS(t){return{[di]:!0,validate:t}}function iS(t){return typeof t=="object"&&t!==null&&di in t&&t[di]===!0&&"validate"in t}function Qn(t){let e;return()=>(e==null&&(e=t()),e)}function lS(t){return iS(t)?t:typeof t=="function"?t():cS(t)}function cS(t){return aS(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new dr({value:e,cause:r.issues})}})}async function iu({value:t,schema:e}){const r=await Kt({value:t,schema:e});if(!r.success)throw dr.wrap({value:t,cause:r.error});return r.value}async function Kt({value:t,schema:e}){const r=lS(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:dr.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:dr.wrap({value:t,cause:n}),rawValue:t}}}async function uS({text:t,schema:e}){try{const r=au(t);return e==null?r:iu({value:r,schema:e})}catch(r){throw Jr.isInstance(r)||dr.isInstance(r)?r:new Jr({text:t,cause:r})}}async function wn({text:t,schema:e}){try{const r=au(t);return e==null?{success:!0,value:r,rawValue:r}:await Kt({value:r,schema:e})}catch(r){return{success:!1,error:Jr.isInstance(r)?r:new Jr({text:t,cause:r}),rawValue:void 0}}}function Ym(t){try{return au(t),!0}catch{return!1}}function dS({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await wn({text:r,schema:e}))}}))}async function Qm({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await Kt({value:e[t],schema:r});if(!n.success)throw new li({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var pS=()=>globalThis.fetch,Xn=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>fS({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),fS=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=pS()})=>{try{const i=await a(t,{method:"POST",headers:Wr(e,`ai-sdk/provider-utils/${Gm}`,lo()),body:r.content,signal:o}),l=oo(i);if(!i.ok){let c;try{c=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw yn(u)||Ve.isInstance(u)?u:new Ve({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(yn(c)||Ve.isInstance(c))?c:new Ve({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw Jm({error:i,url:t,requestBodyValues:r.values})}};function TI(t){return t}function Xm(t){return{...t,type:"dynamic"}}async function pr(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var bn=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=oo(n);if(a.trim()==="")return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await uS({text:a,schema:t});return{responseHeaders:i,value:new Ve({message:e(l),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},e2=t=>async({response:e})=>{const r=oo(e);if(e.body==null)throw new vm({});return{responseHeaders:r,value:dS({stream:e.body,schema:t})}},es=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await wn({text:s,schema:t}),a=oo(e);if(!o.success)throw new Ve({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},hS=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},mS=Symbol("Let zodToJsonSchema decide on which parser to use"),t2={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"},gS=t=>typeof t=="string"?{...t2,name:t}:{...t2,...t};function Ot(){return{}}function vS(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=ze(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function _S(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function yS(){return{type:"boolean"}}function r2(t,e){return ze(t.type._def,e)}var wS=(t,e)=>ze(t.innerType._def,e);function n2(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>n2(t,e,s))};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 bS(t)}}var bS=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function kS(t,e){return{...ze(t.innerType._def,e),default:t.defaultValue()}}function SS(t,e){return e.effectStrategy==="input"?ze(t.schema._def,e):Ot()}function TS(t){return{type:"string",enum:Array.from(t.values)}}var CS=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function $S(t,e){const r=[ze(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ze(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(CS(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function ES(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var lu=void 0,Yt={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:()=>(lu===void 0&&(lu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),lu),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 s2(t,e){const r={type:"string"};if(t.checks)for(const n of t.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(e.emailStrategy){case"format:email":Qt(r,"email",n.message,e);break;case"format:idn-email":Qt(r,"idn-email",n.message,e);break;case"pattern:zod":gt(r,Yt.email,n.message,e);break}break;case"url":Qt(r,"uri",n.message,e);break;case"uuid":Qt(r,"uuid",n.message,e);break;case"regex":gt(r,n.regex,n.message,e);break;case"cuid":gt(r,Yt.cuid,n.message,e);break;case"cuid2":gt(r,Yt.cuid2,n.message,e);break;case"startsWith":gt(r,RegExp(`^${cu(n.value,e)}`),n.message,e);break;case"endsWith":gt(r,RegExp(`${cu(n.value,e)}$`),n.message,e);break;case"datetime":Qt(r,"date-time",n.message,e);break;case"date":Qt(r,"date",n.message,e);break;case"time":Qt(r,"time",n.message,e);break;case"duration":Qt(r,"duration",n.message,e);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":{gt(r,RegExp(cu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Qt(r,"ipv4",n.message,e),n.version!=="v4"&&Qt(r,"ipv6",n.message,e);break}case"base64url":gt(r,Yt.base64url,n.message,e);break;case"jwt":gt(r,Yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&gt(r,Yt.ipv4Cidr,n.message,e),n.version!=="v4"&&gt(r,Yt.ipv6Cidr,n.message,e);break}case"emoji":gt(r,Yt.emoji(),n.message,e);break;case"ulid":{gt(r,Yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Qt(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{gt(r,Yt.base64,n.message,e);break}}break}case"nanoid":gt(r,Yt.nanoid,n.message,e)}return r}function cu(t,e){return e.patternStrategy==="escape"?IS(t):t}var xS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function IS(t){let e="";for(let r=0;r<t.length;r++)xS.has(t[r])||(e+="\\"),e+=t[r];return e}function Qt(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function gt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:o2(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=o2(e,n)}function o2(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,l=!1;for(let c=0;c<s.length;c++){if(a){o+=s[c],a=!1;continue}if(n.i){if(i){if(s[c].match(/[a-z]/)){l?(o+=s[c],o+=`${s[c-2]}-${s[c]}`.toUpperCase(),l=!1):s[c+1]==="-"&&((r=s[c+2])!=null&&r.match(/[a-z]/))?(o+=s[c],l=!0):o+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){o+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(n.m){if(s[c]==="^"){o+=`(^|(?<=[\r
549
+ Error message: ${Kn(e)}`,cause:e}),this[Im]=!0,this.text=t}static isInstance(t){return ve.hasMarker(t,xm)}};Im=F5;var Rm="AI_LoadAPIKeyError",Pm=`vercel.ai.error.${Rm}`,V5=Symbol.for(Pm),Om,Gr=class extends ve{constructor({message:t}){super({name:Rm,message:t}),this[Om]=!0}static isInstance(t){return ve.hasMarker(t,Pm)}};Om=V5;var Am="AI_NoSuchModelError",Mm=`vercel.ai.error.${Am}`,H5=Symbol.for(Mm),Nm,Lm=class extends ve{constructor({errorName:t=Am,modelId:e,modelType:r,message:n=`No such ${r}: ${e}`}){super({name:t,message:n}),this[Nm]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return ve.hasMarker(t,Mm)}};Nm=H5;var jm="AI_TooManyEmbeddingValuesForCallError",qm=`vercel.ai.error.${jm}`,B5=Symbol.for(qm),zm,J5=class extends ve{constructor(t){super({name:jm,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[zm]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return ve.hasMarker(t,qm)}};zm=B5;var Dm="AI_TypeValidationError",Um=`vercel.ai.error.${Dm}`,G5=Symbol.for(Um),Zm,W5=class od extends ve{constructor({value:e,cause:r}){super({name:Dm,message:`Type validation failed: Value: ${JSON.stringify(e)}.
550
+ Error message: ${Kn(r)}`,cause:r}),this[Zm]=!0,this.value=e}static isInstance(e){return ve.hasMarker(e,Um)}static wrap({value:e,cause:r}){return od.isInstance(r)&&r.value===e?r:new od({value:e,cause:r})}};Zm=G5;var dr=W5,Fm="AI_UnsupportedFunctionalityError",Vm=`vercel.ai.error.${Fm}`,K5=Symbol.for(Vm),Hm,Wt=class extends ve{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:Fm,message:e}),this[Hm]=!0,this.functionality=t}static isInstance(t){return ve.hasMarker(t,Vm)}};Hm=K5;function Yn(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function Y5(t,e){if(t==null)return Promise.resolve();const r=e?.abortSignal;return new Promise((n,s)=>{if(r?.aborted){s(Bm());return}const o=setTimeout(()=>{a(),n()},t),a=()=>{clearTimeout(o),r?.removeEventListener("abort",i)},i=()=>{a(),s(Bm())};r?.addEventListener("abort",i)})}function Bm(){return new DOMException("Delay was aborted","AbortError")}var ci=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((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function oo(t){return Object.fromEntries([...t.headers])}var ao=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new li({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},io=ao();function su(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function yn(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Q5=["fetch failed","failed to fetch"];function Jm({error:t,url:e,requestBodyValues:r}){if(yn(t))return t;if(t instanceof TypeError&&Q5.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new Ve({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function lo(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function X5(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function Wr(t,...e){const r=new Headers(X5(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var Gm="3.0.18",eS=()=>globalThis.fetch,Wm=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:s,fetch:o=eS()})=>{try{const a=await o(t,{method:"GET",headers:Wr(e,`ai-sdk/provider-utils/${Gm}`,lo()),signal:s}),i=oo(a);if(!a.ok){let l;try{l=await n({response:a,url:t,requestBodyValues:{}})}catch(c){throw yn(c)||Ve.isInstance(c)?c:new Ve({message:"Failed to process error response",cause:c,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(yn(l)||Ve.isInstance(l))?l:new Ve({message:"Failed to process successful response",cause:l,statusCode:a.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw Jm({error:a,url:t,requestBodyValues:{}})}};function tS({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([n,s])=>{const o=n.toLowerCase();return o==="*"||o==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:o.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:n})=>t.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(e))}function rS({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Gr({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Gr({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function ui({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var nS=/"__proto__"\s*:/,sS=/"constructor"\s*:/;function Km(t){const e=JSON.parse(t);return e===null||typeof e!="object"||nS.test(t)===!1&&sS.test(t)===!1?e:oS(e)}function oS(t){let e=[t];for(;e.length;){const r=e;e=[];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 s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function ou(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return Km(t)}try{return Km(t)}finally{Error.stackTraceLimit=e}}var di=Symbol.for("vercel.ai.validator");function aS(t){return{[di]:!0,validate:t}}function iS(t){return typeof t=="object"&&t!==null&&di in t&&t[di]===!0&&"validate"in t}function Qn(t){let e;return()=>(e==null&&(e=t()),e)}function lS(t){return iS(t)?t:typeof t=="function"?t():cS(t)}function cS(t){return aS(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new dr({value:e,cause:r.issues})}})}async function au({value:t,schema:e}){const r=await Kt({value:t,schema:e});if(!r.success)throw dr.wrap({value:t,cause:r.error});return r.value}async function Kt({value:t,schema:e}){const r=lS(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:dr.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:dr.wrap({value:t,cause:n}),rawValue:t}}}async function uS({text:t,schema:e}){try{const r=ou(t);return e==null?r:au({value:r,schema:e})}catch(r){throw Jr.isInstance(r)||dr.isInstance(r)?r:new Jr({text:t,cause:r})}}async function wn({text:t,schema:e}){try{const r=ou(t);return e==null?{success:!0,value:r,rawValue:r}:await Kt({value:r,schema:e})}catch(r){return{success:!1,error:Jr.isInstance(r)?r:new Jr({text:t,cause:r}),rawValue:void 0}}}function Ym(t){try{return ou(t),!0}catch{return!1}}function dS({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await wn({text:r,schema:e}))}}))}async function Qm({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await Kt({value:e[t],schema:r});if(!n.success)throw new li({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var pS=()=>globalThis.fetch,Xn=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>fS({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),fS=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=pS()})=>{try{const i=await a(t,{method:"POST",headers:Wr(e,`ai-sdk/provider-utils/${Gm}`,lo()),body:r.content,signal:o}),l=oo(i);if(!i.ok){let c;try{c=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw yn(u)||Ve.isInstance(u)?u:new Ve({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(yn(c)||Ve.isInstance(c))?c:new Ve({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw Jm({error:i,url:t,requestBodyValues:r.values})}};function TI(t){return t}function Xm(t){return{...t,type:"dynamic"}}async function pr(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var bn=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=oo(n);if(a.trim()==="")return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await uS({text:a,schema:t});return{responseHeaders:i,value:new Ve({message:e(l),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},e2=t=>async({response:e})=>{const r=oo(e);if(e.body==null)throw new vm({});return{responseHeaders:r,value:dS({stream:e.body,schema:t})}},es=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await wn({text:s,schema:t}),a=oo(e);if(!o.success)throw new Ve({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},hS=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},mS=Symbol("Let zodToJsonSchema decide on which parser to use"),t2={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"},gS=t=>typeof t=="string"?{...t2,name:t}:{...t2,...t};function Ot(){return{}}function vS(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=ze(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function _S(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function yS(){return{type:"boolean"}}function r2(t,e){return ze(t.type._def,e)}var wS=(t,e)=>ze(t.innerType._def,e);function n2(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>n2(t,e,s))};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 bS(t)}}var bS=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function kS(t,e){return{...ze(t.innerType._def,e),default:t.defaultValue()}}function SS(t,e){return e.effectStrategy==="input"?ze(t.schema._def,e):Ot()}function TS(t){return{type:"string",enum:Array.from(t.values)}}var CS=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function $S(t,e){const r=[ze(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ze(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(CS(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function ES(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var iu=void 0,Yt={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:()=>(iu===void 0&&(iu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),iu),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 s2(t,e){const r={type:"string"};if(t.checks)for(const n of t.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(e.emailStrategy){case"format:email":Qt(r,"email",n.message,e);break;case"format:idn-email":Qt(r,"idn-email",n.message,e);break;case"pattern:zod":gt(r,Yt.email,n.message,e);break}break;case"url":Qt(r,"uri",n.message,e);break;case"uuid":Qt(r,"uuid",n.message,e);break;case"regex":gt(r,n.regex,n.message,e);break;case"cuid":gt(r,Yt.cuid,n.message,e);break;case"cuid2":gt(r,Yt.cuid2,n.message,e);break;case"startsWith":gt(r,RegExp(`^${lu(n.value,e)}`),n.message,e);break;case"endsWith":gt(r,RegExp(`${lu(n.value,e)}$`),n.message,e);break;case"datetime":Qt(r,"date-time",n.message,e);break;case"date":Qt(r,"date",n.message,e);break;case"time":Qt(r,"time",n.message,e);break;case"duration":Qt(r,"duration",n.message,e);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":{gt(r,RegExp(lu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Qt(r,"ipv4",n.message,e),n.version!=="v4"&&Qt(r,"ipv6",n.message,e);break}case"base64url":gt(r,Yt.base64url,n.message,e);break;case"jwt":gt(r,Yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&gt(r,Yt.ipv4Cidr,n.message,e),n.version!=="v4"&&gt(r,Yt.ipv6Cidr,n.message,e);break}case"emoji":gt(r,Yt.emoji(),n.message,e);break;case"ulid":{gt(r,Yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Qt(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{gt(r,Yt.base64,n.message,e);break}}break}case"nanoid":gt(r,Yt.nanoid,n.message,e)}return r}function lu(t,e){return e.patternStrategy==="escape"?IS(t):t}var xS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function IS(t){let e="";for(let r=0;r<t.length;r++)xS.has(t[r])||(e+="\\"),e+=t[r];return e}function Qt(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function gt(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:o2(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=o2(e,n)}function o2(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,l=!1;for(let c=0;c<s.length;c++){if(a){o+=s[c],a=!1;continue}if(n.i){if(i){if(s[c].match(/[a-z]/)){l?(o+=s[c],o+=`${s[c-2]}-${s[c]}`.toUpperCase(),l=!1):s[c+1]==="-"&&((r=s[c+2])!=null&&r.match(/[a-z]/))?(o+=s[c],l=!0):o+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){o+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(n.m){if(s[c]==="^"){o+=`(^|(?<=[\r
551
551
  ]))`;continue}else if(s[c]==="$"){o+=`($|(?=[\r
552
552
  ]))`;continue}}if(n.s&&s[c]==="."){o+=i?`${s[c]}\r
553
553
  `:`[${s[c]}\r
554
- ]`;continue}o+=s[c],s[c]==="\\"?a=!0:i&&s[c]==="]"?i=!1:!i&&s[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function a2(t,e){var r,n,s,o,a,i;const l={type:"object",additionalProperties:(r=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=s2(t.keyType._def,e);return{...l,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=r2(t.keyType._def,e);return{...l,propertyNames:u}}}return l}function RS(t,e){if(e.mapStrategy==="record")return a2(t,e);const r=ze(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ot(),n=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ot();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function PS(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function OS(){return{not:Ot()}}function AS(){return{type:"null"}}var uu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function MS(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in uu&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=uu[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return NS(t,e)}var NS=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>ze(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function LS(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[uu[t.innerType._def.typeName],"null"]};const r=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function jS(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function qS(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const l=DS(i),c=ze(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const o=zS(t,e);return o!==void 0&&(r.additionalProperties=o),r}function zS(t,e){if(t.catchall._def.typeName!=="ZodNever")return ze(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function DS(t){try{return t.isOptional()}catch{return!0}}var US=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return ze(t.innerType._def,e);const n=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Ot()},n]}:Ot()},ZS=(t,e)=>{if(e.pipeStrategy==="input")return ze(t.in._def,e);if(e.pipeStrategy==="output")return ze(t.out._def,e);const r=ze(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ze(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function FS(t,e){return ze(t.type._def,e)}function VS(t,e){const n={type:"array",uniqueItems:!0,items:ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function HS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ze(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function BS(){return{not:Ot()}}function JS(){return Ot()}var GS=(t,e)=>ze(t.innerType._def,e),WS=(t,e,r)=>{switch(e){case z.ZodString:return s2(t,r);case z.ZodNumber:return jS(t);case z.ZodObject:return qS(t,r);case z.ZodBigInt:return _S(t);case z.ZodBoolean:return yS();case z.ZodDate:return n2(t,r);case z.ZodUndefined:return BS();case z.ZodNull:return AS();case z.ZodArray:return vS(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return MS(t,r);case z.ZodIntersection:return $S(t,r);case z.ZodTuple:return HS(t,r);case z.ZodRecord:return a2(t,r);case z.ZodLiteral:return ES(t);case z.ZodEnum:return TS(t);case z.ZodNativeEnum:return PS(t);case z.ZodNullable:return LS(t,r);case z.ZodOptional:return US(t,r);case z.ZodMap:return RS(t,r);case z.ZodSet:return VS(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return FS(t,r);case z.ZodNaN:case z.ZodNever:return OS();case z.ZodEffects:return SS(t,r);case z.ZodAny:return Ot();case z.ZodUnknown:return JS();case z.ZodDefault:return kS(t,r);case z.ZodBranded:return r2(t,r);case z.ZodReadonly:return GS(t,r);case z.ZodCatch:return wS(t,r);case z.ZodPipeline:return ZS(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function ze(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const l=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(l!==mS)return l}if(s&&!r){const l=KS(s,e);if(l!==void 0)return l}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=WS(t,t.typeName,e),i=typeof a=="function"?ze(a(),e):a;if(i&&YS(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return o.jsonSchema=i,l}return o.jsonSchema=i,i}var KS=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:hS(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ot()):e.$refStrategy==="seen"?Ot():void 0}},YS=(t,e,r)=>(t.description&&(r.description=t.description),r),QS=t=>{const e=gS(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},XS=(t,e)=>{var r;const n=QS(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,p])=>{var h;return{...c,[u]:(h=ze(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Ot()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=ze(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Ot(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const l=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},eT=XS;function tT(t,e){var r;const n=(r=void 0)!=null?r:!1;return co(()=>eT(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function rT(t,e){var r;const n=(r=void 0)!=null?r:!1;return co(()=>ul(t,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async s=>{const o=await dl(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function nT(t){return"_zod"in t}function kn(t,e){return nT(t)?rT(t):tT(t)}var du=Symbol.for("vercel.ai.schema");function co(t,{validate:e}={}){return{[du]:!0,_type:void 0,[di]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function sT(t){return typeof t=="object"&&t!==null&&du in t&&t[du]===!0&&"jsonSchema"in t&&"validate"in t}function pi(t){return t==null?co({properties:{},additionalProperties:!1}):sT(t)?t:typeof t=="function"?t():kn(t)}var{btoa:oT,atob:aT}=globalThis;function pu(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=aT(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function fi(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return oT(e)}function iT(t){return t instanceof Uint8Array?fi(t):t}function i2(t){return t?.replace(/\/$/,"")}function lT(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*l2({execute:t,input:e,options:r}){const n=t(e,r);if(lT(n)){let s;for await(const o of n)s=o,yield{type:"preliminary",output:o};yield{type:"final",output:s}}else yield{type:"final",output:await n}}var fu,c2;function cT(){if(c2)return fu;c2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(u,p)=>{for(var h in p)t(u,h,{get:p[h],enumerable:!0})},o=(u,p,h,d)=>{if(p&&typeof p=="object"||typeof p=="function")for(let f of r(p))!n.call(u,f)&&f!==h&&t(u,f,{get:()=>p[f],enumerable:!(d=e(p,f))||d.enumerable});return u},a=u=>o(t({},"__esModule",{value:!0}),u),i={};s(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),fu=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return fu}var hu,u2;function uT(){if(u2)return hu;u2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(p,h)=>{for(var d in h)t(p,d,{get:h[d],enumerable:!0})},o=(p,h,d,f)=>{if(h&&typeof h=="object"||typeof h=="function")for(let w of r(h))!n.call(p,w)&&w!==d&&t(p,w,{get:()=>h[w],enumerable:!(f=e(h,w))||f.enumerable});return p},a=p=>o(t({},"__esModule",{value:!0}),p),i={};s(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),hu=a(i);var l=cT();async function c(){return""}function u(){return""}return hu}var d2=uT(),dT="vercel.ai.gateway.error",mu=Symbol.for(dT),p2,f2,At=class b_ extends(f2=Error,p2=mu,f2){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[p2]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return b_.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&mu in e&&e[mu]===!0}},h2="GatewayAuthenticationError",pT=`vercel.ai.gateway.error.${h2}`,m2=Symbol.for(pT),g2,v2,gu=class k_ extends(v2=At,g2=m2,v2){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[g2]=!0,this.name=h2,this.type="authentication_error"}static isInstance(e){return At.hasMarker(e)&&m2 in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:s=401,cause:o}){let a;return e?a=`AI Gateway authentication failed: Invalid API key.
554
+ ]`;continue}o+=s[c],s[c]==="\\"?a=!0:i&&s[c]==="]"?i=!1:!i&&s[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function a2(t,e){var r,n,s,o,a,i;const l={type:"object",additionalProperties:(r=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=s2(t.keyType._def,e);return{...l,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=r2(t.keyType._def,e);return{...l,propertyNames:u}}}return l}function RS(t,e){if(e.mapStrategy==="record")return a2(t,e);const r=ze(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ot(),n=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ot();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function PS(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function OS(){return{not:Ot()}}function AS(){return{type:"null"}}var cu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function MS(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in cu&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=cu[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return NS(t,e)}var NS=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>ze(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function LS(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[cu[t.innerType._def.typeName],"null"]};const r=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function jS(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function qS(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const l=DS(i),c=ze(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const o=zS(t,e);return o!==void 0&&(r.additionalProperties=o),r}function zS(t,e){if(t.catchall._def.typeName!=="ZodNever")return ze(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function DS(t){try{return t.isOptional()}catch{return!0}}var US=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return ze(t.innerType._def,e);const n=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Ot()},n]}:Ot()},ZS=(t,e)=>{if(e.pipeStrategy==="input")return ze(t.in._def,e);if(e.pipeStrategy==="output")return ze(t.out._def,e);const r=ze(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ze(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function FS(t,e){return ze(t.type._def,e)}function VS(t,e){const n={type:"array",uniqueItems:!0,items:ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function HS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ze(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ze(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function BS(){return{not:Ot()}}function JS(){return Ot()}var GS=(t,e)=>ze(t.innerType._def,e),WS=(t,e,r)=>{switch(e){case z.ZodString:return s2(t,r);case z.ZodNumber:return jS(t);case z.ZodObject:return qS(t,r);case z.ZodBigInt:return _S(t);case z.ZodBoolean:return yS();case z.ZodDate:return n2(t,r);case z.ZodUndefined:return BS();case z.ZodNull:return AS();case z.ZodArray:return vS(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return MS(t,r);case z.ZodIntersection:return $S(t,r);case z.ZodTuple:return HS(t,r);case z.ZodRecord:return a2(t,r);case z.ZodLiteral:return ES(t);case z.ZodEnum:return TS(t);case z.ZodNativeEnum:return PS(t);case z.ZodNullable:return LS(t,r);case z.ZodOptional:return US(t,r);case z.ZodMap:return RS(t,r);case z.ZodSet:return VS(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return FS(t,r);case z.ZodNaN:case z.ZodNever:return OS();case z.ZodEffects:return SS(t,r);case z.ZodAny:return Ot();case z.ZodUnknown:return JS();case z.ZodDefault:return kS(t,r);case z.ZodBranded:return r2(t,r);case z.ZodReadonly:return GS(t,r);case z.ZodCatch:return wS(t,r);case z.ZodPipeline:return ZS(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function ze(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const l=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(l!==mS)return l}if(s&&!r){const l=KS(s,e);if(l!==void 0)return l}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=WS(t,t.typeName,e),i=typeof a=="function"?ze(a(),e):a;if(i&&YS(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return o.jsonSchema=i,l}return o.jsonSchema=i,i}var KS=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:hS(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ot()):e.$refStrategy==="seen"?Ot():void 0}},YS=(t,e,r)=>(t.description&&(r.description=t.description),r),QS=t=>{const e=gS(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},XS=(t,e)=>{var r;const n=QS(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,p])=>{var h;return{...c,[u]:(h=ze(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Ot()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=ze(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Ot(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const l=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},eT=XS;function tT(t,e){var r;const n=(r=void 0)!=null?r:!1;return co(()=>eT(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function rT(t,e){var r;const n=(r=void 0)!=null?r:!1;return co(()=>ul(t,{target:"draft-7",io:"output",reused:n?"ref":"inline"}),{validate:async s=>{const o=await dl(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function nT(t){return"_zod"in t}function kn(t,e){return nT(t)?rT(t):tT(t)}var uu=Symbol.for("vercel.ai.schema");function co(t,{validate:e}={}){return{[uu]:!0,_type:void 0,[di]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function sT(t){return typeof t=="object"&&t!==null&&uu in t&&t[uu]===!0&&"jsonSchema"in t&&"validate"in t}function pi(t){return t==null?co({properties:{},additionalProperties:!1}):sT(t)?t:typeof t=="function"?t():kn(t)}var{btoa:oT,atob:aT}=globalThis;function du(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=aT(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function fi(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return oT(e)}function iT(t){return t instanceof Uint8Array?fi(t):t}function i2(t){return t?.replace(/\/$/,"")}function lT(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*l2({execute:t,input:e,options:r}){const n=t(e,r);if(lT(n)){let s;for await(const o of n)s=o,yield{type:"preliminary",output:o};yield{type:"final",output:s}}else yield{type:"final",output:await n}}var pu,c2;function cT(){if(c2)return pu;c2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(u,p)=>{for(var h in p)t(u,h,{get:p[h],enumerable:!0})},o=(u,p,h,d)=>{if(p&&typeof p=="object"||typeof p=="function")for(let f of r(p))!n.call(u,f)&&f!==h&&t(u,f,{get:()=>p[f],enumerable:!(d=e(p,f))||d.enumerable});return u},a=u=>o(t({},"__esModule",{value:!0}),u),i={};s(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),pu=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return pu}var fu,u2;function uT(){if(u2)return fu;u2=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,s=(p,h)=>{for(var d in h)t(p,d,{get:h[d],enumerable:!0})},o=(p,h,d,f)=>{if(h&&typeof h=="object"||typeof h=="function")for(let w of r(h))!n.call(p,w)&&w!==d&&t(p,w,{get:()=>h[w],enumerable:!(f=e(h,w))||f.enumerable});return p},a=p=>o(t({},"__esModule",{value:!0}),p),i={};s(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),fu=a(i);var l=cT();async function c(){return""}function u(){return""}return fu}var d2=uT(),dT="vercel.ai.gateway.error",hu=Symbol.for(dT),p2,f2,At=class b_ extends(f2=Error,p2=hu,f2){constructor({message:e,statusCode:r=500,cause:n}){super(e),this[p2]=!0,this.statusCode=r,this.cause=n}static isInstance(e){return b_.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&hu in e&&e[hu]===!0}},h2="GatewayAuthenticationError",pT=`vercel.ai.gateway.error.${h2}`,m2=Symbol.for(pT),g2,v2,mu=class k_ extends(v2=At,g2=m2,v2){constructor({message:e="Authentication failed",statusCode:r=401,cause:n}={}){super({message:e,statusCode:r,cause:n}),this[g2]=!0,this.name=h2,this.type="authentication_error"}static isInstance(e){return At.hasMarker(e)&&m2 in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:n="Authentication failed",statusCode:s=401,cause:o}){let a;return e?a=`AI Gateway authentication failed: Invalid API key.
555
555
 
556
556
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
557
557
 
@@ -566,15 +566,15 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
566
566
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
567
567
 
568
568
  Option 2 - OIDC token:
569
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new k_({message:a,statusCode:s,cause:o})}},_2="GatewayInvalidRequestError",fT=`vercel.ai.gateway.error.${_2}`,y2=Symbol.for(fT),w2,b2,hT=class extends(b2=At,w2=y2,b2){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[w2]=!0,this.name=_2,this.type="invalid_request_error"}static isInstance(t){return At.hasMarker(t)&&y2 in t}},k2="GatewayRateLimitError",mT=`vercel.ai.gateway.error.${k2}`,S2=Symbol.for(mT),T2,C2,gT=class extends(C2=At,T2=S2,C2){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[T2]=!0,this.name=k2,this.type="rate_limit_exceeded"}static isInstance(t){return At.hasMarker(t)&&S2 in t}},$2="GatewayModelNotFoundError",vT=`vercel.ai.gateway.error.${$2}`,E2=Symbol.for(vT),_T=Qn(()=>kn(C({modelId:v()}))),x2,I2,R2=class extends(I2=At,x2=E2,I2){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[x2]=!0,this.name=$2,this.type="model_not_found",this.modelId=r}static isInstance(t){return At.hasMarker(t)&&E2 in t}},P2="GatewayInternalServerError",yT=`vercel.ai.gateway.error.${P2}`,O2=Symbol.for(yT),A2,M2,N2=class extends(M2=At,A2=O2,M2){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[A2]=!0,this.name=P2,this.type="internal_server_error"}static isInstance(t){return At.hasMarker(t)&&O2 in t}},L2="GatewayResponseError",wT=`vercel.ai.gateway.error.${L2}`,j2=Symbol.for(wT),q2,z2,bT=class extends(z2=At,q2=j2,z2){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:n,cause:s}={}){super({message:t,statusCode:e,cause:s}),this[q2]=!0,this.name=L2,this.type="response_error",this.response=r,this.validationError=n}static isInstance(t){return At.hasMarker(t)&&j2 in t}};async function D2({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:n,authMethod:s}){const o=await Kt({value:t,schema:kT});if(!o.success)return new bT({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:o.error,cause:n});const a=o.value,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return gu.createContextualError({apiKeyProvided:s==="api-key",oidcTokenProvided:s==="oidc",statusCode:e,cause:n});case"invalid_request_error":return new hT({message:l,statusCode:e,cause:n});case"rate_limit_exceeded":return new gT({message:l,statusCode:e,cause:n});case"model_not_found":{const c=await Kt({value:a.error.param,schema:_T});return new R2({message:l,statusCode:e,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new N2({message:l,statusCode:e,cause:n});default:return new N2({message:l,statusCode:e,cause:n})}}var kT=Qn(()=>kn(C({error:C({message:v(),type:v().nullish(),param:Le().nullish(),code:ce([v(),L()]).nullish()})})));function Kr(t,e){var r;return At.isInstance(t)?t:Ve.isInstance(t)?D2({response:ST(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):D2({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function ST(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var U2="ai-gateway-auth-method";async function ts(t){const e=await Kt({value:t[U2],schema:TT});return e.success?e.value:void 0}var TT=Qn(()=>kn(ce([j("api-key"),j("oidc")]))),Z2=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Wm({url:`${this.config.baseURL}/config`,headers:await pr(this.config.headers()),successfulResponseHandler:es(CT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await Kr(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await Wm({url:`${t.origin}/v1/credits`,headers:await pr(this.config.headers()),successfulResponseHandler:es($T),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await Kr(t)}}},CT=Qn(()=>kn(C({models:N(C({id:v(),name:v(),description:v().nullish(),pricing:C({input:v(),output:v(),input_cache_read:v().nullish(),input_cache_write:v().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:n})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:j("v2"),provider:v(),modelId:v()}),modelType:Ce(["language","embedding","image"]).nullish()}))}))),$T=Qn(()=>kn(C({balance:v(),total_used:v()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),ET=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await pr(this.config.headers());try{const{responseHeaders:o,value:a,rawValue:i}=await Xn({url:this.getUrl(),headers:Yn(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await pr(this.config.o11yHeaders)),body:e,successfulResponseHandler:es(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:e},response:{headers:o,body:i},warnings:r}}catch(o){throw await Kr(o,await ts(s))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await pr(this.config.headers());try{const{value:o,responseHeaders:a}=await Xn({url:this.getUrl(),headers:Yn(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await pr(this.config.o11yHeaders)),body:e,successfulResponseHandler:e2(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:e},response:{headers:a}}}catch(o){throw await Kr(o,await ts(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const s=Uint8Array.from(n.data),o=Buffer.from(s).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${o}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},xT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;const o=await pr(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Xn({url:this.getUrl(),headers:Yn(o,e??{},this.getModelConfigHeaders(),await pr(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...n?{providerOptions:n}:{}},successfulResponseHandler:es(IT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(s=i.usage)!=null?s:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await Kr(a,await ts(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},IT=Qn(()=>kn(C({embeddings:N(N(L())),usage:C({tokens:L()}).nullish(),providerMetadata:Se(v(),Se(v(),Le())).optional()}))),RT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var l;const c=await pr(this.config.headers());try{const{responseHeaders:u,value:p,rawValue:h}=await Xn({url:this.getUrl(),headers:Yn(c,a??{},this.getModelConfigHeaders(),await pr(this.config.o11yHeaders)),body:{prompt:t,n:e,...r&&{size:r},...n&&{aspectRatio:n},...s&&{seed:s},...o&&{providerOptions:o}},successfulResponseHandler:es(OT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:d=>d}),...i&&{abortSignal:i},fetch:this.config.fetch});return{images:p.images,warnings:(l=p.warnings)!=null?l:[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw Kr(u,await ts(c))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},PT=C({images:N(Le()).optional()}).catchall(Le()),OT=C({images:N(v()),warnings:N(C({type:j("other"),message:v()})).optional(),providerMetadata:Se(v(),PT).optional()});async function AT(){var t;return(t=d2.getContext().headers)==null?void 0:t["x-vercel-id"]}var MT="2.0.18",NT="0.0.1";function LT(t={}){var e,r;let n=null,s=null;const o=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let a=0;const i=(r=i2(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const f=await qT(t);if(f)return Wr({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":NT,[U2]:f.authMethod,...t.headers},`ai-sdk/gateway/${MT}`);throw gu.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const f=ui({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),w=ui({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=ui({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const y=await AT();return{...f&&{"ai-o11y-deployment-id":f},...w&&{"ai-o11y-environment":w},...m&&{"ai-o11y-region":m},...y&&{"ai-o11y-request-id":y}}}},u=f=>new ET(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),p=async()=>{var f,w,m;const y=(m=(w=(f=t._internal)==null?void 0:f.currentDate)==null?void 0:w.call(f).getTime())!=null?m:Date.now();return(!n||y-a>o)&&(a=y,n=new Z2({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(_=>(s=_,_)).catch(async _=>{throw await Kr(_,await ts(await l()))})),s?Promise.resolve(s):n},h=async()=>new Z2({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async f=>{throw await Kr(f,await ts(await l()))}),d=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(f)};return d.getAvailableModels=p,d.getCredits=h,d.imageModel=f=>new RT(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),d.languageModel=u,d.textEmbeddingModel=f=>new xT(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),d}var jT=LT();async function qT(t){const e=ui({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await d2.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var zT=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Sn="1.9.0",F2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function DT(t){var e=new Set([t]),r=new Set,n=t.match(F2);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(l){return l===t};function o(i){return r.add(i),!1}function a(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(F2);if(!c)return o(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||s.major!==u.major?o(l):s.major===0?s.minor===u.minor&&s.patch<=u.patch?a(l):o(l):s.minor<=u.minor?a(l):o(l)}}var UT=DT(Sn),ZT=Sn.split(".")[0],uo=Symbol.for("opentelemetry.js.api."+ZT),po=zT;function fo(t,e,r,n){var s;n===void 0&&(n=!1);var o=po[uo]=(s=po[uo])!==null&&s!==void 0?s:{version:Sn};if(!n&&o[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(o.version!==Sn){var a=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+t+" does not match previously registered API v"+Sn);return r.error(a.stack||a.message),!1}return o[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Sn+"."),!0}function Tn(t){var e,r,n=(e=po[uo])===null||e===void 0?void 0:e.version;if(!(!n||!UT(n)))return(r=po[uo])===null||r===void 0?void 0:r[t]}function ho(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Sn+".");var r=po[uo];r&&delete r[t]}var FT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},VT=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},HT=(function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("verbose",this._namespace,e)},t})();function mo(t,e,r){var n=Tn("diag");if(n)return r.unshift(e),n[t].apply(n,VT([],FT(r),!1))}var Mt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Mt||(Mt={}));function BT(t,e){t<Mt.NONE?t=Mt.NONE:t>Mt.ALL&&(t=Mt.ALL),e=e||{};function r(n,s){var o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",Mt.ERROR),warn:r("warn",Mt.WARN),info:r("info",Mt.INFO),debug:r("debug",Mt.DEBUG),verbose:r("verbose",Mt.VERBOSE)}}var JT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},GT=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},WT="diag",fr=(function(){function t(){function e(s){return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];var i=Tn("diag");if(i)return i[s].apply(i,GT([],JT(o),!1))}}var r=this,n=function(s,o){var a,i,l;if(o===void 0&&(o={logLevel:Mt.INFO}),s===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof o=="number"&&(o={logLevel:o});var u=Tn("diag"),p=BT((i=o.logLevel)!==null&&i!==void 0?i:Mt.INFO,s);if(u&&!o.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+h),p.warn("Current logger will overwrite one already registered from "+h)}return fo("diag",p,r,!0)};r.setLogger=n,r.disable=function(){ho(WT,r)},r.createComponentLogger=function(s){return new HT(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t})(),KT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},YT=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},QT=(function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=KT(e,2),n=r[0],s=r[1];return[n,s]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var o=new t(this._entries);try{for(var a=YT(n),i=a.next();!i.done;i=a.next()){var l=i.value;o._entries.delete(l)}}catch(c){e={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}return o},t.prototype.clear=function(){return new t},t})();fr.instance();function XT(t){return t===void 0&&(t={}),new QT(new Map(Object.entries(t)))}function V2(t){return Symbol.for(t)}var eC=(function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new t(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t})(),tC=new eC,Cn=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(n[o]=s[o])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),rC=(function(){function t(){}return t.prototype.createGauge=function(e,r){return pC},t.prototype.createHistogram=function(e,r){return fC},t.prototype.createCounter=function(e,r){return dC},t.prototype.createUpDownCounter=function(e,r){return hC},t.prototype.createObservableGauge=function(e,r){return gC},t.prototype.createObservableCounter=function(e,r){return mC},t.prototype.createObservableUpDownCounter=function(e,r){return vC},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t})(),hi=(function(){function t(){}return t})(),nC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(hi),sC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(hi),oC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(hi),aC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(hi),vu=(function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t})(),iC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(vu),lC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(vu),cC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(vu),uC=new rC,dC=new nC,pC=new oC,fC=new aC,hC=new sC,mC=new iC,gC=new lC,vC=new cC,_C={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},yC={set:function(t,e,r){t!=null&&(t[e]=r)}},wC=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},bC=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},kC=(function(){function t(){}return t.prototype.active=function(){return tC},t.prototype.with=function(e,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,bC([n],wC(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),SC=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},TC=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},_u="context",CC=new kC,mi=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return fo(_u,e,fr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return(s=this._getContextManager()).with.apply(s,TC([e,r,n],SC(o),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Tn(_u)||CC},t.prototype.disable=function(){this._getContextManager().disable(),ho(_u,fr.instance())},t})(),yu;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(yu||(yu={}));var H2="0000000000000000",B2="00000000000000000000000000000000",$C={traceId:B2,spanId:H2,traceFlags:yu.NONE},go=(function(){function t(e){e===void 0&&(e=$C),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t})(),wu=V2("OpenTelemetry Context Key SPAN");function bu(t){return t.getValue(wu)||void 0}function EC(){return bu(mi.getInstance().active())}function ku(t,e){return t.setValue(wu,e)}function xC(t){return t.deleteValue(wu)}function IC(t,e){return ku(t,new go(e))}function J2(t){var e;return(e=bu(t))===null||e===void 0?void 0:e.spanContext()}var RC=/^([0-9a-f]{32})$/i,PC=/^[0-9a-f]{16}$/i;function OC(t){return RC.test(t)&&t!==B2}function AC(t){return PC.test(t)&&t!==H2}function G2(t){return OC(t.traceId)&&AC(t.spanId)}function MC(t){return new go(t)}var Su=mi.getInstance(),W2=(function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=Su.active());var s=!!r?.root;if(s)return new go;var o=n&&J2(n);return NC(o)&&G2(o)?new go(o):new go},t.prototype.startActiveSpan=function(e,r,n,s){var o,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,a=n,i=s);var l=a??Su.active(),c=this.startSpan(e,o,l),u=ku(l,c);return Su.with(u,i,void 0,c)}},t})();function NC(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var LC=new W2,jC=(function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):LC},t})(),qC=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new W2},t})(),zC=new qC,K2=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new jC(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:zC},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t})(),gi;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(gi||(gi={})),mi.getInstance(),fr.instance();var DC=(function(){function t(){}return t.prototype.getMeter=function(e,r,n){return uC},t})(),UC=new DC,Tu="metrics",ZC=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return fo(Tu,e,fr.instance())},t.prototype.getMeterProvider=function(){return Tn(Tu)||UC},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){ho(Tu,fr.instance())},t})();ZC.getInstance();var FC=(function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t})(),Cu=V2("OpenTelemetry Baggage Key");function Y2(t){return t.getValue(Cu)||void 0}function VC(){return Y2(mi.getInstance().active())}function HC(t,e){return t.setValue(Cu,e)}function BC(t){return t.deleteValue(Cu)}var $u="propagation",JC=new FC,GC=(function(){function t(){this.createBaggage=XT,this.getBaggage=Y2,this.getActiveBaggage=VC,this.setBaggage=HC,this.deleteBaggage=BC}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return fo($u,e,fr.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=yC),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=_C),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){ho($u,fr.instance())},t.prototype._getGlobalPropagator=function(){return Tn($u)||JC},t})();GC.getInstance();var Eu="trace",WC=(function(){function t(){this._proxyTracerProvider=new K2,this.wrapSpanContext=MC,this.isSpanContextValid=G2,this.deleteSpan=xC,this.getSpan=bu,this.getActiveSpan=EC,this.getSpanContext=J2,this.setSpan=ku,this.setSpanContext=IC}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=fo(Eu,this._proxyTracerProvider,fr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return Tn(Eu)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){ho(Eu,fr.instance()),this._proxyTracerProvider=new K2},t})(),KC=WC.getInstance(),YC=Object.defineProperty,QC=(t,e)=>{for(var r in e)YC(t,r,{get:e[r],enumerable:!0})},Q2="AI_NoOutputSpecifiedError",X2=`vercel.ai.error.${Q2}`,XC=Symbol.for(X2),eg,tg=class extends ve{constructor({message:t="No output specified."}={}){super({name:Q2,message:t}),this[eg]=!0}static isInstance(t){return ve.hasMarker(t,X2)}};eg=XC;function e8(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let n=`${e} The tool "${r}" is not supported by this model`;return t.details&&(n+=` - ${t.details}`),n}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var t8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",rg=!1,ng=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}rg||(rg=!0,console.info(t8));for(const r of t)console.warn(e8(r))}},sg="AI_InvalidArgumentError",og=`vercel.ai.error.${sg}`,r8=Symbol.for(og),ag,hr=class extends ve{constructor({parameter:t,value:e,message:r}){super({name:sg,message:`Invalid argument for parameter ${t}: ${r}`}),this[ag]=!0,this.parameter=t,this.value=e}static isInstance(t){return ve.hasMarker(t,og)}};ag=r8;var ig="AI_InvalidToolInputError",lg=`vercel.ai.error.${ig}`,n8=Symbol.for(lg),cg,ug=class extends ve{constructor({toolInput:t,toolName:e,cause:r,message:n=`Invalid input for tool ${e}: ${Kn(r)}`}){super({name:ig,message:n,cause:r}),this[cg]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return ve.hasMarker(t,lg)}};cg=n8;var dg="AI_NoObjectGeneratedError",pg=`vercel.ai.error.${dg}`,s8=Symbol.for(pg),fg,hg=class extends ve{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s,finishReason:o}){super({name:dg,message:t,cause:e}),this[fg]=!0,this.text=r,this.response=n,this.usage=s,this.finishReason=o}static isInstance(t){return ve.hasMarker(t,pg)}};fg=s8;var mg="AI_NoOutputGeneratedError",gg=`vercel.ai.error.${mg}`,o8=Symbol.for(gg),vg,a8=class extends ve{constructor({message:t="No output generated.",cause:e}={}){super({name:mg,message:t,cause:e}),this[vg]=!0}static isInstance(t){return ve.hasMarker(t,gg)}};vg=o8;var _g="AI_NoSuchToolError",yg=`vercel.ai.error.${_g}`,i8=Symbol.for(yg),wg,xu=class extends ve{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:_g,message:r}),this[wg]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return ve.hasMarker(t,yg)}};wg=i8;var bg="AI_ToolCallRepairError",kg=`vercel.ai.error.${bg}`,l8=Symbol.for(kg),Sg,c8=class extends ve{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Kn(t)}`}){super({name:bg,message:r,cause:t}),this[Sg]=!0,this.originalError=e}static isInstance(t){return ve.hasMarker(t,kg)}};Sg=l8;var u8=class extends ve{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},Tg="AI_InvalidMessageRoleError",Cg=`vercel.ai.error.${Tg}`,d8=Symbol.for(Cg),$g,p8=class extends ve{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Tg,message:e}),this[$g]=!0,this.role=t}static isInstance(t){return ve.hasMarker(t,Cg)}};$g=d8;var Eg="AI_DownloadError",xg=`vercel.ai.error.${Eg}`,f8=Symbol.for(xg),Ig,Iu=class extends ve{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Eg,message:s,cause:n}),this[Ig]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return ve.hasMarker(t,xg)}};Ig=f8;var Rg="AI_RetryError",Pg=`vercel.ai.error.${Rg}`,h8=Symbol.for(Pg),Og,Ag=class extends ve{constructor({message:t,reason:e,errors:r}){super({name:Rg,message:t}),this[Og]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return ve.hasMarker(t,Pg)}};Og=h8;function vi(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new u8({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return m8().languageModel(t)}function m8(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:jT}var g8=[{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]}],v8=t=>{const e=typeof t=="string"?pu(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function _8(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?v8(t):t}function y8({data:t,signatures:e}){const r=_8(t),n=typeof r=="string"?pu(r.substring(0,Math.min(r.length,24))):r;for(const s of e)if(n.length>=s.bytesPrefix.length&&s.bytesPrefix.every((o,a)=>o===null||n[a]===o))return s.mediaType}var Mg="5.0.106",w8=async({url:t})=>{var e;const r=t.toString();try{const n=await fetch(r,{headers:Wr({},`ai-sdk/${Mg}`,lo())});if(!n.ok)throw new Iu({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(e=n.headers.get("content-type"))!=null?e:void 0}}catch(n){throw Iu.isInstance(n)?n:new Iu({url:r,cause:n})}},b8=(t=w8)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function k8(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Ng=ce([v(),Pa(Uint8Array),Pa(ArrayBuffer),Hf(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Lg(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=k8(t.toString());if(e==null||r==null)throw new ve({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function S8(t){return typeof t=="string"?t:t instanceof ArrayBuffer?fi(new Uint8Array(t)):fi(t)}async function jg({prompt:t,supportedUrls:e,download:r=b8()}){const n=await C8(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(s=>T8({message:s,downloadedAssets:n}))]}function T8({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(n=>$8(n,e)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const s=n.providerOptions;switch(n.type){case"file":{const{data:o,mediaType:a}=Lg(n.data);return{type:"file",data:o,filename:n.filename,mediaType:a??n.mediaType,providerOptions:s}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:s};case"text":return{type:"text",text:n.text,providerOptions:s};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:s};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:s}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:t.providerOptions};default:{const n=r;throw new p8({role:n})}}}async function C8(t,e,r){const n=t.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var a;const i=(a=o.mediaType)!=null?a:o.type==="image"?"image/*":void 0;let l=o.type==="image"?o.image:o.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&tS({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:r})})),s=await e(n);return Object.fromEntries(s.map((o,a)=>o==null?null:[n[a].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function $8(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let n;const s=t.type;switch(s){case"image":n=t.image;break;case"file":n=t.data;break;default:throw new Error(`Unsupported part type: ${s}`)}const{data:o,mediaType:a}=Lg(n);let i=a??t.mediaType,l=o;if(l instanceof URL){const c=e[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(s){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=y8({data:l,signatures:g8}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function Ru({maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,seed:a,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new hr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new hr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new hr({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new hr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new hr({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new hr({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new hr({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new hr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,stopSequences:i,seed:a}}function E8(t){return t!=null&&Object.keys(t).length>0}function qg({tools:t,toolChoice:e,activeTools:r}){return E8(t)?{tools:(r!=null?Object.entries(t).filter(([s])=>r.includes(s)):Object.entries(t)).map(([s,o])=>{const a=o.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:s,description:o.description,inputSchema:pi(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:s,id:o.id,args:o.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var vo=Vf(()=>ce([fl(),v(),L(),ge(),Se(v(),vo),N(vo)])),mr=Se(v(),Se(v(),vo)),zg=C({type:j("text"),text:v(),providerOptions:mr.optional()}),x8=C({type:j("image"),image:ce([Ng,Pa(URL)]),mediaType:v().optional(),providerOptions:mr.optional()}),Dg=C({type:j("file"),data:ce([Ng,Pa(URL)]),filename:v().optional(),mediaType:v(),providerOptions:mr.optional()}),I8=C({type:j("reasoning"),text:v(),providerOptions:mr.optional()}),R8=C({type:j("tool-call"),toolCallId:v(),toolName:v(),input:Le(),providerOptions:mr.optional(),providerExecuted:ge().optional()}),P8=et("type",[C({type:j("text"),value:v()}),C({type:j("json"),value:vo}),C({type:j("error-text"),value:v()}),C({type:j("error-json"),value:vo}),C({type:j("content"),value:N(ce([C({type:j("text"),text:v()}),C({type:j("media"),data:v(),mediaType:v()})]))})]),Ug=C({type:j("tool-result"),toolCallId:v(),toolName:v(),output:P8,providerOptions:mr.optional()}),O8=C({role:j("system"),content:v(),providerOptions:mr.optional()}),A8=C({role:j("user"),content:ce([v(),N(ce([zg,x8,Dg]))]),providerOptions:mr.optional()}),M8=C({role:j("assistant"),content:ce([v(),N(ce([zg,Dg,I8,R8,Ug]))]),providerOptions:mr.optional()}),N8=C({role:j("tool"),content:N(Ug),providerOptions:mr.optional()}),L8=ce([O8,A8,M8,N8]);async function Zg(t){if(t.prompt==null&&t.messages==null)throw new _n({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new _n({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new _n({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new _n({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new _n({prompt:t,message:"messages must not be empty"});const r=await Kt({value:e,schema:N(L8)});if(!r.success)throw new _n({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Fg(t){return gu.isInstance(t)||R2.isInstance(t)?new ve({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function rs({operationId:t,telemetry:e}){return{"operation.name":`${t}${e?.functionId!=null?` ${e.functionId}`:""}`,"resource.name":e?.functionId,"ai.operationId":t,"ai.telemetry.functionId":e?.functionId}}function Vg({model:t,settings:e,telemetry:r,headers:n}){var s;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((o,[a,i])=>(o[`ai.settings.${a}`]=i,o),{}),...Object.entries((s=r?.metadata)!=null?s:{}).reduce((o,[a,i])=>(o[`ai.telemetry.metadata.${a}`]=i,o),{}),...Object.entries(n??{}).reduce((o,[a,i])=>(i!==void 0&&(o[`ai.request.headers.${a}`]=i),o),{})}}var j8={startSpan(){return _i},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(_i);if(typeof r=="function")return r(_i);if(typeof n=="function")return n(_i)}},_i={spanContext(){return q8},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}},q8={traceId:"",spanId:"",traceFlags:0};function Hg({isEnabled:t=!1,tracer:e}={}){return t?e||KC.getTracer("ai"):j8}function ns({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async o=>{try{const a=await n(o);return s&&o.end(),a}catch(a){try{Pu(o,a)}finally{o.end()}throw a}})}function Pu(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:gi.ERROR,message:e.message})):t.setStatus({code:gi.ERROR})}function Dt({telemetry:t,attributes:e}){return t?.isEnabled!==!0?{}:Object.entries(e).reduce((r,[n,s])=>{if(s==null)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if(t?.recordInputs===!1)return r;const o=s.input();return o==null?r:{...r,[n]:o}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if(t?.recordOutputs===!1)return r;const o=s.output();return o==null?r:{...r,[n]:o}}return{...r,[n]:s}},{})}function Bg(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?S8(r.data):r.data}:r)})))}function Jg(t,e){return{inputTokens:_o(t.inputTokens,e.inputTokens),outputTokens:_o(t.outputTokens,e.outputTokens),totalTokens:_o(t.totalTokens,e.totalTokens),reasoningTokens:_o(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:_o(t.cachedInputTokens,e.cachedInputTokens)}}function _o(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function Ou(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function z8({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let n;const s=r["retry-after-ms"];if(s){const a=parseFloat(s);Number.isNaN(a)||(n=a)}const o=r["retry-after"];if(o&&n===void 0){const a=parseFloat(o);Number.isNaN(a)?n=Date.parse(o)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<e)?n:e}var D8=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:n}={})=>async s=>Gg(s,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:n});async function Gg(t,{maxRetries:e,delayInMs:r,backoffFactor:n,abortSignal:s},o=[]){try{return await t()}catch(a){if(yn(a)||e===0)throw a;const i=ou(a),l=[...o,a],c=l.length;if(c>e)throw new Ag({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Ve.isInstance(a)&&a.isRetryable===!0&&c<=e)return await Y5(z8({error:a,exponentialBackoffDelay:r}),{abortSignal:s}),Gg(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n,abortSignal:s},l);throw c===1?a:new Ag({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Wg({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new hr({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new hr({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:D8({maxRetries:r,abortSignal:e})}}function Kg(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var Yg=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=fi(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=pu(this.base64Data)),this.uint8ArrayData}},U8=class extends Yg{constructor(t){super(t),this.type="file"}};async function Qg({toolCall:t,tools:e,repairToolCall:r,system:n,messages:s}){try{if(e==null)throw new xu({toolName:t.toolName});try{return await Xg({toolCall:t,tools:e})}catch(o){if(r==null||!(xu.isInstance(o)||ug.isInstance(o)))throw o;let a=null;try{a=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return pi(l).jsonSchema},system:n,messages:s,error:o})}catch(i){throw new c8({cause:i,originalError:o})}if(a==null)throw o;return await Xg({toolCall:a,tools:e})}}catch(o){const a=await wn({text:t.input}),i=a.success?a.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:o,providerMetadata:t.providerMetadata}}}async function Xg({toolCall:t,tools:e}){const r=t.toolName,n=e[r];if(n==null)throw new xu({toolName:t.toolName,availableTools:Object.keys(e)});const s=pi(n.inputSchema),o=t.input.trim()===""?await Kt({value:{},schema:s}):await wn({text:t.input,schema:s});if(o.success===!1)throw new ug({toolName:r,toolInput:t.input,cause:o.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var ev=class{constructor({content:t,finishReason:e,usage:r,warnings:n,request:s,response:o,providerMetadata:a}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=n,this.request=s,this.response=o,this.providerMetadata=a}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function Au(t){return({steps:e})=>e.length===t}async function tv({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function Mu({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:Kn(t)}:r==="json"?{type:"error-json",value:rv(t)}:e?.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:rv(t)}}function rv(t){return t===void 0?null:t}function Nu({content:t,tools:e}){const r=[],n=t.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Mu({tool:e?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Mu({tool:e?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const s=t.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Mu({tool:e?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"}),...o.providerMetadata!=null?{providerOptions:o.providerMetadata}:{}}));return s.length>0&&r.push({role:"tool",content:s}),r}var Z8=ao({prefix:"aitxt",size:24});async function nv({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Au(1),experimental_output:u,experimental_telemetry:p,providerOptions:h,experimental_activeTools:d,activeTools:f=d,experimental_prepareStep:w,prepareStep:m=w,experimental_repairToolCall:y,experimental_download:_,experimental_context:g,_internal:{generateId:b=Z8,currentDate:k=()=>new Date}={},onStepFinish:S,...T}){const x=vi(t),I=Ou(c),{maxRetries:A,retry:P}=Wg({maxRetries:a,abortSignal:i}),D=Ru(T),U=Wr(l??{},`ai/${Mg}`),V=Vg({model:x,telemetry:p,headers:U,settings:{...D,maxRetries:A}}),se=await Zg({system:n,prompt:s,messages:o}),fe=Hg(p);try{return await ns({name:"ai.generateText",attributes:Dt({telemetry:p,attributes:{...rs({operationId:"ai.generateText",telemetry:p}),...V,"ai.model.provider":x.provider,"ai.model.id":x.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:s,messages:o})}}}),tracer:fe,fn:async de=>{var re,_e,H,O,F,q,E;const R=Ru(T);let $,B=[],W=[];const ye=[],pe=[];do{const G=[...se.messages,...ye],K=await m?.({model:x,steps:pe,stepNumber:pe.length,messages:G}),X=vi((re=K?.model)!=null?re:x),ue=await jg({prompt:{system:(_e=K?.system)!=null?_e:se.system,messages:(H=K?.messages)!=null?H:G},supportedUrls:await X.supportedUrls,download:_}),{toolChoice:he,tools:He}=qg({tools:e,toolChoice:(O=K?.toolChoice)!=null?O:r,activeTools:(F=K?.activeTools)!=null?F:f});$=await P(()=>{var xe;return ns({name:"ai.generateText.doGenerate",attributes:Dt({telemetry:p,attributes:{...rs({operationId:"ai.generateText.doGenerate",telemetry:p}),...V,"ai.model.provider":X.provider,"ai.model.id":X.modelId,"ai.prompt.messages":{input:()=>Bg(ue)},"ai.prompt.tools":{input:()=>He?.map(Et=>JSON.stringify(Et))},"ai.prompt.toolChoice":{input:()=>he!=null?JSON.stringify(he):void 0},"gen_ai.system":X.provider,"gen_ai.request.model":X.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxOutputTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.stop_sequences":T.stopSequences,"gen_ai.request.temperature":(xe=T.temperature)!=null?xe:void 0,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:fe,fn:async Et=>{var Pr,xt,it,Ut,Xr,en,cs,Pi;const nt=await X.doGenerate({...R,tools:He,toolChoice:he,responseFormat:u?.responseFormat,prompt:ue,providerOptions:h,abortSignal:i,headers:U}),Or={id:(xt=(Pr=nt.response)==null?void 0:Pr.id)!=null?xt:b(),timestamp:(Ut=(it=nt.response)==null?void 0:it.timestamp)!=null?Ut:k(),modelId:(en=(Xr=nt.response)==null?void 0:Xr.modelId)!=null?en:X.modelId,headers:(cs=nt.response)==null?void 0:cs.headers,body:(Pi=nt.response)==null?void 0:Pi.body};return Et.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":nt.finishReason,"ai.response.text":{output:()=>Kg(nt.content)},"ai.response.toolCalls":{output:()=>{const Ar=sv(nt.content);return Ar==null?void 0:JSON.stringify(Ar)}},"ai.response.id":Or.id,"ai.response.model":Or.modelId,"ai.response.timestamp":Or.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(nt.providerMetadata),"ai.usage.promptTokens":nt.usage.inputTokens,"ai.usage.completionTokens":nt.usage.outputTokens,"gen_ai.response.finish_reasons":[nt.finishReason],"gen_ai.response.id":Or.id,"gen_ai.response.model":Or.modelId,"gen_ai.usage.input_tokens":nt.usage.inputTokens,"gen_ai.usage.output_tokens":nt.usage.outputTokens}})),{...nt,response:Or}}})});const Je=await Promise.all($.content.filter(xe=>xe.type==="tool-call").map(xe=>Qg({toolCall:xe,tools:e,repairToolCall:y,system:n,messages:G})));for(const xe of Je){if(xe.invalid)continue;const Et=e[xe.toolName];Et?.onInputAvailable!=null&&await Et.onInputAvailable({input:xe.input,toolCallId:xe.toolCallId,messages:G,abortSignal:i,experimental_context:g})}const ee=Je.filter(xe=>xe.invalid&&xe.dynamic);W=[];for(const xe of ee)W.push({type:"tool-error",toolCallId:xe.toolCallId,toolName:xe.toolName,input:xe.input,error:ou(xe.error),dynamic:!0});B=Je.filter(xe=>!xe.providerExecuted),e!=null&&W.push(...await F8({toolCalls:B.filter(xe=>!xe.invalid),tools:e,tracer:fe,telemetry:p,messages:G,abortSignal:i,experimental_context:g}));const be=H8({content:$.content,toolCalls:Je,toolOutputs:W});ye.push(...Nu({content:be,tools:e}));const yt=new ev({content:be,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(q=$.request)!=null?q:{},response:{...$.response,messages:structuredClone(ye)}});ng((E=$.warnings)!=null?E:[]),pe.push(yt),await S?.(yt)}while(B.length>0&&W.length===B.length&&!await tv({stopConditions:I,steps:pe}));de.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>Kg($.content)},"ai.response.toolCalls":{output:()=>{const G=sv($.content);return G==null?void 0:JSON.stringify(G)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const M=pe[pe.length-1];let Z;return M.finishReason==="stop"&&(Z=await u?.parseOutput({text:M.text},{response:M.response,usage:M.usage,finishReason:M.finishReason})),new V8({steps:pe,resolvedOutput:Z})}})}catch(de){throw Fg(de)}}async function F8({toolCalls:t,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:o,experimental_context:a}){return(await Promise.all(t.map(async({toolCallId:l,toolName:c,input:u})=>{const p=e[c];if(p?.execute!=null)return ns({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...rs({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async h=>{try{const d=l2({execute:p.execute.bind(p),input:u,options:{toolCallId:l,messages:s,abortSignal:o,experimental_context:a}});let f;for await(const w of d)w.type==="final"&&(f=w.output);try{h.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:f,dynamic:p.type==="dynamic"}}catch(d){return Pu(h,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:p.type==="dynamic"}}}})}))).filter(l=>l!=null)}var V8=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>Jg(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new tg;return this.resolvedOutput}};function sv(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function H8({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new Yg(n)};case"tool-call":return e.find(s=>s.toolCallId===n.toolCallId);case"tool-result":{const s=e.find(o=>o.toolCallId===n.toolCallId);if(s==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,error:n.result,providerExecuted:!0,dynamic:s.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,output:n.result,providerExecuted:!0,dynamic:s.dynamic}}}}),...r]}function yi(t,e){const r=new Headers(t??{});for(const[n,s]of Object.entries(e))r.has(n)||r.set(n,s);return r}function B8({status:t,statusText:e,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:yi(r,{"content-type":"text/plain; charset=utf-8"})})}function ov({response:t,status:e,statusText:r,headers:n,stream:s}){t.writeHead(e??200,r,n);const o=s.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await o.read();if(i)break;t.write(l)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function J8({response:t,status:e,statusText:r,headers:n,textStream:s}){ov({response:t,status:e,statusText:r,headers:Object.fromEntries(yi(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:s.pipeThrough(new TextEncoderStream)})}var av=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
569
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new k_({message:a,statusCode:s,cause:o})}},_2="GatewayInvalidRequestError",fT=`vercel.ai.gateway.error.${_2}`,y2=Symbol.for(fT),w2,b2,hT=class extends(b2=At,w2=y2,b2){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[w2]=!0,this.name=_2,this.type="invalid_request_error"}static isInstance(t){return At.hasMarker(t)&&y2 in t}},k2="GatewayRateLimitError",mT=`vercel.ai.gateway.error.${k2}`,S2=Symbol.for(mT),T2,C2,gT=class extends(C2=At,T2=S2,C2){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[T2]=!0,this.name=k2,this.type="rate_limit_exceeded"}static isInstance(t){return At.hasMarker(t)&&S2 in t}},$2="GatewayModelNotFoundError",vT=`vercel.ai.gateway.error.${$2}`,E2=Symbol.for(vT),_T=Qn(()=>kn(C({modelId:v()}))),x2,I2,R2=class extends(I2=At,x2=E2,I2){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[x2]=!0,this.name=$2,this.type="model_not_found",this.modelId=r}static isInstance(t){return At.hasMarker(t)&&E2 in t}},P2="GatewayInternalServerError",yT=`vercel.ai.gateway.error.${P2}`,O2=Symbol.for(yT),A2,M2,N2=class extends(M2=At,A2=O2,M2){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[A2]=!0,this.name=P2,this.type="internal_server_error"}static isInstance(t){return At.hasMarker(t)&&O2 in t}},L2="GatewayResponseError",wT=`vercel.ai.gateway.error.${L2}`,j2=Symbol.for(wT),q2,z2,bT=class extends(z2=At,q2=j2,z2){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:n,cause:s}={}){super({message:t,statusCode:e,cause:s}),this[q2]=!0,this.name=L2,this.type="response_error",this.response=r,this.validationError=n}static isInstance(t){return At.hasMarker(t)&&j2 in t}};async function D2({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:n,authMethod:s}){const o=await Kt({value:t,schema:kT});if(!o.success)return new bT({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:o.error,cause:n});const a=o.value,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return mu.createContextualError({apiKeyProvided:s==="api-key",oidcTokenProvided:s==="oidc",statusCode:e,cause:n});case"invalid_request_error":return new hT({message:l,statusCode:e,cause:n});case"rate_limit_exceeded":return new gT({message:l,statusCode:e,cause:n});case"model_not_found":{const c=await Kt({value:a.error.param,schema:_T});return new R2({message:l,statusCode:e,modelId:c.success?c.value.modelId:void 0,cause:n})}case"internal_server_error":return new N2({message:l,statusCode:e,cause:n});default:return new N2({message:l,statusCode:e,cause:n})}}var kT=Qn(()=>kn(C({error:C({message:v(),type:v().nullish(),param:Le().nullish(),code:ce([v(),L()]).nullish()})})));function Kr(t,e){var r;return At.isInstance(t)?t:Ve.isInstance(t)?D2({response:ST(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):D2({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function ST(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var U2="ai-gateway-auth-method";async function ts(t){const e=await Kt({value:t[U2],schema:TT});return e.success?e.value:void 0}var TT=Qn(()=>kn(ce([j("api-key"),j("oidc")]))),Z2=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await Wm({url:`${this.config.baseURL}/config`,headers:await pr(this.config.headers()),successfulResponseHandler:es(CT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await Kr(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await Wm({url:`${t.origin}/v1/credits`,headers:await pr(this.config.headers()),successfulResponseHandler:es($T),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await Kr(t)}}},CT=Qn(()=>kn(C({models:N(C({id:v(),name:v(),description:v().nullish(),pricing:C({input:v(),output:v(),input_cache_read:v().nullish(),input_cache_write:v().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:n})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:C({specificationVersion:j("v2"),provider:v(),modelId:v()}),modelType:Ce(["language","embedding","image"]).nullish()}))}))),$T=Qn(()=>kn(C({balance:v(),total_used:v()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),ET=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await pr(this.config.headers());try{const{responseHeaders:o,value:a,rawValue:i}=await Xn({url:this.getUrl(),headers:Yn(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await pr(this.config.o11yHeaders)),body:e,successfulResponseHandler:es(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:e},response:{headers:o,body:i},warnings:r}}catch(o){throw await Kr(o,await ts(s))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:n}=t,s=await pr(this.config.headers());try{const{value:o,responseHeaders:a}=await Xn({url:this.getUrl(),headers:Yn(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await pr(this.config.o11yHeaders)),body:e,successfulResponseHandler:e2(ht()),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:o.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:e},response:{headers:a}}}catch(o){throw await Kr(o,await ts(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const s=Uint8Array.from(n.data),o=Buffer.from(s).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${o}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},xT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;const o=await pr(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Xn({url:this.getUrl(),headers:Yn(o,e??{},this.getModelConfigHeaders(),await pr(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...n?{providerOptions:n}:{}},successfulResponseHandler:es(IT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(s=i.usage)!=null?s:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await Kr(a,await ts(o))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},IT=Qn(()=>kn(C({embeddings:N(N(L())),usage:C({tokens:L()}).nullish(),providerMetadata:Se(v(),Se(v(),Le())).optional()}))),RT=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var l;const c=await pr(this.config.headers());try{const{responseHeaders:u,value:p,rawValue:h}=await Xn({url:this.getUrl(),headers:Yn(c,a??{},this.getModelConfigHeaders(),await pr(this.config.o11yHeaders)),body:{prompt:t,n:e,...r&&{size:r},...n&&{aspectRatio:n},...s&&{seed:s},...o&&{providerOptions:o}},successfulResponseHandler:es(OT),failedResponseHandler:bn({errorSchema:ht(),errorToMessage:d=>d}),...i&&{abortSignal:i},fetch:this.config.fetch});return{images:p.images,warnings:(l=p.warnings)!=null?l:[],providerMetadata:p.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:u}}}catch(u){throw Kr(u,await ts(c))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},PT=C({images:N(Le()).optional()}).catchall(Le()),OT=C({images:N(v()),warnings:N(C({type:j("other"),message:v()})).optional(),providerMetadata:Se(v(),PT).optional()});async function AT(){var t;return(t=d2.getContext().headers)==null?void 0:t["x-vercel-id"]}var MT="2.0.18",NT="0.0.1";function LT(t={}){var e,r;let n=null,s=null;const o=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let a=0;const i=(r=i2(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const f=await qT(t);if(f)return Wr({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":NT,[U2]:f.authMethod,...t.headers},`ai-sdk/gateway/${MT}`);throw mu.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const f=ui({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),w=ui({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=ui({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const y=await AT();return{...f&&{"ai-o11y-deployment-id":f},...w&&{"ai-o11y-environment":w},...m&&{"ai-o11y-region":m},...y&&{"ai-o11y-request-id":y}}}},u=f=>new ET(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),p=async()=>{var f,w,m;const y=(m=(w=(f=t._internal)==null?void 0:f.currentDate)==null?void 0:w.call(f).getTime())!=null?m:Date.now();return(!n||y-a>o)&&(a=y,n=new Z2({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(_=>(s=_,_)).catch(async _=>{throw await Kr(_,await ts(await l()))})),s?Promise.resolve(s):n},h=async()=>new Z2({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async f=>{throw await Kr(f,await ts(await l()))}),d=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(f)};return d.getAvailableModels=p,d.getCredits=h,d.imageModel=f=>new RT(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),d.languageModel=u,d.textEmbeddingModel=f=>new xT(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),d}var jT=LT();async function qT(t){const e=ui({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await d2.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var zT=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Sn="1.9.0",F2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function DT(t){var e=new Set([t]),r=new Set,n=t.match(F2);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(l){return l===t};function o(i){return r.add(i),!1}function a(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(F2);if(!c)return o(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||s.major!==u.major?o(l):s.major===0?s.minor===u.minor&&s.patch<=u.patch?a(l):o(l):s.minor<=u.minor?a(l):o(l)}}var UT=DT(Sn),ZT=Sn.split(".")[0],uo=Symbol.for("opentelemetry.js.api."+ZT),po=zT;function fo(t,e,r,n){var s;n===void 0&&(n=!1);var o=po[uo]=(s=po[uo])!==null&&s!==void 0?s:{version:Sn};if(!n&&o[t]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(a.stack||a.message),!1}if(o.version!==Sn){var a=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+t+" does not match previously registered API v"+Sn);return r.error(a.stack||a.message),!1}return o[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Sn+"."),!0}function Tn(t){var e,r,n=(e=po[uo])===null||e===void 0?void 0:e.version;if(!(!n||!UT(n)))return(r=po[uo])===null||r===void 0?void 0:r[t]}function ho(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Sn+".");var r=po[uo];r&&delete r[t]}var FT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},VT=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},HT=(function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return mo("verbose",this._namespace,e)},t})();function mo(t,e,r){var n=Tn("diag");if(n)return r.unshift(e),n[t].apply(n,VT([],FT(r),!1))}var Mt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Mt||(Mt={}));function BT(t,e){t<Mt.NONE?t=Mt.NONE:t>Mt.ALL&&(t=Mt.ALL),e=e||{};function r(n,s){var o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",Mt.ERROR),warn:r("warn",Mt.WARN),info:r("info",Mt.INFO),debug:r("debug",Mt.DEBUG),verbose:r("verbose",Mt.VERBOSE)}}var JT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},GT=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},WT="diag",fr=(function(){function t(){function e(s){return function(){for(var o=[],a=0;a<arguments.length;a++)o[a]=arguments[a];var i=Tn("diag");if(i)return i[s].apply(i,GT([],JT(o),!1))}}var r=this,n=function(s,o){var a,i,l;if(o===void 0&&(o={logLevel:Mt.INFO}),s===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof o=="number"&&(o={logLevel:o});var u=Tn("diag"),p=BT((i=o.logLevel)!==null&&i!==void 0?i:Mt.INFO,s);if(u&&!o.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+h),p.warn("Current logger will overwrite one already registered from "+h)}return fo("diag",p,r,!0)};r.setLogger=n,r.disable=function(){ho(WT,r)},r.createComponentLogger=function(s){return new HT(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t})(),KT=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},YT=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},QT=(function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=KT(e,2),n=r[0],s=r[1];return[n,s]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var o=new t(this._entries);try{for(var a=YT(n),i=a.next();!i.done;i=a.next()){var l=i.value;o._entries.delete(l)}}catch(c){e={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(e)throw e.error}}return o},t.prototype.clear=function(){return new t},t})();fr.instance();function XT(t){return t===void 0&&(t={}),new QT(new Map(Object.entries(t)))}function V2(t){return Symbol.for(t)}var eC=(function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var o=new t(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t})(),tC=new eC,Cn=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(n[o]=s[o])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),rC=(function(){function t(){}return t.prototype.createGauge=function(e,r){return pC},t.prototype.createHistogram=function(e,r){return fC},t.prototype.createCounter=function(e,r){return dC},t.prototype.createUpDownCounter=function(e,r){return hC},t.prototype.createObservableGauge=function(e,r){return gC},t.prototype.createObservableCounter=function(e,r){return mC},t.prototype.createObservableUpDownCounter=function(e,r){return vC},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t})(),hi=(function(){function t(){}return t})(),nC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(hi),sC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,n){},e})(hi),oC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(hi),aC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,n){},e})(hi),gu=(function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t})(),iC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(gu),lC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(gu),cC=(function(t){Cn(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(gu),uC=new rC,dC=new nC,pC=new oC,fC=new aC,hC=new sC,mC=new iC,gC=new lC,vC=new cC,_C={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},yC={set:function(t,e,r){t!=null&&(t[e]=r)}},wC=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},bC=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},kC=(function(){function t(){}return t.prototype.active=function(){return tC},t.prototype.with=function(e,r,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return r.call.apply(r,bC([n],wC(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t})(),SC=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(i){a={error:i}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return o},TC=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))},vu="context",CC=new kC,mi=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return fo(vu,e,fr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,o=[],a=3;a<arguments.length;a++)o[a-3]=arguments[a];return(s=this._getContextManager()).with.apply(s,TC([e,r,n],SC(o),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Tn(vu)||CC},t.prototype.disable=function(){this._getContextManager().disable(),ho(vu,fr.instance())},t})(),_u;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(_u||(_u={}));var H2="0000000000000000",B2="00000000000000000000000000000000",$C={traceId:B2,spanId:H2,traceFlags:_u.NONE},go=(function(){function t(e){e===void 0&&(e=$C),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t})(),yu=V2("OpenTelemetry Context Key SPAN");function wu(t){return t.getValue(yu)||void 0}function EC(){return wu(mi.getInstance().active())}function bu(t,e){return t.setValue(yu,e)}function xC(t){return t.deleteValue(yu)}function IC(t,e){return bu(t,new go(e))}function J2(t){var e;return(e=wu(t))===null||e===void 0?void 0:e.spanContext()}var RC=/^([0-9a-f]{32})$/i,PC=/^[0-9a-f]{16}$/i;function OC(t){return RC.test(t)&&t!==B2}function AC(t){return PC.test(t)&&t!==H2}function G2(t){return OC(t.traceId)&&AC(t.spanId)}function MC(t){return new go(t)}var ku=mi.getInstance(),W2=(function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=ku.active());var s=!!r?.root;if(s)return new go;var o=n&&J2(n);return NC(o)&&G2(o)?new go(o):new go},t.prototype.startActiveSpan=function(e,r,n,s){var o,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(o=r,i=n):(o=r,a=n,i=s);var l=a??ku.active(),c=this.startSpan(e,o,l),u=bu(l,c);return ku.with(u,i,void 0,c)}},t})();function NC(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var LC=new W2,jC=(function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):LC},t})(),qC=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new W2},t})(),zC=new qC,K2=(function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new jC(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:zC},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t})(),gi;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(gi||(gi={})),mi.getInstance(),fr.instance();var DC=(function(){function t(){}return t.prototype.getMeter=function(e,r,n){return uC},t})(),UC=new DC,Su="metrics",ZC=(function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return fo(Su,e,fr.instance())},t.prototype.getMeterProvider=function(){return Tn(Su)||UC},t.prototype.getMeter=function(e,r,n){return this.getMeterProvider().getMeter(e,r,n)},t.prototype.disable=function(){ho(Su,fr.instance())},t})();ZC.getInstance();var FC=(function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t})(),Tu=V2("OpenTelemetry Baggage Key");function Y2(t){return t.getValue(Tu)||void 0}function VC(){return Y2(mi.getInstance().active())}function HC(t,e){return t.setValue(Tu,e)}function BC(t){return t.deleteValue(Tu)}var Cu="propagation",JC=new FC,GC=(function(){function t(){this.createBaggage=XT,this.getBaggage=Y2,this.getActiveBaggage=VC,this.setBaggage=HC,this.deleteBaggage=BC}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return fo(Cu,e,fr.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=yC),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=_C),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){ho(Cu,fr.instance())},t.prototype._getGlobalPropagator=function(){return Tn(Cu)||JC},t})();GC.getInstance();var $u="trace",WC=(function(){function t(){this._proxyTracerProvider=new K2,this.wrapSpanContext=MC,this.isSpanContextValid=G2,this.deleteSpan=xC,this.getSpan=wu,this.getActiveSpan=EC,this.getSpanContext=J2,this.setSpan=bu,this.setSpanContext=IC}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=fo($u,this._proxyTracerProvider,fr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return Tn($u)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){ho($u,fr.instance()),this._proxyTracerProvider=new K2},t})(),KC=WC.getInstance(),YC=Object.defineProperty,QC=(t,e)=>{for(var r in e)YC(t,r,{get:e[r],enumerable:!0})},Q2="AI_NoOutputSpecifiedError",X2=`vercel.ai.error.${Q2}`,XC=Symbol.for(X2),eg,tg=class extends ve{constructor({message:t="No output specified."}={}){super({name:Q2,message:t}),this[eg]=!0}static isInstance(t){return ve.hasMarker(t,X2)}};eg=XC;function e8(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let n=`${e} The tool "${r}" is not supported by this model`;return t.details&&(n+=` - ${t.details}`),n}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var t8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",rg=!1,ng=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}rg||(rg=!0,console.info(t8));for(const r of t)console.warn(e8(r))}},sg="AI_InvalidArgumentError",og=`vercel.ai.error.${sg}`,r8=Symbol.for(og),ag,hr=class extends ve{constructor({parameter:t,value:e,message:r}){super({name:sg,message:`Invalid argument for parameter ${t}: ${r}`}),this[ag]=!0,this.parameter=t,this.value=e}static isInstance(t){return ve.hasMarker(t,og)}};ag=r8;var ig="AI_InvalidToolInputError",lg=`vercel.ai.error.${ig}`,n8=Symbol.for(lg),cg,ug=class extends ve{constructor({toolInput:t,toolName:e,cause:r,message:n=`Invalid input for tool ${e}: ${Kn(r)}`}){super({name:ig,message:n,cause:r}),this[cg]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return ve.hasMarker(t,lg)}};cg=n8;var dg="AI_NoObjectGeneratedError",pg=`vercel.ai.error.${dg}`,s8=Symbol.for(pg),fg,hg=class extends ve{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s,finishReason:o}){super({name:dg,message:t,cause:e}),this[fg]=!0,this.text=r,this.response=n,this.usage=s,this.finishReason=o}static isInstance(t){return ve.hasMarker(t,pg)}};fg=s8;var mg="AI_NoOutputGeneratedError",gg=`vercel.ai.error.${mg}`,o8=Symbol.for(gg),vg,a8=class extends ve{constructor({message:t="No output generated.",cause:e}={}){super({name:mg,message:t,cause:e}),this[vg]=!0}static isInstance(t){return ve.hasMarker(t,gg)}};vg=o8;var _g="AI_NoSuchToolError",yg=`vercel.ai.error.${_g}`,i8=Symbol.for(yg),wg,Eu=class extends ve{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:_g,message:r}),this[wg]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return ve.hasMarker(t,yg)}};wg=i8;var bg="AI_ToolCallRepairError",kg=`vercel.ai.error.${bg}`,l8=Symbol.for(kg),Sg,c8=class extends ve{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Kn(t)}`}){super({name:bg,message:r,cause:t}),this[Sg]=!0,this.originalError=e}static isInstance(t){return ve.hasMarker(t,kg)}};Sg=l8;var u8=class extends ve{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},Tg="AI_InvalidMessageRoleError",Cg=`vercel.ai.error.${Tg}`,d8=Symbol.for(Cg),$g,p8=class extends ve{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Tg,message:e}),this[$g]=!0,this.role=t}static isInstance(t){return ve.hasMarker(t,Cg)}};$g=d8;var Eg="AI_DownloadError",xg=`vercel.ai.error.${Eg}`,f8=Symbol.for(xg),Ig,xu=class extends ve{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Eg,message:s,cause:n}),this[Ig]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return ve.hasMarker(t,xg)}};Ig=f8;var Rg="AI_RetryError",Pg=`vercel.ai.error.${Rg}`,h8=Symbol.for(Pg),Og,Ag=class extends ve{constructor({message:t,reason:e,errors:r}){super({name:Rg,message:t}),this[Og]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return ve.hasMarker(t,Pg)}};Og=h8;function vi(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new u8({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return m8().languageModel(t)}function m8(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:jT}var g8=[{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]}],v8=t=>{const e=typeof t=="string"?du(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function _8(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?v8(t):t}function y8({data:t,signatures:e}){const r=_8(t),n=typeof r=="string"?du(r.substring(0,Math.min(r.length,24))):r;for(const s of e)if(n.length>=s.bytesPrefix.length&&s.bytesPrefix.every((o,a)=>o===null||n[a]===o))return s.mediaType}var Mg="5.0.106",w8=async({url:t})=>{var e;const r=t.toString();try{const n=await fetch(r,{headers:Wr({},`ai-sdk/${Mg}`,lo())});if(!n.ok)throw new xu({url:r,statusCode:n.status,statusText:n.statusText});return{data:new Uint8Array(await n.arrayBuffer()),mediaType:(e=n.headers.get("content-type"))!=null?e:void 0}}catch(n){throw xu.isInstance(n)?n:new xu({url:r,cause:n})}},b8=(t=w8)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function k8(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var Ng=ce([v(),Pa(Uint8Array),Pa(ArrayBuffer),Vf(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Lg(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=k8(t.toString());if(e==null||r==null)throw new ve({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function S8(t){return typeof t=="string"?t:t instanceof ArrayBuffer?fi(new Uint8Array(t)):fi(t)}async function jg({prompt:t,supportedUrls:e,download:r=b8()}){const n=await C8(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(s=>T8({message:s,downloadedAssets:n}))]}function T8({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(n=>$8(n,e)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).map(n=>{const s=n.providerOptions;switch(n.type){case"file":{const{data:o,mediaType:a}=Lg(n.data);return{type:"file",data:o,filename:n.filename,mediaType:a??n.mediaType,providerOptions:s}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:s};case"text":return{type:"text",text:n.text,providerOptions:s};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:s};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:s}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(n=>({type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:n.output,providerOptions:n.providerOptions})),providerOptions:t.providerOptions};default:{const n=r;throw new p8({role:n})}}}async function C8(t,e,r){const n=t.filter(o=>o.role==="user").map(o=>o.content).filter(o=>Array.isArray(o)).flat().filter(o=>o.type==="image"||o.type==="file").map(o=>{var a;const i=(a=o.mediaType)!=null?a:o.type==="image"?"image/*":void 0;let l=o.type==="image"?o.image:o.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(o=>o.data instanceof URL).map(o=>({url:o.data,isUrlSupportedByModel:o.mediaType!=null&&tS({url:o.data.toString(),mediaType:o.mediaType,supportedUrls:r})})),s=await e(n);return Object.fromEntries(s.map((o,a)=>o==null?null:[n[a].url.toString(),{data:o.data,mediaType:o.mediaType}]).filter(o=>o!=null))}function $8(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let n;const s=t.type;switch(s){case"image":n=t.image;break;case"file":n=t.data;break;default:throw new Error(`Unsupported part type: ${s}`)}const{data:o,mediaType:a}=Lg(n);let i=a??t.mediaType,l=o;if(l instanceof URL){const c=e[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(s){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=y8({data:l,signatures:g8}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function Iu({maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,seed:a,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new hr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new hr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new hr({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new hr({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new hr({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new hr({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(o!=null&&typeof o!="number")throw new hr({parameter:"frequencyPenalty",value:o,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new hr({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:o,stopSequences:i,seed:a}}function E8(t){return t!=null&&Object.keys(t).length>0}function qg({tools:t,toolChoice:e,activeTools:r}){return E8(t)?{tools:(r!=null?Object.entries(t).filter(([s])=>r.includes(s)):Object.entries(t)).map(([s,o])=>{const a=o.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:s,description:o.description,inputSchema:pi(o.inputSchema).jsonSchema,providerOptions:o.providerOptions};case"provider-defined":return{type:"provider-defined",name:s,id:o.id,args:o.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var vo=Ff(()=>ce([fl(),v(),L(),ge(),Se(v(),vo),N(vo)])),mr=Se(v(),Se(v(),vo)),zg=C({type:j("text"),text:v(),providerOptions:mr.optional()}),x8=C({type:j("image"),image:ce([Ng,Pa(URL)]),mediaType:v().optional(),providerOptions:mr.optional()}),Dg=C({type:j("file"),data:ce([Ng,Pa(URL)]),filename:v().optional(),mediaType:v(),providerOptions:mr.optional()}),I8=C({type:j("reasoning"),text:v(),providerOptions:mr.optional()}),R8=C({type:j("tool-call"),toolCallId:v(),toolName:v(),input:Le(),providerOptions:mr.optional(),providerExecuted:ge().optional()}),P8=et("type",[C({type:j("text"),value:v()}),C({type:j("json"),value:vo}),C({type:j("error-text"),value:v()}),C({type:j("error-json"),value:vo}),C({type:j("content"),value:N(ce([C({type:j("text"),text:v()}),C({type:j("media"),data:v(),mediaType:v()})]))})]),Ug=C({type:j("tool-result"),toolCallId:v(),toolName:v(),output:P8,providerOptions:mr.optional()}),O8=C({role:j("system"),content:v(),providerOptions:mr.optional()}),A8=C({role:j("user"),content:ce([v(),N(ce([zg,x8,Dg]))]),providerOptions:mr.optional()}),M8=C({role:j("assistant"),content:ce([v(),N(ce([zg,Dg,I8,R8,Ug]))]),providerOptions:mr.optional()}),N8=C({role:j("tool"),content:N(Ug),providerOptions:mr.optional()}),L8=ce([O8,A8,M8,N8]);async function Zg(t){if(t.prompt==null&&t.messages==null)throw new _n({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new _n({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new _n({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new _n({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new _n({prompt:t,message:"messages must not be empty"});const r=await Kt({value:e,schema:N(L8)});if(!r.success)throw new _n({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function Fg(t){return mu.isInstance(t)||R2.isInstance(t)?new ve({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function rs({operationId:t,telemetry:e}){return{"operation.name":`${t}${e?.functionId!=null?` ${e.functionId}`:""}`,"resource.name":e?.functionId,"ai.operationId":t,"ai.telemetry.functionId":e?.functionId}}function Vg({model:t,settings:e,telemetry:r,headers:n}){var s;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((o,[a,i])=>(o[`ai.settings.${a}`]=i,o),{}),...Object.entries((s=r?.metadata)!=null?s:{}).reduce((o,[a,i])=>(o[`ai.telemetry.metadata.${a}`]=i,o),{}),...Object.entries(n??{}).reduce((o,[a,i])=>(i!==void 0&&(o[`ai.request.headers.${a}`]=i),o),{})}}var j8={startSpan(){return _i},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(_i);if(typeof r=="function")return r(_i);if(typeof n=="function")return n(_i)}},_i={spanContext(){return q8},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}},q8={traceId:"",spanId:"",traceFlags:0};function Hg({isEnabled:t=!1,tracer:e}={}){return t?e||KC.getTracer("ai"):j8}function ns({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async o=>{try{const a=await n(o);return s&&o.end(),a}catch(a){try{Ru(o,a)}finally{o.end()}throw a}})}function Ru(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:gi.ERROR,message:e.message})):t.setStatus({code:gi.ERROR})}function Dt({telemetry:t,attributes:e}){return t?.isEnabled!==!0?{}:Object.entries(e).reduce((r,[n,s])=>{if(s==null)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if(t?.recordInputs===!1)return r;const o=s.input();return o==null?r:{...r,[n]:o}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if(t?.recordOutputs===!1)return r;const o=s.output();return o==null?r:{...r,[n]:o}}return{...r,[n]:s}},{})}function Bg(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?S8(r.data):r.data}:r)})))}function Jg(t,e){return{inputTokens:_o(t.inputTokens,e.inputTokens),outputTokens:_o(t.outputTokens,e.outputTokens),totalTokens:_o(t.totalTokens,e.totalTokens),reasoningTokens:_o(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:_o(t.cachedInputTokens,e.cachedInputTokens)}}function _o(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function Pu(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function z8({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let n;const s=r["retry-after-ms"];if(s){const a=parseFloat(s);Number.isNaN(a)||(n=a)}const o=r["retry-after"];if(o&&n===void 0){const a=parseFloat(o);Number.isNaN(a)?n=Date.parse(o)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<e)?n:e}var D8=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:n}={})=>async s=>Gg(s,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:n});async function Gg(t,{maxRetries:e,delayInMs:r,backoffFactor:n,abortSignal:s},o=[]){try{return await t()}catch(a){if(yn(a)||e===0)throw a;const i=su(a),l=[...o,a],c=l.length;if(c>e)throw new Ag({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Ve.isInstance(a)&&a.isRetryable===!0&&c<=e)return await Y5(z8({error:a,exponentialBackoffDelay:r}),{abortSignal:s}),Gg(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n,abortSignal:s},l);throw c===1?a:new Ag({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function Wg({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new hr({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new hr({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:D8({maxRetries:r,abortSignal:e})}}function Kg(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var Yg=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=fi(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=du(this.base64Data)),this.uint8ArrayData}},U8=class extends Yg{constructor(t){super(t),this.type="file"}};async function Qg({toolCall:t,tools:e,repairToolCall:r,system:n,messages:s}){try{if(e==null)throw new Eu({toolName:t.toolName});try{return await Xg({toolCall:t,tools:e})}catch(o){if(r==null||!(Eu.isInstance(o)||ug.isInstance(o)))throw o;let a=null;try{a=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return pi(l).jsonSchema},system:n,messages:s,error:o})}catch(i){throw new c8({cause:i,originalError:o})}if(a==null)throw o;return await Xg({toolCall:a,tools:e})}}catch(o){const a=await wn({text:t.input}),i=a.success?a.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:o,providerMetadata:t.providerMetadata}}}async function Xg({toolCall:t,tools:e}){const r=t.toolName,n=e[r];if(n==null)throw new Eu({toolName:t.toolName,availableTools:Object.keys(e)});const s=pi(n.inputSchema),o=t.input.trim()===""?await Kt({value:{},schema:s}):await wn({text:t.input,schema:s});if(o.success===!1)throw new ug({toolName:r,toolInput:t.input,cause:o.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:o.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var ev=class{constructor({content:t,finishReason:e,usage:r,warnings:n,request:s,response:o,providerMetadata:a}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=n,this.request=s,this.response=o,this.providerMetadata=a}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function Ou(t){return({steps:e})=>e.length===t}async function tv({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function Au({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:Kn(t)}:r==="json"?{type:"error-json",value:rv(t)}:e?.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:rv(t)}}function rv(t){return t===void 0?null:t}function Mu({content:t,tools:e}){const r=[],n=t.filter(o=>o.type!=="source").filter(o=>(o.type!=="tool-result"||o.providerExecuted)&&(o.type!=="tool-error"||o.providerExecuted)).filter(o=>o.type!=="text"||o.text.length>0).map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,providerOptions:o.providerMetadata};case"reasoning":return{type:"reasoning",text:o.text,providerOptions:o.providerMetadata};case"file":return{type:"file",data:o.file.base64,mediaType:o.file.mediaType,providerOptions:o.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:o.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Au({tool:e?.[o.toolName],output:o.output,errorMode:"none"}),providerExecuted:!0,providerOptions:o.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Au({tool:e?.[o.toolName],output:o.error,errorMode:"json"}),providerOptions:o.providerMetadata}}});n.length>0&&r.push({role:"assistant",content:n});const s=t.filter(o=>o.type==="tool-result"||o.type==="tool-error").filter(o=>!o.providerExecuted).map(o=>({type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Au({tool:e?.[o.toolName],output:o.type==="tool-result"?o.output:o.error,errorMode:o.type==="tool-error"?"text":"none"}),...o.providerMetadata!=null?{providerOptions:o.providerMetadata}:{}}));return s.length>0&&r.push({role:"tool",content:s}),r}var Z8=ao({prefix:"aitxt",size:24});async function nv({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Ou(1),experimental_output:u,experimental_telemetry:p,providerOptions:h,experimental_activeTools:d,activeTools:f=d,experimental_prepareStep:w,prepareStep:m=w,experimental_repairToolCall:y,experimental_download:_,experimental_context:g,_internal:{generateId:b=Z8,currentDate:k=()=>new Date}={},onStepFinish:S,...T}){const x=vi(t),I=Pu(c),{maxRetries:A,retry:P}=Wg({maxRetries:a,abortSignal:i}),D=Iu(T),U=Wr(l??{},`ai/${Mg}`),V=Vg({model:x,telemetry:p,headers:U,settings:{...D,maxRetries:A}}),se=await Zg({system:n,prompt:s,messages:o}),fe=Hg(p);try{return await ns({name:"ai.generateText",attributes:Dt({telemetry:p,attributes:{...rs({operationId:"ai.generateText",telemetry:p}),...V,"ai.model.provider":x.provider,"ai.model.id":x.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:s,messages:o})}}}),tracer:fe,fn:async de=>{var re,_e,H,O,F,q,E;const R=Iu(T);let $,B=[],W=[];const ye=[],pe=[];do{const G=[...se.messages,...ye],K=await m?.({model:x,steps:pe,stepNumber:pe.length,messages:G}),X=vi((re=K?.model)!=null?re:x),ue=await jg({prompt:{system:(_e=K?.system)!=null?_e:se.system,messages:(H=K?.messages)!=null?H:G},supportedUrls:await X.supportedUrls,download:_}),{toolChoice:he,tools:He}=qg({tools:e,toolChoice:(O=K?.toolChoice)!=null?O:r,activeTools:(F=K?.activeTools)!=null?F:f});$=await P(()=>{var xe;return ns({name:"ai.generateText.doGenerate",attributes:Dt({telemetry:p,attributes:{...rs({operationId:"ai.generateText.doGenerate",telemetry:p}),...V,"ai.model.provider":X.provider,"ai.model.id":X.modelId,"ai.prompt.messages":{input:()=>Bg(ue)},"ai.prompt.tools":{input:()=>He?.map(Et=>JSON.stringify(Et))},"ai.prompt.toolChoice":{input:()=>he!=null?JSON.stringify(he):void 0},"gen_ai.system":X.provider,"gen_ai.request.model":X.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxOutputTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.stop_sequences":T.stopSequences,"gen_ai.request.temperature":(xe=T.temperature)!=null?xe:void 0,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:fe,fn:async Et=>{var Pr,xt,it,Ut,Xr,en,cs,Pi;const nt=await X.doGenerate({...R,tools:He,toolChoice:he,responseFormat:u?.responseFormat,prompt:ue,providerOptions:h,abortSignal:i,headers:U}),Or={id:(xt=(Pr=nt.response)==null?void 0:Pr.id)!=null?xt:b(),timestamp:(Ut=(it=nt.response)==null?void 0:it.timestamp)!=null?Ut:k(),modelId:(en=(Xr=nt.response)==null?void 0:Xr.modelId)!=null?en:X.modelId,headers:(cs=nt.response)==null?void 0:cs.headers,body:(Pi=nt.response)==null?void 0:Pi.body};return Et.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":nt.finishReason,"ai.response.text":{output:()=>Kg(nt.content)},"ai.response.toolCalls":{output:()=>{const Ar=sv(nt.content);return Ar==null?void 0:JSON.stringify(Ar)}},"ai.response.id":Or.id,"ai.response.model":Or.modelId,"ai.response.timestamp":Or.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(nt.providerMetadata),"ai.usage.promptTokens":nt.usage.inputTokens,"ai.usage.completionTokens":nt.usage.outputTokens,"gen_ai.response.finish_reasons":[nt.finishReason],"gen_ai.response.id":Or.id,"gen_ai.response.model":Or.modelId,"gen_ai.usage.input_tokens":nt.usage.inputTokens,"gen_ai.usage.output_tokens":nt.usage.outputTokens}})),{...nt,response:Or}}})});const Je=await Promise.all($.content.filter(xe=>xe.type==="tool-call").map(xe=>Qg({toolCall:xe,tools:e,repairToolCall:y,system:n,messages:G})));for(const xe of Je){if(xe.invalid)continue;const Et=e[xe.toolName];Et?.onInputAvailable!=null&&await Et.onInputAvailable({input:xe.input,toolCallId:xe.toolCallId,messages:G,abortSignal:i,experimental_context:g})}const ee=Je.filter(xe=>xe.invalid&&xe.dynamic);W=[];for(const xe of ee)W.push({type:"tool-error",toolCallId:xe.toolCallId,toolName:xe.toolName,input:xe.input,error:su(xe.error),dynamic:!0});B=Je.filter(xe=>!xe.providerExecuted),e!=null&&W.push(...await F8({toolCalls:B.filter(xe=>!xe.invalid),tools:e,tracer:fe,telemetry:p,messages:G,abortSignal:i,experimental_context:g}));const be=H8({content:$.content,toolCalls:Je,toolOutputs:W});ye.push(...Mu({content:be,tools:e}));const yt=new ev({content:be,finishReason:$.finishReason,usage:$.usage,warnings:$.warnings,providerMetadata:$.providerMetadata,request:(q=$.request)!=null?q:{},response:{...$.response,messages:structuredClone(ye)}});ng((E=$.warnings)!=null?E:[]),pe.push(yt),await S?.(yt)}while(B.length>0&&W.length===B.length&&!await tv({stopConditions:I,steps:pe}));de.setAttributes(Dt({telemetry:p,attributes:{"ai.response.finishReason":$.finishReason,"ai.response.text":{output:()=>Kg($.content)},"ai.response.toolCalls":{output:()=>{const G=sv($.content);return G==null?void 0:JSON.stringify(G)}},"ai.response.providerMetadata":JSON.stringify($.providerMetadata),"ai.usage.promptTokens":$.usage.inputTokens,"ai.usage.completionTokens":$.usage.outputTokens}}));const M=pe[pe.length-1];let Z;return M.finishReason==="stop"&&(Z=await u?.parseOutput({text:M.text},{response:M.response,usage:M.usage,finishReason:M.finishReason})),new V8({steps:pe,resolvedOutput:Z})}})}catch(de){throw Fg(de)}}async function F8({toolCalls:t,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:o,experimental_context:a}){return(await Promise.all(t.map(async({toolCallId:l,toolName:c,input:u})=>{const p=e[c];if(p?.execute!=null)return ns({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...rs({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async h=>{try{const d=l2({execute:p.execute.bind(p),input:u,options:{toolCallId:l,messages:s,abortSignal:o,experimental_context:a}});let f;for await(const w of d)w.type==="final"&&(f=w.output);try{h.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:f,dynamic:p.type==="dynamic"}}catch(d){return Ru(h,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:p.type==="dynamic"}}}})}))).filter(l=>l!=null)}var V8=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>Jg(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new tg;return this.resolvedOutput}};function sv(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function H8({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(n=>{switch(n.type){case"text":case"reasoning":case"source":return n;case"file":return{type:"file",file:new Yg(n)};case"tool-call":return e.find(s=>s.toolCallId===n.toolCallId);case"tool-result":{const s=e.find(o=>o.toolCallId===n.toolCallId);if(s==null)throw new Error(`Tool call ${n.toolCallId} not found.`);return n.isError?{type:"tool-error",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,error:n.result,providerExecuted:!0,dynamic:s.dynamic}:{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,input:s.input,output:n.result,providerExecuted:!0,dynamic:s.dynamic}}}}),...r]}function yi(t,e){const r=new Headers(t??{});for(const[n,s]of Object.entries(e))r.has(n)||r.set(n,s);return r}function B8({status:t,statusText:e,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:yi(r,{"content-type":"text/plain; charset=utf-8"})})}function ov({response:t,status:e,statusText:r,headers:n,stream:s}){t.writeHead(e??200,r,n);const o=s.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await o.read();if(i)break;t.write(l)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function J8({response:t,status:e,statusText:r,headers:n,textStream:s}){ov({response:t,status:e,statusText:r,headers:Object.fromEntries(yi(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:s.pipeThrough(new TextEncoderStream)})}var av=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
570
570
 
571
571
  `)},flush(t){t.enqueue(`data: [DONE]
572
572
 
573
- `)}})}},iv={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function G8({status:t,statusText:e,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new av);if(s){const[a,i]=o.tee();o=a,s({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:yi(r,iv)})}function W8({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return r?.role==="assistant"?r.id:typeof e=="function"?e():e}function K8(t){return t.type.startsWith("data-")}function lv(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];if(s===void 0)continue;const o=n in t?t[n]:void 0,a=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&i?r[n]=lv(o,s):r[n]=s}return r}function Y8(t){const e=["ROOT"];let r=-1,n=null;function s(l,c,u){switch(l){case'"':{r=c,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,e.pop(),e.push(u),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(u),e.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,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function o(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function a(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":s(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.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",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const p=t.substring(n,l+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(n,t.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function cv(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await wn({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await wn({text:Y8(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Lu(t){return t.type.startsWith("tool-")}function uv(t){return t.type.split("-").slice(1).join("-")}function Q8({lastMessage:t,messageId:e}){return{message:t?.role==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function X8({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:a}){return t.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var p,h,d,f;function w(b){const S=c.message.parts.filter(Lu).find(T=>T.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function m(b){const S=c.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function y(b){var k;const S=c.message.parts.find(I=>Lu(I)&&I.toolCallId===b.toolCallId),T=b,x=S;S!=null?(S.state=b.state,x.input=T.input,x.output=T.output,x.errorText=T.errorText,x.rawInput=T.rawInput,x.preliminary=T.preliminary,x.providerExecuted=(k=T.providerExecuted)!=null?k:S.providerExecuted,T.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=T.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function _(b){var k,S;const T=c.message.parts.find(A=>A.type==="dynamic-tool"&&A.toolCallId===b.toolCallId),x=b,I=T;T!=null?(T.state=b.state,I.toolName=b.toolName,I.input=x.input,I.output=x.output,I.errorText=x.errorText,I.rawInput=(k=x.rawInput)!=null?k:I.rawInput,I.preliminary=x.preliminary,I.providerExecuted=(S=x.providerExecuted)!=null?S:T.providerExecuted,x.providerMetadata!=null&&T.state==="input-available"&&(T.callProviderMetadata=x.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function g(b){if(b!=null){const k=c.message.metadata!=null?lv(c.message.metadata,b):b;e!=null&&await iu({value:k,schema:e}),c.message.metadata=k}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(p=i.providerMetadata)!=null?p:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[i.id];b.state="done",b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[i.id];b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,b.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(Lu);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:k}=await cv(b.text);b.dynamic?_({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}):y({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}),u();break}case"tool-input-available":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:uv(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:uv(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await g(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await g(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await g(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{s?.(new Error(i.errorText));break}default:if(K8(i)){r?.[i.type]!=null&&await iu({value:i.data,schema:r[i.type]});const b=i;if(b.transient){a?.(b);break}const k=b.id!=null?c.message.parts.find(S=>b.type===S.type&&b.id===S.id):void 0;k!=null?k.data=b.data:c.message.parts.push(b),a?.(b),u()}}l.enqueue(i)})}}))}function e7({messageId:t,originalMessages:e=[],onFinish:r,onError:n,stream:s}){let o=e?.[e.length-1];o?.role!=="assistant"?o=void 0:t=o.id;let a=!1;const i=s.pipeThrough(new TransformStream({transform(h,d){if(h.type==="start"){const f=h;f.messageId==null&&t!=null&&(f.messageId=t)}h.type==="abort"&&(a=!0),d.enqueue(h)}}));if(r==null)return i;const l=Q8({lastMessage:o?structuredClone(o):void 0,messageId:t??""}),c=async h=>{await h({state:l,write:()=>{}})};let u=!1;const p=async()=>{if(u||!r)return;u=!0;const h=l.message.id===o?.id;await r({isAborted:a,isContinuation:h,responseMessage:l.message,messages:[...h?e.slice(0,-1):e,l.message],finishReason:l.finishReason})};return X8({stream:i,runUpdateMessageJob:c,onError:n}).pipeThrough(new TransformStream({transform(h,d){d.enqueue(h)},async cancel(){await p()},async flush(){await p()}}))}function t7({response:t,status:e,statusText:r,headers:n,stream:s,consumeSseStream:o}){let a=s.pipeThrough(new av);if(o){const[i,l]=a.tee();a=i,o({stream:l})}ov({response:t,status:e,statusText:r,headers:Object.fromEntries(yi(n,iv).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function wi(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var a;n=!0;try{o&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:a}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},e}async function r7({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){e?.(n)}finally{r.releaseLock()}}function dv(){let t,e;return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}function n7(){let t=[],e=null,r=!1,n=dv();const s=()=>{r=!0,n.resolve(),t.forEach(a=>a.cancel()),t=[],e?.close()},o=async()=>{if(r&&t.length===0){e?.close();return}if(t.length===0)return n=dv(),await n.promise,o();try{const{value:a,done:i}=await t[0].read();i?(t.shift(),t.length>0?await o():r&&e?.close()):e?.enqueue(a)}catch(a){e?.error(a),t.shift(),s()}};return{stream:new ReadableStream({start(a){e=a},pull:o,async cancel(){for(const a of t)await a.cancel();t=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),t.length===0&&e?.close()},terminate:s}}function s7(){var t,e;return(e=(t=globalThis?.performance)==null?void 0:t.now())!=null?e:Date.now()}function o7({tools:t,generatorStream:e,tracer:r,telemetry:n,system:s,messages:o,abortSignal:a,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(y){c=y}}),p=new Set,h=new Map;let d=!1,f;function w(){d&&p.size===0&&(f!=null&&c.enqueue(f),c.close())}const m=new TransformStream({async transform(y,_){const g=y.type;switch(g){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{_.enqueue(y);break}case"file":{_.enqueue({type:"file",file:new U8({data:y.data,mediaType:y.mediaType})});break}case"finish":{f={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const b=await Qg({toolCall:y,tools:t,repairToolCall:i,system:s,messages:o});if(_.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:ou(b.error),dynamic:!0});break}const k=t[b.toolName];if(h.set(b.toolCallId,b.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:l}),k.execute!=null&&b.providerExecuted!==!0){const S=io();p.add(S),ns({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...rs({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async T=>{let x;try{const I=l2({execute:k.execute.bind(k),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:l}});for await(const A of I)c.enqueue({...b,type:"tool-result",output:A.output,...A.type==="preliminary"&&{preliminary:!0}}),A.type==="final"&&(x=A.output)}catch(I){Pu(T,I),c.enqueue({...b,type:"tool-error",error:I}),p.delete(S),w();return}p.delete(S),w();try{T.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(x)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=y.toolName;y.isError?c.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):_.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const b=g;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,w()}});return new ReadableStream({async start(y){return Promise.all([e.pipeThrough(m).pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){}})),u.pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){y.close()}}))])}})}var a7=ao({prefix:"aitxt",size:24});function ju({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Au(1),experimental_output:u,experimental_telemetry:p,prepareStep:h,providerOptions:d,experimental_activeTools:f,activeTools:w=f,experimental_repairToolCall:m,experimental_transform:y,experimental_download:_,includeRawChunks:g=!1,onChunk:b,onError:k=({error:V})=>{console.error(V)},onFinish:S,onAbort:T,onStepFinish:x,experimental_context:I,_internal:{now:A=s7,generateId:P=a7,currentDate:D=()=>new Date}={},...U}){return new l7({model:vi(t),telemetry:p,headers:l,settings:U,maxRetries:a,abortSignal:i,system:n,prompt:s,messages:o,tools:e,toolChoice:r,transforms:Ou(y),activeTools:w,repairToolCall:m,stopConditions:Ou(c),output:u,providerOptions:d,prepareStep:h,includeRawChunks:g,onChunk:b,onError:k,onFinish:S,onAbort:T,onStepFinish:x,now:A,currentDate:D,generateId:P,experimental_context:I,download:_})}function i7(t){if(!t)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let e,r="",n="",s="";function o({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:e,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&n.length>0&&o({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(e==null)e=a.id;else if(a.id!==e){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text;const l=await t.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==s&&(o({controller:i,partialOutput:l.partial}),s=c)}}})}var l7=class{constructor({model:t,telemetry:e,headers:r,settings:n,maxRetries:s,abortSignal:o,system:a,prompt:i,messages:l,tools:c,toolChoice:u,transforms:p,activeTools:h,repairToolCall:d,stopConditions:f,output:w,providerOptions:m,prepareStep:y,includeRawChunks:_,now:g,currentDate:b,generateId:k,onChunk:S,onError:T,onFinish:x,onAbort:I,onStepFinish:A,experimental_context:P,download:D}){this._totalUsage=new ci,this._finishReason=new ci,this._steps=new ci,this.output=w,this.includeRawChunks=_,this.tools=c;let U,V=[];const se=[];let fe,de,re={},_e=[];const H=[];let O,F={},q={};const E=new TransformStream({async transform(K,X){var ue,he,He,Je;X.enqueue(K);const{part:ee}=K;if((ee.type==="text-delta"||ee.type==="reasoning-delta"||ee.type==="source"||ee.type==="tool-call"||ee.type==="tool-result"||ee.type==="tool-input-start"||ee.type==="tool-input-delta"||ee.type==="raw")&&await S?.({chunk:ee}),ee.type==="error"&&await T({error:Fg(ee.error)}),ee.type==="text-start"&&(F[ee.id]={type:"text",text:"",providerMetadata:ee.providerMetadata},V.push(F[ee.id])),ee.type==="text-delta"){const be=F[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}be.text+=ee.text,be.providerMetadata=(ue=ee.providerMetadata)!=null?ue:be.providerMetadata}if(ee.type==="text-end"){const be=F[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}be.providerMetadata=(he=ee.providerMetadata)!=null?he:be.providerMetadata,delete F[ee.id]}if(ee.type==="reasoning-start"&&(q[ee.id]={type:"reasoning",text:"",providerMetadata:ee.providerMetadata},V.push(q[ee.id])),ee.type==="reasoning-delta"){const be=q[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}be.text+=ee.text,be.providerMetadata=(He=ee.providerMetadata)!=null?He:be.providerMetadata}if(ee.type==="reasoning-end"){const be=q[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}be.providerMetadata=(Je=ee.providerMetadata)!=null?Je:be.providerMetadata,delete q[ee.id]}if(ee.type==="file"&&V.push({type:"file",file:ee.file}),ee.type==="source"&&V.push(ee),ee.type==="tool-call"&&V.push(ee),ee.type==="tool-result"&&!ee.preliminary&&V.push(ee),ee.type==="tool-error"&&V.push(ee),ee.type==="start-step"&&(re=ee.request,_e=ee.warnings),ee.type==="finish-step"){const be=Nu({content:V,tools:c}),yt=new ev({content:V,finishReason:ee.finishReason,usage:ee.usage,warnings:_e,request:re,response:{...ee.response,messages:[...se,...be]},providerMetadata:ee.providerMetadata});await A?.(yt),ng(_e),H.push(yt),V=[],q={},F={},se.push(...be),U.resolve()}ee.type==="finish"&&(de=ee.totalUsage,fe=ee.finishReason)},async flush(K){try{if(H.length===0){const He=new a8({message:"No output generated. Check the stream for errors."});G._finishReason.reject(He),G._totalUsage.reject(He),G._steps.reject(He);return}const X=fe??"unknown",ue=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};G._finishReason.resolve(X),G._totalUsage.resolve(ue),G._steps.resolve(H);const he=H[H.length-1];await x?.({finishReason:X,totalUsage:ue,usage:he.usage,content:he.content,text:he.text,reasoningText:he.reasoningText,reasoning:he.reasoning,files:he.files,sources:he.sources,toolCalls:he.toolCalls,staticToolCalls:he.staticToolCalls,dynamicToolCalls:he.dynamicToolCalls,toolResults:he.toolResults,staticToolResults:he.staticToolResults,dynamicToolResults:he.dynamicToolResults,request:he.request,response:he.response,warnings:he.warnings,providerMetadata:he.providerMetadata,steps:H}),O.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":X,"ai.response.text":{output:()=>he.text},"ai.response.toolCalls":{output:()=>{var He;return(He=he.toolCalls)!=null&&He.length?JSON.stringify(he.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(he.providerMetadata),"ai.usage.inputTokens":ue.inputTokens,"ai.usage.outputTokens":ue.outputTokens,"ai.usage.totalTokens":ue.totalTokens,"ai.usage.reasoningTokens":ue.reasoningTokens,"ai.usage.cachedInputTokens":ue.cachedInputTokens}}))}catch(X){K.error(X)}finally{O.end()}}}),R=n7();this.addStream=R.addStream,this.closeStream=R.close;const $=R.stream.getReader();let B=new ReadableStream({async start(K){K.enqueue({type:"start"})},async pull(K){function X(){I?.({steps:H}),K.enqueue({type:"abort"}),K.close()}try{const{done:ue,value:he}=await $.read();if(ue){K.close();return}if(o?.aborted){X();return}K.enqueue(he)}catch(ue){yn(ue)&&o?.aborted?X():K.error(ue)}},cancel(K){return R.stream.cancel(K)}});for(const K of p)B=B.pipeThrough(K({tools:c,stopStream(){R.terminate()}}));this.baseStream=B.pipeThrough(i7(w)).pipeThrough(E);const{maxRetries:W,retry:ye}=Wg({maxRetries:s,abortSignal:o}),pe=Hg(e),M=Ru(n),Z=Vg({model:t,telemetry:e,headers:r,settings:{...M,maxRetries:W}}),G=this;ns({name:"ai.streamText",attributes:Dt({telemetry:e,attributes:{...rs({operationId:"ai.streamText",telemetry:e}),...Z,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:pe,endWhenDone:!1,fn:async K=>{O=K;async function X({currentStep:ue,responseMessages:he,usage:He}){var Je,ee,be,yt,xe;const Et=G.includeRawChunks;U=new ci;const Pr=await Zg({system:a,prompt:i,messages:l}),xt=[...Pr.messages,...he],it=await y?.({model:t,steps:H,stepNumber:H.length,messages:xt}),Ut=vi((Je=it?.model)!=null?Je:t),Xr=await jg({prompt:{system:(ee=it?.system)!=null?ee:Pr.system,messages:(be=it?.messages)!=null?be:xt},supportedUrls:await Ut.supportedUrls,download:D}),{toolChoice:en,tools:cs}=qg({tools:c,toolChoice:(yt=it?.toolChoice)!=null?yt:u,activeTools:(xe=it?.activeTools)!=null?xe:h}),{result:{stream:Pi,response:nt,request:Or},doStreamSpan:Ar,startTimestampMs:m_}=await ye(()=>ns({name:"ai.streamText.doStream",attributes:Dt({telemetry:e,attributes:{...rs({operationId:"ai.streamText.doStream",telemetry:e}),...Z,"ai.model.provider":Ut.provider,"ai.model.id":Ut.modelId,"ai.prompt.messages":{input:()=>Bg(Xr)},"ai.prompt.tools":{input:()=>cs?.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>en!=null?JSON.stringify(en):void 0},"gen_ai.system":Ut.provider,"gen_ai.request.model":Ut.modelId,"gen_ai.request.frequency_penalty":M.frequencyPenalty,"gen_ai.request.max_tokens":M.maxOutputTokens,"gen_ai.request.presence_penalty":M.presencePenalty,"gen_ai.request.stop_sequences":M.stopSequences,"gen_ai.request.temperature":M.temperature,"gen_ai.request.top_k":M.topK,"gen_ai.request.top_p":M.topP}}),tracer:pe,endWhenDone:!1,fn:async we=>({startTimestampMs:g(),doStreamSpan:we,result:await Ut.doStream({...M,tools:cs,toolChoice:en,responseFormat:w?.responseFormat,prompt:Xr,providerOptions:m,abortSignal:o,headers:r,includeRawChunks:Et})})})),sI=o7({tools:c,generatorStream:Pi,tracer:pe,telemetry:e,system:a,messages:xt,repairToolCall:d,abortSignal:o,experimental_context:P}),oI=Or??{},Oi=[],Qu=[];let Xu;const ed={};let us="unknown",rr={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},td,g_=!0,_r={id:k(),timestamp:b(),modelId:t.modelId},v_="";G.addStream(sI.pipeThrough(new TransformStream({async transform(we,lt){var So,To,Ai,Mr;if(we.type==="stream-start"){Xu=we.warnings;return}if(g_){const wt=g()-m_;g_=!1,Ar.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":wt}),Ar.setAttributes({"ai.response.msToFirstChunk":wt}),lt.enqueue({type:"start-step",request:oI,warnings:Xu??[]})}const __=we.type;switch(__){case"text-start":case"text-end":{lt.enqueue(we);break}case"text-delta":{we.delta.length>0&&(lt.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),v_+=we.delta);break}case"reasoning-start":case"reasoning-end":{lt.enqueue(we);break}case"reasoning-delta":{lt.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{lt.enqueue(we),Oi.push(we);break}case"tool-result":{lt.enqueue(we),we.preliminary||Qu.push(we);break}case"tool-error":{lt.enqueue(we),Qu.push(we);break}case"response-metadata":{_r={id:(So=we.id)!=null?So:_r.id,timestamp:(To=we.timestamp)!=null?To:_r.timestamp,modelId:(Ai=we.modelId)!=null?Ai:_r.modelId};break}case"finish":{rr=we.usage,us=we.finishReason,td=we.providerMetadata;const wt=g()-m_;Ar.addEvent("ai.stream.finish"),Ar.setAttributes({"ai.response.msToFinish":wt,"ai.response.avgOutputTokensPerSecond":1e3*((Mr=rr.outputTokens)!=null?Mr:0)/wt});break}case"file":{lt.enqueue(we);break}case"source":{lt.enqueue(we);break}case"tool-input-start":{ed[we.id]=we.toolName;const wt=c?.[we.toolName];wt?.onInputStart!=null&&await wt.onInputStart({toolCallId:we.id,messages:xt,abortSignal:o,experimental_context:P}),lt.enqueue({...we,dynamic:wt?.type==="dynamic"});break}case"tool-input-end":{delete ed[we.id],lt.enqueue(we);break}case"tool-input-delta":{const wt=ed[we.id],rd=c?.[wt];rd?.onInputDelta!=null&&await rd.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:xt,abortSignal:o,experimental_context:P}),lt.enqueue(we);break}case"error":{lt.enqueue(we),us="error";break}case"raw":{Et&&lt.enqueue(we);break}default:{const wt=__;throw new Error(`Unknown chunk type: ${wt}`)}}},async flush(we){const lt=Oi.length>0?JSON.stringify(Oi):void 0;try{Ar.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":us,"ai.response.text":{output:()=>v_},"ai.response.toolCalls":{output:()=>lt},"ai.response.id":_r.id,"ai.response.model":_r.modelId,"ai.response.timestamp":_r.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(td),"ai.usage.inputTokens":rr.inputTokens,"ai.usage.outputTokens":rr.outputTokens,"ai.usage.totalTokens":rr.totalTokens,"ai.usage.reasoningTokens":rr.reasoningTokens,"ai.usage.cachedInputTokens":rr.cachedInputTokens,"gen_ai.response.finish_reasons":[us],"gen_ai.response.id":_r.id,"gen_ai.response.model":_r.modelId,"gen_ai.usage.input_tokens":rr.inputTokens,"gen_ai.usage.output_tokens":rr.outputTokens}}))}catch{}finally{Ar.end()}we.enqueue({type:"finish-step",finishReason:us,usage:rr,providerMetadata:td,response:{..._r,headers:nt?.headers}});const So=Jg(He,rr);await U.promise;const To=Oi.filter(Mr=>Mr.providerExecuted!==!0),Ai=Qu.filter(Mr=>Mr.providerExecuted!==!0);if(To.length>0&&Ai.length===To.length&&!await tv({stopConditions:f,steps:H})){he.push(...Nu({content:H[H.length-1].content,tools:c}));try{await X({currentStep:ue+1,responseMessages:he,usage:So})}catch(Mr){we.enqueue({type:"error",error:Mr}),G.closeStream()}}else we.enqueue({type:"finish",finishReason:us,totalUsage:So}),G.closeStream()}})))}await X({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(K=>{G.addStream(new ReadableStream({start(X){X.enqueue({type:"error",error:K}),X.close()}})),G.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return wi(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return wi(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await r7({stream:this.fullStream,onError:t?.onError})}catch(r){(e=t?.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new tg;return wi(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=Kn}={}){const c=e!=null?W8({originalMessages:t,responseMessageId:e}):void 0,u={},p=d=>{var f,w;const m=u[d];return((w=(f=this.tools)==null?void 0:f[m])==null?void 0:w.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(d,f)=>{const w=n?.({part:d}),m=d.type;switch(m){case"text-start":{f.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{s&&f.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{o&&d.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),o&&d.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const y=p(d.id);f.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const y=p(d.toolCallId);d.invalid?f.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(d.error)}):f.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=p(d.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=p(d.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{f.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...w!=null?{messageMetadata:w}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:d.finishReason,...w!=null?{messageMetadata:w}:{}});break}case"abort":{f.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const y=m;throw new Error(`Unknown chunk type: ${y}`)}}w!=null&&m!=="start"&&m!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:w})}}));return wi(e7({stream:h,messageId:c??e?.(),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){t7({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(t,e){J8({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:l,...c}={}){return G8({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(t){return B8({textStream:this.textStream,...t})}};ao({prefix:"aiobj",size:24}),ao({prefix:"aiobj",size:24});var c7={};QC(c7,{object:()=>d7,text:()=>u7});var u7=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),d7=({schema:t})=>{const e=pi(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const n=await cv(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await wn({text:r});if(!s.success)throw new hg({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Kt({value:s.value,schema:e});if(!o.success)throw new hg({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},p7="AI_MCPClientError",pv=`vercel.ai.error.${p7}`,f7=Symbol.for(pv),fv,hv,De=class extends(hv=ve,fv=f7,hv){constructor({name:t="MCPClientError",message:e,cause:r,data:n,code:s}){super({name:t,message:e,cause:r}),this[fv]=!0,this.data=n,this.code=s}static isInstance(t){return ve.hasMarker(t,pv)}},ss="2025-06-18",h7=[ss,"2025-03-26","2024-11-05"],m7=Ye({name:v(),version:v()}),bi=Ye({_meta:Q(C({}).loose())}),Ir=bi,mv=C({method:v(),params:Q(bi)}),gv=C({applyDefaults:Q(ge())}).loose(),g7=Ye({experimental:Q(C({}).loose()),logging:Q(C({}).loose()),prompts:Q(Ye({listChanged:Q(ge())})),resources:Q(Ye({subscribe:Q(ge()),listChanged:Q(ge())})),tools:Q(Ye({listChanged:Q(ge())})),elicitation:Q(gv)});C({elicitation:Q(gv)}).loose();var v7=Ir.extend({protocolVersion:v(),capabilities:g7,serverInfo:m7,instructions:Q(v())}),qu=Ir.extend({nextCursor:Q(v())}),_7=C({name:v(),description:Q(v()),inputSchema:C({type:j("object"),properties:Q(C({}).loose())}).loose()}).loose(),y7=qu.extend({tools:N(_7)}),vv=C({type:j("text"),text:v()}).loose(),_v=C({type:j("image"),data:Lf(),mimeType:v()}).loose(),w7=C({uri:v(),name:v(),title:Q(v()),description:Q(v()),mimeType:Q(v()),size:Q(L())}).loose(),b7=qu.extend({resources:N(w7)}),yv=C({uri:v(),name:Q(v()),title:Q(v()),mimeType:Q(v())}).loose(),wv=yv.extend({text:v()}),bv=yv.extend({blob:Lf()}),kv=C({type:j("resource"),resource:ce([wv,bv])}).loose(),k7=Ir.extend({content:N(ce([vv,_v,kv])),isError:ge().default(!1).optional()}).or(Ir.extend({toolResult:Le()})),S7=C({uriTemplate:v(),name:v(),title:Q(v()),description:Q(v()),mimeType:Q(v())}).loose(),T7=Ir.extend({resourceTemplates:N(S7)}),C7=Ir.extend({contents:N(ce([wv,bv]))}),$7=C({name:v(),description:Q(v()),required:Q(ge())}).loose(),E7=C({name:v(),title:Q(v()),description:Q(v()),arguments:Q(N($7))}).loose(),x7=qu.extend({prompts:N(E7)}),I7=C({role:ce([j("user"),j("assistant")]),content:ce([vv,_v,kv])}).loose(),R7=Ir.extend({description:Q(v()),messages:N(I7)}),P7=bi.extend({message:v(),requestedSchema:Le()}),Sv=mv.extend({method:j("elicitation/create"),params:P7}),O7=Ir.extend({action:ce([j("accept"),j("decline"),j("cancel")]),content:Q(Se(v(),Le()))}),ki="2.0",A7=C({jsonrpc:j(ki),id:ce([v(),L().int()])}).merge(mv).strict(),M7=C({jsonrpc:j(ki),id:ce([v(),L().int()]),result:Ir}).strict(),N7=C({jsonrpc:j(ki),id:ce([v(),L().int()]),error:C({code:L().int(),message:v(),data:Q(Le())})}).strict(),L7=C({jsonrpc:j(ki)}).merge(C({method:v(),params:Q(bi)})).strict(),yo=ce([A7,L7,M7,N7]),Tv=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Cv=C({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:L().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),$t=v().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Jf.custom,message:"URL must be parseable",fatal:!0}),Vp}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),j7=C({resource:v().url(),authorization_servers:N($t).optional(),jwks_uri:v().url().optional(),scopes_supported:N(v()).optional(),bearer_methods_supported:N(v()).optional(),resource_signing_alg_values_supported:N(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ge().optional(),authorization_details_types_supported:N(v()).optional(),dpop_signing_alg_values_supported:N(v()).optional(),dpop_bound_access_tokens_required:ge().optional()}).passthrough(),$v=C({issuer:v(),authorization_endpoint:$t,token_endpoint:$t,registration_endpoint:$t.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),grant_types_supported:N(v()).optional(),code_challenge_methods_supported:N(v()),token_endpoint_auth_methods_supported:N(v()).optional(),token_endpoint_auth_signing_alg_values_supported:N(v()).optional()}).passthrough(),q7=C({issuer:v(),authorization_endpoint:$t,token_endpoint:$t,userinfo_endpoint:$t.optional(),jwks_uri:$t,registration_endpoint:$t.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),grant_types_supported:N(v()).optional(),subject_types_supported:N(v()),id_token_signing_alg_values_supported:N(v()),claims_supported:N(v()).optional(),token_endpoint_auth_methods_supported:N(v()).optional()}).passthrough(),z7=q7.merge($v.pick({code_challenge_methods_supported:!0})),D7=C({client_id:v(),client_secret:v().optional(),client_id_issued_at:L().optional(),client_secret_expires_at:L().optional()}).strip(),U7=C({redirect_uris:N($t),token_endpoint_auth_method:v().optional(),grant_types:N(v()).optional(),response_types:N(v()).optional(),client_name:v().optional(),client_uri:$t.optional(),logo_uri:$t.optional(),scope:v().optional(),contacts:N(v()).optional(),tos_uri:$t.optional(),policy_uri:v().optional(),jwks_uri:$t.optional(),jwks:ht().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),Z7=C({error:v(),error_description:v().optional(),error_uri:v().optional()}),F7=U7.merge(D7),V7="AI_MCPClientOAuthError",Ev=`vercel.ai.error.${V7}`,H7=Symbol.for(Ev),xv,Iv,wo=class extends(Iv=ve,xv=H7,Iv){constructor({name:t="MCPClientOAuthError",message:e,cause:r}){super({name:t,message:e,cause:r}),this[xv]=!0}static isInstance(t){return ve.hasMarker(t,Ev)}},os=class extends wo{};os.errorCode="server_error";var Si=class extends wo{};Si.errorCode="invalid_client";var Ti=class extends wo{};Ti.errorCode="invalid_grant";var Ci=class extends wo{};Ci.errorCode="unauthorized_client";var B7={[os.errorCode]:os,[Si.errorCode]:Si,[Ti.errorCode]:Ti,[Ci.errorCode]:Ci};function J7(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function G7({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}var $i=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Ei(t){var e;const r=(e=t.headers.get("www-authenticate"))!=null?e:t.headers.get("WWW-Authenticate");if(!r)return;const[n,s]=r.split(" ");if(n.toLowerCase()!=="bearer"||!s)return;const o=/resource_metadata="([^"]*)"/,a=r.match(o);if(a)try{return new URL(a[1])}catch{return}}function W7(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function zu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?zu(t,void 0,r):void 0;throw n}}async function Rv(t,e,r=fetch){return await zu(t,{"MCP-Protocol-Version":e},r)}function K7(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Y7(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!=null?s:ss;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=W7(e,a.pathname);l=new URL(u,(o=n?.metadataServerUrl)!=null?o:a),l.search=a.search}let c=await Rv(l,i,r);if(!n?.metadataUrl&&K7(c,a.pathname)){const u=new URL(`/.well-known/${e}`,a);c=await Rv(u,i,r)}return c}async function Q7(t,e,r=fetch){const n=await Y7(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.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 j7.parse(await n.json())}function X7(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function e$(t,{fetchFn:e=fetch,protocolVersion:r=ss}={}){var n;const s={"MCP-Protocol-Version":r},o=X7(t);for(const{url:a,type:i}of o){const l=await zu(a,s,e);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return $v.parse(await l.json());{const c=z7.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function t$(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){const i="code",l="S256";let c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",t);const u=await n0(),p=u.code_verifier,h=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",h),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),o&&c.searchParams.set("state",o),s&&c.searchParams.set("scope",s),s?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:p}}function Pv(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Ov(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":r$(s,o,r);return;case"client_secret_post":n$(s,o,n);return;case"none":s$(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function r$(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function n$(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function s$(t,e){e.set("client_id",t)}async function Du(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=Z7.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=B7[s]||os;return new i({message:o||"",cause:a})}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new os({message:s})}}async function o$(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",p=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(h,d,t,e);else{const w=(c=e?.token_endpoint_auth_methods_supported)!=null?c:[],m=Pv(r,w);Ov(m,r,h,d)}a&&d.set("resource",a.href);const f=await(l??fetch)(p,{method:"POST",headers:h,body:d});if(!f.ok)throw await Du(f);return Cv.parse(await f.json())}async function a$(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){var i;const l="refresh_token";let c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:l,refresh_token:n});if(o)o(u,p,t,e);else{const d=(i=e?.token_endpoint_auth_methods_supported)!=null?i:[],f=Pv(r,d);Ov(f,r,u,p)}s&&p.set("resource",s.href);const h=await(a??fetch)(c,{method:"POST",headers:u,body:p});if(!h.ok)throw await Du(h);return Cv.parse({refresh_token:n,...await h.json()})}async function i$(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await Du(o);return F7.parse(await o.json())}async function xi(t,e){var r,n;try{return await Uu(t,e)}catch(s){if(s instanceof Si||s instanceof Ci)return await((r=t.invalidateCredentials)==null?void 0:r.call(t,"all")),await Uu(t,e);if(s instanceof Ti)return await((n=t.invalidateCredentials)==null?void 0:n.call(t,"tokens")),await Uu(t,e);throw s}}async function l$(t,e,r){const n=J7(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!G7({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 Uu(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await Q7(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=e);const l=await l$(e,t,a),c=await e$(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const w=await i$(i,{metadata:c,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(w),u=w}if(r!==void 0){const w=await t.codeVerifier(),m=await o$(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:w,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(m),"AUTHORIZED"}const p=await t.tokens();if(p?.refresh_token)try{const w=await a$(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof wo)||w instanceof os))throw w}const h=t.state?await t.state():void 0,{authorizationUrl:d,codeVerifier:f}=await t$(i,{metadata:c,clientInformation:u,state:h,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(f),await t.redirectToAuthorization(d),"REDIRECT"}var c$=class{constructor({url:t,headers:e,authProvider:r}){this.connected=!1,this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":ss};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Wr(e,`ai-sdk/${Tv}`,lo())}async start(){return new Promise((t,e)=>{if(this.connected)return t();this.abortController=new AbortController;const r=async(n=!1)=>{var s,o,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(s=this.abortController)==null?void 0:s.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ei(u);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new $i;return(o=this.onerror)==null||o.call(this,w),e(w)}}catch(f){return(a=this.onerror)==null||a.call(this,f),e(f)}return r(!0)}if(!u.ok||!u.body){let f=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(f+=". This server does not support SSE transport. Try using `http` transport instead");const w=new De({message:f});return(i=this.onerror)==null||i.call(this,w),e(w)}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).getReader(),d=async()=>{var f,w,m;try{for(;;){const{done:y,value:_}=await h.read();if(y){if(this.connected)throw this.connected=!1,new De({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:g,data:b}=_;if(g==="endpoint"){if(this.endpoint=new URL(b,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,t()}else if(g==="message")try{const k=yo.parse(JSON.parse(b));(f=this.onmessage)==null||f.call(this,k)}catch(k){const S=new De({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(w=this.onerror)==null||w.call(this,S)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(m=this.onerror)==null||m.call(this,y),e(y)}};this.sseConnection={close:()=>h.cancel()},d()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),e(c)}};r()})}async close(){var t,e,r;this.connected=!1,(t=this.sseConnection)==null||t.close(),(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){if(!this.endpoint||!this.connected)throw new De({message:"MCP SSE Transport Error: Not connected"});const e=this.endpoint,r=async(n=!1)=>{var s,o,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(t),signal:(s=this.abortController)==null?void 0:s.signal},p=await fetch(e,u);if(p.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ei(p);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new $i;(o=this.onerror)==null||o.call(this,d);return}}catch(h){(a=this.onerror)==null||a.call(this,h);return}return r(!0)}if(!p.ok){const h=await p.text().catch(()=>null),d=new De({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${p.status}): ${h}`});(i=this.onerror)==null||i.call(this,d);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},u$=class{constructor({url:t,headers:e,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":ss};if(this.sessionId&&(e["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Wr(e,`ai-sdk/${Tv}`,lo())}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 t,e,r;(t=this.inboundSseConnection)==null||t.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{}(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){const e=async(r=!1)=>{var n,s,o,a,i,l,c;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(t),signal:(n=this.abortController)==null?void 0:n.signal},h=await fetch(this.url,p),d=h.headers.get("mcp-session-id");if(d&&(this.sessionId=d),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Ei(h);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new $i}catch(m){throw(s=this.onerror)==null||s.call(this,m),m}return e(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const m=await h.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${m}`;h.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const _=new De({message:y});throw(o=this.onerror)==null||o.call(this,_),_}const f=h.headers.get("content-type")||"";if(f.includes("application/json")){const m=await h.json(),y=Array.isArray(m)?m.map(_=>yo.parse(_)):[yo.parse(m)];for(const _ of y)(a=this.onmessage)==null||a.call(this,_);return}if(f.includes("text/event-stream")){if(!h.body){const g=new De({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,g),g}const y=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).getReader();(async()=>{var g,b,k;try{for(;;){const{done:S,value:T}=await y.read();if(S)return;const{event:x,data:I}=T;if(x==="message")try{const A=yo.parse(JSON.parse(I));(g=this.onmessage)==null||g.call(this,A)}catch(A){const P=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:A});(b=this.onerror)==null||b.call(this,P)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const w=new De({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`});throw(l=this.onerror)==null||l.call(this,w),w}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await e()}getNextReconnectionDelay(t){const{initialReconnectionDelay:e,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(e*Math.pow(r,t),n)}scheduleInboundSseReconnection(){var t;const{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){(t=this.onerror)==null||t.call(this,new De({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) 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(t=!1,e){var r,n,s,o,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});e&&(l["last-event-id"]=e);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&&!t){this.resourceMetadataUrl=Ei(c);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new $i;(n=this.onerror)==null||n.call(this,w);return}}catch(f){(s=this.onerror)==null||s.call(this,f);return}return this.openInboundSse(!0,e)}if(c.status===405)return;if(!c.ok||!c.body){const f=new De({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(o=this.onerror)==null||o.call(this,f);return}const h=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).getReader(),d=async()=>{var f,w,m,y;try{for(;;){const{done:_,value:g}=await h.read();if(_)return;const{event:b,data:k,id:S}=g;if(S&&(this.lastInboundEventId=S),b==="message")try{const T=yo.parse(JSON.parse(k));(f=this.onmessage)==null||f.call(this,T)}catch(T){const x=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:T});(w=this.onerror)==null||w.call(this,x)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(m=this.onerror)==null||m.call(this,_),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,d()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function d$(t){switch(t.type){case"sse":return new c$(t);case"http":return new u$(t);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 p$(t){return"start"in t&&typeof t.start=="function"&&"send"in t&&typeof t.send=="function"&&"close"in t&&typeof t.close=="function"}var f$="1.0.0";async function h$(t){const e=new m$(t);return await e.init(),e}var m$=class{constructor({transport:t,name:e="ai-sdk-mcp-client",version:r=f$,onUncaughtError:n,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=s??{},p$(t)?this.transport=t:this.transport=d$(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new De({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:e,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const t=await this.request({request:{method:"initialize",params:{protocolVersion:ss,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:v7});if(t===void 0)throw new De({message:"Server sent invalid initialize result"});if(!h7.includes(t.protocolVersion))throw new De({message:`Server's protocol version is not supported: ${t.protocolVersion}`});return this.serverCapabilities=t.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(t){throw await this.close(),t}}async close(){var t;this.isClosed||(await((t=this.transport)==null?void 0:t.close()),this.onClose())}assertCapability(t){switch(t){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: ${t}`})}}async request({request:t,resultSchema:e,options:r}){return new Promise((n,s)=>{if(this.isClosed)return s(new De({message:"Attempted to send a request from a closed client"}));this.assertCapability(t.method);const o=r?.signal;o?.throwIfAborted();const a=this.requestMessageId++,i={...t,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(o?.aborted)return s(new De({message:"Request was aborted",cause:o.reason}));if(c instanceof Error)return s(c);try{const u=e.parse(c.result);n(u)}catch(u){const p=new De({message:"Failed to parse server response",cause:u});s(p)}}),this.transport.send(i).catch(c=>{l(),s(c)})})}async listTools({params:t,options:e}={}){try{return this.request({request:{method:"tools/list",params:t},resultSchema:y7,options:e})}catch(r){throw r}}async callTool({name:t,args:e,options:r}){try{return this.request({request:{method:"tools/call",params:{name:t,arguments:e}},resultSchema:k7,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:t,options:e}={}){try{return this.request({request:{method:"resources/list",params:t},resultSchema:b7,options:e})}catch(r){throw r}}async readResourceInternal({uri:t,options:e}){try{return this.request({request:{method:"resources/read",params:{uri:t}},resultSchema:C7,options:e})}catch(r){throw r}}async listResourceTemplatesInternal({options:t}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:T7,options:t})}catch(e){throw e}}async listPromptsInternal({params:t,options:e}={}){try{return this.request({request:{method:"prompts/list",params:t},resultSchema:x7,options:e})}catch(r){throw r}}async getPromptInternal({name:t,args:e,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:t,arguments:e}},resultSchema:R7,options:r})}catch(n){throw n}}async notification(t){const e={...t,jsonrpc:"2.0"};await this.transport.send(e)}async tools({schemas:t="automatic"}={}){var e;const r={};try{const n=await this.listTools();for(const{name:s,description:o,inputSchema:a}of n.tools){if(t!=="automatic"&&!(s in t))continue;const i=this,l=async(u,p)=>{var h;return(h=p?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:s,args:u,options:p})},c=t==="automatic"?Xm({description:o,inputSchema:co({...a,properties:(e=a.properties)!=null?e:{},additionalProperties:!1}),execute:l}):{description:o,inputSchema:t[s].inputSchema,execute:l};r[s]=c}return r}catch(n){throw n}}listResources({params:t,options:e}={}){return this.listResourcesInternal({params:t,options:e})}readResource({uri:t,options:e}){return this.readResourceInternal({uri:t,options:e})}listResourceTemplates({options:t}={}){return this.listResourceTemplatesInternal({options:t})}listPrompts({params:t,options:e}={}){return this.listPromptsInternal({params:t,options:e})}getPrompt({name:t,arguments:e,options:r}){return this.getPromptInternal({name:t,args:e,options:r})}onElicitationRequest(t,e){if(t!==Sv)throw new De({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=e}async onRequestMessage(t){try{if(t.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`Unsupported request method: ${t.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const e=Sv.safeParse({method:t.method,params:t.params});if(!e.success){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32602,message:`Invalid elicitation request: ${e.error.message}`,data:e.error.issues}});return}try{const r=await this.elicitationRequestHandler(e.data),n=O7.parse(r);await this.transport.send({jsonrpc:"2.0",id:t.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const t=new De({message:"Connection closed"});for(const e of this.responseHandlers.values())e(t);this.responseHandlers.clear()}onError(t){this.onUncaughtError&&this.onUncaughtError(t)}onResponse(t){const e=Number(t.id),r=this.responseHandlers.get(e);if(r===void 0)throw new De({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(t)}`});this.responseHandlers.delete(e),r("result"in t?t:new De({message:t.error.message,code:t.error.code,data:t.error.data,cause:t.error}))}};function gr(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function bo(t){return Object.fromEntries([...t.headers])}var g$=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new li({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},Xt=g$();function Zu(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var v$=["fetch failed","failed to fetch"];function _$({error:t,url:e,requestBodyValues:r}){if(Zu(t))return t;if(t instanceof TypeError&&v$.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new Ve({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function y$(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function w$(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function Av(t,...e){const r=new Headers(w$(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var b$="3.0.19";function k$({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Gr({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Gr({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function S$({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function T$(t){var e;const[r,n=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?e:n}var C$=/"__proto__"\s*:/,$$=/"constructor"\s*:/;function Mv(t){const e=JSON.parse(t);return e===null||typeof e!="object"||C$.test(t)===!1&&$$.test(t)===!1?e:E$(e)}function E$(t){let e=[t];for(;e.length;){const r=e;e=[];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 s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function Fu(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return Mv(t)}try{return Mv(t)}finally{Error.stackTraceLimit=e}}var Ii=Symbol.for("vercel.ai.validator");function x$(t){return{[Ii]:!0,validate:t}}function I$(t){return typeof t=="object"&&t!==null&&Ii in t&&t[Ii]===!0&&"validate"in t}function vt(t){let e;return()=>(e==null&&(e=t()),e)}function R$(t){return I$(t)?t:typeof t=="function"?t():P$(t)}function P$(t){return x$(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new dr({value:e,cause:r.issues})}})}async function Yr({value:t,schema:e}){const r=await Vu({value:t,schema:e});if(!r.success)throw dr.wrap({value:t,cause:r.error});return r.value}async function Vu({value:t,schema:e}){const r=R$(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:dr.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:dr.wrap({value:t,cause:n}),rawValue:t}}}async function O$({text:t,schema:e}){try{const r=Fu(t);return e==null?r:Yr({value:r,schema:e})}catch(r){throw Jr.isInstance(r)||dr.isInstance(r)?r:new Jr({text:t,cause:r})}}async function Nv({text:t,schema:e}){try{const r=Fu(t);return e==null?{success:!0,value:r,rawValue:r}:await Vu({value:r,schema:e})}catch(r){return{success:!1,error:Jr.isInstance(r)?r:new Jr({text:t,cause:r}),rawValue:void 0}}}function Lv(t){try{return Fu(t),!0}catch{return!1}}function A$({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Nv({text:r,schema:e}))}}))}async function Qr({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await Vu({value:e[t],schema:r});if(!n.success)throw new li({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var M$=()=>globalThis.fetch,Rr=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>jv({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),N$=async({url:t,headers:e,formData:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>jv({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),jv=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=M$()})=>{try{const i=await a(t,{method:"POST",headers:Av(e,`ai-sdk/provider-utils/${b$}`,y$()),body:r.content,signal:o}),l=bo(i);if(!i.ok){let c;try{c=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw Zu(u)||Ve.isInstance(u)?u:new Ve({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Zu(c)||Ve.isInstance(c))?c:new Ve({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw _$({error:i,url:t,requestBodyValues:r.values})}};function CI(t){return t}function as({id:t,name:e,inputSchema:r,outputSchema:n}){return({execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:t,name:e,args:c,inputSchema:r,outputSchema:n,execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:l})}var L$=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=bo(n);if(a.trim()==="")return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await O$({text:a,schema:t});return{responseHeaders:i,value:new Ve({message:e(l),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Hu=t=>async({response:e})=>{const r=bo(e);if(e.body==null)throw new vm({});return{responseHeaders:r,value:A$({stream:e.body,schema:t})}},is=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await Nv({text:s,schema:t}),a=bo(e);if(!o.success)throw new Ve({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},j$=()=>async({response:t,url:e,requestBodyValues:r})=>{const n=bo(t);if(!t.body)throw new Ve({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0});try{const s=await t.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(s)}}catch(s){throw new Ve({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0,cause:s})}};function Ri(t){if(t.type==="object"){t.additionalProperties=!1;const e=t.properties;if(e!=null)for(const r in e)e[r]=Ri(e[r])}return t.type==="array"&&t.items!=null&&(Array.isArray(t.items)?t.items=t.items.map(e=>Ri(e)):t.items=Ri(t.items)),t}var q$=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},z$=Symbol("Let zodToJsonSchema decide on which parser to use"),qv={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"},D$=t=>typeof t=="string"?{...qv,name:t}:{...qv,...t};function Nt(){return{}}function U$(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=Ue(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function Z$(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function F$(){return{type:"boolean"}}function zv(t,e){return Ue(t.type._def,e)}var V$=(t,e)=>Ue(t.innerType._def,e);function Dv(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Dv(t,e,s))};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 H$(t)}}var H$=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function B$(t,e){return{...Ue(t.innerType._def,e),default:t.defaultValue()}}function J$(t,e){return e.effectStrategy==="input"?Ue(t.schema._def,e):Nt()}function G$(t){return{type:"string",enum:Array.from(t.values)}}var W$=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function K$(t,e){const r=[Ue(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ue(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(W$(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function Y$(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Bu=void 0,er={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:()=>(Bu===void 0&&(Bu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Bu),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 Uv(t,e){const r={type:"string"};if(t.checks)for(const n of t.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(e.emailStrategy){case"format:email":tr(r,"email",n.message,e);break;case"format:idn-email":tr(r,"idn-email",n.message,e);break;case"pattern:zod":_t(r,er.email,n.message,e);break}break;case"url":tr(r,"uri",n.message,e);break;case"uuid":tr(r,"uuid",n.message,e);break;case"regex":_t(r,n.regex,n.message,e);break;case"cuid":_t(r,er.cuid,n.message,e);break;case"cuid2":_t(r,er.cuid2,n.message,e);break;case"startsWith":_t(r,RegExp(`^${Ju(n.value,e)}`),n.message,e);break;case"endsWith":_t(r,RegExp(`${Ju(n.value,e)}$`),n.message,e);break;case"datetime":tr(r,"date-time",n.message,e);break;case"date":tr(r,"date",n.message,e);break;case"time":tr(r,"time",n.message,e);break;case"duration":tr(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{_t(r,RegExp(Ju(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&tr(r,"ipv4",n.message,e),n.version!=="v4"&&tr(r,"ipv6",n.message,e);break}case"base64url":_t(r,er.base64url,n.message,e);break;case"jwt":_t(r,er.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&_t(r,er.ipv4Cidr,n.message,e),n.version!=="v4"&&_t(r,er.ipv6Cidr,n.message,e);break}case"emoji":_t(r,er.emoji(),n.message,e);break;case"ulid":{_t(r,er.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{tr(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{_t(r,er.base64,n.message,e);break}}break}case"nanoid":_t(r,er.nanoid,n.message,e)}return r}function Ju(t,e){return e.patternStrategy==="escape"?X$(t):t}var Q$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function X$(t){let e="";for(let r=0;r<t.length;r++)Q$.has(t[r])||(e+="\\"),e+=t[r];return e}function tr(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function _t(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Zv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Zv(e,n)}function Zv(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,l=!1;for(let c=0;c<s.length;c++){if(a){o+=s[c],a=!1;continue}if(n.i){if(i){if(s[c].match(/[a-z]/)){l?(o+=s[c],o+=`${s[c-2]}-${s[c]}`.toUpperCase(),l=!1):s[c+1]==="-"&&((r=s[c+2])!=null&&r.match(/[a-z]/))?(o+=s[c],l=!0):o+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){o+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(n.m){if(s[c]==="^"){o+=`(^|(?<=[\r
573
+ `)}})}},iv={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function G8({status:t,statusText:e,headers:r,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new av);if(s){const[a,i]=o.tee();o=a,s({stream:i})}return new Response(o.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:yi(r,iv)})}function W8({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return r?.role==="assistant"?r.id:typeof e=="function"?e():e}function K8(t){return t.type.startsWith("data-")}function lv(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const s=e[n];if(s===void 0)continue;const o=n in t?t[n]:void 0,a=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),i=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);a&&i?r[n]=lv(o,s):r[n]=s}return r}function Y8(t){const e=["ROOT"];let r=-1,n=null;function s(l,c,u){switch(l){case'"':{r=c,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,e.pop(),e.push(u),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(u),e.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,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function o(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function a(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":s(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.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",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const p=t.substring(n,l+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(n,t.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function cv(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await wn({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await wn({text:Y8(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Nu(t){return t.type.startsWith("tool-")}function uv(t){return t.type.split("-").slice(1).join("-")}function Q8({lastMessage:t,messageId:e}){return{message:t?.role==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function X8({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:n,onError:s,onToolCall:o,onData:a}){return t.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var p,h,d,f;function w(b){const S=c.message.parts.filter(Nu).find(T=>T.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function m(b){const S=c.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===b);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function y(b){var k;const S=c.message.parts.find(I=>Nu(I)&&I.toolCallId===b.toolCallId),T=b,x=S;S!=null?(S.state=b.state,x.input=T.input,x.output=T.output,x.errorText=T.errorText,x.rawInput=T.rawInput,x.preliminary=T.preliminary,x.providerExecuted=(k=T.providerExecuted)!=null?k:S.providerExecuted,T.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=T.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function _(b){var k,S;const T=c.message.parts.find(A=>A.type==="dynamic-tool"&&A.toolCallId===b.toolCallId),x=b,I=T;T!=null?(T.state=b.state,I.toolName=b.toolName,I.input=x.input,I.output=x.output,I.errorText=x.errorText,I.rawInput=(k=x.rawInput)!=null?k:I.rawInput,I.preliminary=x.preliminary,I.providerExecuted=(S=x.providerExecuted)!=null?S:T.providerExecuted,x.providerMetadata!=null&&T.state==="input-available"&&(T.callProviderMetadata=x.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,...x.providerMetadata!=null?{callProviderMetadata:x.providerMetadata}:{}})}async function g(b){if(b!=null){const k=c.message.metadata!=null?lv(c.message.metadata,b):b;e!=null&&await au({value:k,schema:e}),c.message.metadata=k}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(p=i.providerMetadata)!=null?p:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[i.id];b.state="done",b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[i.id];b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,b.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(Nu);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:k}=await cv(b.text);b.dynamic?_({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}):y({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:k}),u();break}case"tool-input-available":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),o&&!i.providerExecuted&&await o({toolCall:i});break}case"tool-input-error":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:uv(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText,providerExecuted:i.providerExecuted})}else{const b=w(i.toolCallId);y({toolCallId:i.toolCallId,toolName:uv(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await g(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await g(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await g(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{s?.(new Error(i.errorText));break}default:if(K8(i)){r?.[i.type]!=null&&await au({value:i.data,schema:r[i.type]});const b=i;if(b.transient){a?.(b);break}const k=b.id!=null?c.message.parts.find(S=>b.type===S.type&&b.id===S.id):void 0;k!=null?k.data=b.data:c.message.parts.push(b),a?.(b),u()}}l.enqueue(i)})}}))}function e7({messageId:t,originalMessages:e=[],onFinish:r,onError:n,stream:s}){let o=e?.[e.length-1];o?.role!=="assistant"?o=void 0:t=o.id;let a=!1;const i=s.pipeThrough(new TransformStream({transform(h,d){if(h.type==="start"){const f=h;f.messageId==null&&t!=null&&(f.messageId=t)}h.type==="abort"&&(a=!0),d.enqueue(h)}}));if(r==null)return i;const l=Q8({lastMessage:o?structuredClone(o):void 0,messageId:t??""}),c=async h=>{await h({state:l,write:()=>{}})};let u=!1;const p=async()=>{if(u||!r)return;u=!0;const h=l.message.id===o?.id;await r({isAborted:a,isContinuation:h,responseMessage:l.message,messages:[...h?e.slice(0,-1):e,l.message],finishReason:l.finishReason})};return X8({stream:i,runUpdateMessageJob:c,onError:n}).pipeThrough(new TransformStream({transform(h,d){d.enqueue(h)},async cancel(){await p()},async flush(){await p()}}))}function t7({response:t,status:e,statusText:r,headers:n,stream:s,consumeSseStream:o}){let a=s.pipeThrough(new av);if(o){const[i,l]=a.tee();a=i,o({stream:l})}ov({response:t,status:e,statusText:r,headers:Object.fromEntries(yi(n,iv).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function wi(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function s(o){var a;n=!0;try{o&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:o,value:a}=await r.read();return o?(await s(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await s(!0),{done:!0,value:void 0}},async throw(o){throw await s(!0),o}}},e}async function r7({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){e?.(n)}finally{r.releaseLock()}}function dv(){let t,e;return{promise:new Promise((n,s)=>{t=n,e=s}),resolve:t,reject:e}}function n7(){let t=[],e=null,r=!1,n=dv();const s=()=>{r=!0,n.resolve(),t.forEach(a=>a.cancel()),t=[],e?.close()},o=async()=>{if(r&&t.length===0){e?.close();return}if(t.length===0)return n=dv(),await n.promise,o();try{const{value:a,done:i}=await t[0].read();i?(t.shift(),t.length>0?await o():r&&e?.close()):e?.enqueue(a)}catch(a){e?.error(a),t.shift(),s()}};return{stream:new ReadableStream({start(a){e=a},pull:o,async cancel(){for(const a of t)await a.cancel();t=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),t.length===0&&e?.close()},terminate:s}}function s7(){var t,e;return(e=(t=globalThis?.performance)==null?void 0:t.now())!=null?e:Date.now()}function o7({tools:t,generatorStream:e,tracer:r,telemetry:n,system:s,messages:o,abortSignal:a,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(y){c=y}}),p=new Set,h=new Map;let d=!1,f;function w(){d&&p.size===0&&(f!=null&&c.enqueue(f),c.close())}const m=new TransformStream({async transform(y,_){const g=y.type;switch(g){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{_.enqueue(y);break}case"file":{_.enqueue({type:"file",file:new U8({data:y.data,mediaType:y.mediaType})});break}case"finish":{f={type:"finish",finishReason:y.finishReason,usage:y.usage,providerMetadata:y.providerMetadata};break}case"tool-call":{try{const b=await Qg({toolCall:y,tools:t,repairToolCall:i,system:s,messages:o});if(_.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:su(b.error),dynamic:!0});break}const k=t[b.toolName];if(h.set(b.toolCallId,b.input),k.onInputAvailable!=null&&await k.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:l}),k.execute!=null&&b.providerExecuted!==!0){const S=io();p.add(S),ns({name:"ai.toolCall",attributes:Dt({telemetry:n,attributes:{...rs({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async T=>{let x;try{const I=l2({execute:k.execute.bind(k),input:b.input,options:{toolCallId:b.toolCallId,messages:o,abortSignal:a,experimental_context:l}});for await(const A of I)c.enqueue({...b,type:"tool-result",output:A.output,...A.type==="preliminary"&&{preliminary:!0}}),A.type==="final"&&(x=A.output)}catch(I){Ru(T,I),c.enqueue({...b,type:"tool-error",error:I}),p.delete(S),w();return}p.delete(S),w();try{T.setAttributes(Dt({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(x)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=y.toolName;y.isError?c.enqueue({type:"tool-error",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),providerExecuted:y.providerExecuted,error:y.result}):_.enqueue({type:"tool-result",toolCallId:y.toolCallId,toolName:b,input:h.get(y.toolCallId),output:y.result,providerExecuted:y.providerExecuted});break}default:{const b=g;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,w()}});return new ReadableStream({async start(y){return Promise.all([e.pipeThrough(m).pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){}})),u.pipeTo(new WritableStream({write(_){y.enqueue(_)},close(){y.close()}}))])}})}var a7=ao({prefix:"aitxt",size:24});function Lu({model:t,tools:e,toolChoice:r,system:n,prompt:s,messages:o,maxRetries:a,abortSignal:i,headers:l,stopWhen:c=Ou(1),experimental_output:u,experimental_telemetry:p,prepareStep:h,providerOptions:d,experimental_activeTools:f,activeTools:w=f,experimental_repairToolCall:m,experimental_transform:y,experimental_download:_,includeRawChunks:g=!1,onChunk:b,onError:k=({error:V})=>{console.error(V)},onFinish:S,onAbort:T,onStepFinish:x,experimental_context:I,_internal:{now:A=s7,generateId:P=a7,currentDate:D=()=>new Date}={},...U}){return new l7({model:vi(t),telemetry:p,headers:l,settings:U,maxRetries:a,abortSignal:i,system:n,prompt:s,messages:o,tools:e,toolChoice:r,transforms:Pu(y),activeTools:w,repairToolCall:m,stopConditions:Pu(c),output:u,providerOptions:d,prepareStep:h,includeRawChunks:g,onChunk:b,onError:k,onFinish:S,onAbort:T,onStepFinish:x,now:A,currentDate:D,generateId:P,experimental_context:I,download:_})}function i7(t){if(!t)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let e,r="",n="",s="";function o({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:e,text:n},partialOutput:i}),n=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&n.length>0&&o({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(e==null)e=a.id;else if(a.id!==e){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){n.length>0&&o({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}r+=a.text,n+=a.text;const l=await t.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==s&&(o({controller:i,partialOutput:l.partial}),s=c)}}})}var l7=class{constructor({model:t,telemetry:e,headers:r,settings:n,maxRetries:s,abortSignal:o,system:a,prompt:i,messages:l,tools:c,toolChoice:u,transforms:p,activeTools:h,repairToolCall:d,stopConditions:f,output:w,providerOptions:m,prepareStep:y,includeRawChunks:_,now:g,currentDate:b,generateId:k,onChunk:S,onError:T,onFinish:x,onAbort:I,onStepFinish:A,experimental_context:P,download:D}){this._totalUsage=new ci,this._finishReason=new ci,this._steps=new ci,this.output=w,this.includeRawChunks=_,this.tools=c;let U,V=[];const se=[];let fe,de,re={},_e=[];const H=[];let O,F={},q={};const E=new TransformStream({async transform(K,X){var ue,he,He,Je;X.enqueue(K);const{part:ee}=K;if((ee.type==="text-delta"||ee.type==="reasoning-delta"||ee.type==="source"||ee.type==="tool-call"||ee.type==="tool-result"||ee.type==="tool-input-start"||ee.type==="tool-input-delta"||ee.type==="raw")&&await S?.({chunk:ee}),ee.type==="error"&&await T({error:Fg(ee.error)}),ee.type==="text-start"&&(F[ee.id]={type:"text",text:"",providerMetadata:ee.providerMetadata},V.push(F[ee.id])),ee.type==="text-delta"){const be=F[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}be.text+=ee.text,be.providerMetadata=(ue=ee.providerMetadata)!=null?ue:be.providerMetadata}if(ee.type==="text-end"){const be=F[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}be.providerMetadata=(he=ee.providerMetadata)!=null?he:be.providerMetadata,delete F[ee.id]}if(ee.type==="reasoning-start"&&(q[ee.id]={type:"reasoning",text:"",providerMetadata:ee.providerMetadata},V.push(q[ee.id])),ee.type==="reasoning-delta"){const be=q[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}be.text+=ee.text,be.providerMetadata=(He=ee.providerMetadata)!=null?He:be.providerMetadata}if(ee.type==="reasoning-end"){const be=q[ee.id];if(be==null){X.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}be.providerMetadata=(Je=ee.providerMetadata)!=null?Je:be.providerMetadata,delete q[ee.id]}if(ee.type==="file"&&V.push({type:"file",file:ee.file}),ee.type==="source"&&V.push(ee),ee.type==="tool-call"&&V.push(ee),ee.type==="tool-result"&&!ee.preliminary&&V.push(ee),ee.type==="tool-error"&&V.push(ee),ee.type==="start-step"&&(re=ee.request,_e=ee.warnings),ee.type==="finish-step"){const be=Mu({content:V,tools:c}),yt=new ev({content:V,finishReason:ee.finishReason,usage:ee.usage,warnings:_e,request:re,response:{...ee.response,messages:[...se,...be]},providerMetadata:ee.providerMetadata});await A?.(yt),ng(_e),H.push(yt),V=[],q={},F={},se.push(...be),U.resolve()}ee.type==="finish"&&(de=ee.totalUsage,fe=ee.finishReason)},async flush(K){try{if(H.length===0){const He=new a8({message:"No output generated. Check the stream for errors."});G._finishReason.reject(He),G._totalUsage.reject(He),G._steps.reject(He);return}const X=fe??"unknown",ue=de??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};G._finishReason.resolve(X),G._totalUsage.resolve(ue),G._steps.resolve(H);const he=H[H.length-1];await x?.({finishReason:X,totalUsage:ue,usage:he.usage,content:he.content,text:he.text,reasoningText:he.reasoningText,reasoning:he.reasoning,files:he.files,sources:he.sources,toolCalls:he.toolCalls,staticToolCalls:he.staticToolCalls,dynamicToolCalls:he.dynamicToolCalls,toolResults:he.toolResults,staticToolResults:he.staticToolResults,dynamicToolResults:he.dynamicToolResults,request:he.request,response:he.response,warnings:he.warnings,providerMetadata:he.providerMetadata,steps:H}),O.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":X,"ai.response.text":{output:()=>he.text},"ai.response.toolCalls":{output:()=>{var He;return(He=he.toolCalls)!=null&&He.length?JSON.stringify(he.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(he.providerMetadata),"ai.usage.inputTokens":ue.inputTokens,"ai.usage.outputTokens":ue.outputTokens,"ai.usage.totalTokens":ue.totalTokens,"ai.usage.reasoningTokens":ue.reasoningTokens,"ai.usage.cachedInputTokens":ue.cachedInputTokens}}))}catch(X){K.error(X)}finally{O.end()}}}),R=n7();this.addStream=R.addStream,this.closeStream=R.close;const $=R.stream.getReader();let B=new ReadableStream({async start(K){K.enqueue({type:"start"})},async pull(K){function X(){I?.({steps:H}),K.enqueue({type:"abort"}),K.close()}try{const{done:ue,value:he}=await $.read();if(ue){K.close();return}if(o?.aborted){X();return}K.enqueue(he)}catch(ue){yn(ue)&&o?.aborted?X():K.error(ue)}},cancel(K){return R.stream.cancel(K)}});for(const K of p)B=B.pipeThrough(K({tools:c,stopStream(){R.terminate()}}));this.baseStream=B.pipeThrough(i7(w)).pipeThrough(E);const{maxRetries:W,retry:ye}=Wg({maxRetries:s,abortSignal:o}),pe=Hg(e),M=Iu(n),Z=Vg({model:t,telemetry:e,headers:r,settings:{...M,maxRetries:W}}),G=this;ns({name:"ai.streamText",attributes:Dt({telemetry:e,attributes:{...rs({operationId:"ai.streamText",telemetry:e}),...Z,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:pe,endWhenDone:!1,fn:async K=>{O=K;async function X({currentStep:ue,responseMessages:he,usage:He}){var Je,ee,be,yt,xe;const Et=G.includeRawChunks;U=new ci;const Pr=await Zg({system:a,prompt:i,messages:l}),xt=[...Pr.messages,...he],it=await y?.({model:t,steps:H,stepNumber:H.length,messages:xt}),Ut=vi((Je=it?.model)!=null?Je:t),Xr=await jg({prompt:{system:(ee=it?.system)!=null?ee:Pr.system,messages:(be=it?.messages)!=null?be:xt},supportedUrls:await Ut.supportedUrls,download:D}),{toolChoice:en,tools:cs}=qg({tools:c,toolChoice:(yt=it?.toolChoice)!=null?yt:u,activeTools:(xe=it?.activeTools)!=null?xe:h}),{result:{stream:Pi,response:nt,request:Or},doStreamSpan:Ar,startTimestampMs:m_}=await ye(()=>ns({name:"ai.streamText.doStream",attributes:Dt({telemetry:e,attributes:{...rs({operationId:"ai.streamText.doStream",telemetry:e}),...Z,"ai.model.provider":Ut.provider,"ai.model.id":Ut.modelId,"ai.prompt.messages":{input:()=>Bg(Xr)},"ai.prompt.tools":{input:()=>cs?.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>en!=null?JSON.stringify(en):void 0},"gen_ai.system":Ut.provider,"gen_ai.request.model":Ut.modelId,"gen_ai.request.frequency_penalty":M.frequencyPenalty,"gen_ai.request.max_tokens":M.maxOutputTokens,"gen_ai.request.presence_penalty":M.presencePenalty,"gen_ai.request.stop_sequences":M.stopSequences,"gen_ai.request.temperature":M.temperature,"gen_ai.request.top_k":M.topK,"gen_ai.request.top_p":M.topP}}),tracer:pe,endWhenDone:!1,fn:async we=>({startTimestampMs:g(),doStreamSpan:we,result:await Ut.doStream({...M,tools:cs,toolChoice:en,responseFormat:w?.responseFormat,prompt:Xr,providerOptions:m,abortSignal:o,headers:r,includeRawChunks:Et})})})),sI=o7({tools:c,generatorStream:Pi,tracer:pe,telemetry:e,system:a,messages:xt,repairToolCall:d,abortSignal:o,experimental_context:P}),oI=Or??{},Oi=[],Yu=[];let Qu;const Xu={};let us="unknown",rr={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},ed,g_=!0,_r={id:k(),timestamp:b(),modelId:t.modelId},v_="";G.addStream(sI.pipeThrough(new TransformStream({async transform(we,lt){var So,To,Ai,Mr;if(we.type==="stream-start"){Qu=we.warnings;return}if(g_){const wt=g()-m_;g_=!1,Ar.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":wt}),Ar.setAttributes({"ai.response.msToFirstChunk":wt}),lt.enqueue({type:"start-step",request:oI,warnings:Qu??[]})}const __=we.type;switch(__){case"text-start":case"text-end":{lt.enqueue(we);break}case"text-delta":{we.delta.length>0&&(lt.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),v_+=we.delta);break}case"reasoning-start":case"reasoning-end":{lt.enqueue(we);break}case"reasoning-delta":{lt.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{lt.enqueue(we),Oi.push(we);break}case"tool-result":{lt.enqueue(we),we.preliminary||Yu.push(we);break}case"tool-error":{lt.enqueue(we),Yu.push(we);break}case"response-metadata":{_r={id:(So=we.id)!=null?So:_r.id,timestamp:(To=we.timestamp)!=null?To:_r.timestamp,modelId:(Ai=we.modelId)!=null?Ai:_r.modelId};break}case"finish":{rr=we.usage,us=we.finishReason,ed=we.providerMetadata;const wt=g()-m_;Ar.addEvent("ai.stream.finish"),Ar.setAttributes({"ai.response.msToFinish":wt,"ai.response.avgOutputTokensPerSecond":1e3*((Mr=rr.outputTokens)!=null?Mr:0)/wt});break}case"file":{lt.enqueue(we);break}case"source":{lt.enqueue(we);break}case"tool-input-start":{Xu[we.id]=we.toolName;const wt=c?.[we.toolName];wt?.onInputStart!=null&&await wt.onInputStart({toolCallId:we.id,messages:xt,abortSignal:o,experimental_context:P}),lt.enqueue({...we,dynamic:wt?.type==="dynamic"});break}case"tool-input-end":{delete Xu[we.id],lt.enqueue(we);break}case"tool-input-delta":{const wt=Xu[we.id],td=c?.[wt];td?.onInputDelta!=null&&await td.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:xt,abortSignal:o,experimental_context:P}),lt.enqueue(we);break}case"error":{lt.enqueue(we),us="error";break}case"raw":{Et&&lt.enqueue(we);break}default:{const wt=__;throw new Error(`Unknown chunk type: ${wt}`)}}},async flush(we){const lt=Oi.length>0?JSON.stringify(Oi):void 0;try{Ar.setAttributes(Dt({telemetry:e,attributes:{"ai.response.finishReason":us,"ai.response.text":{output:()=>v_},"ai.response.toolCalls":{output:()=>lt},"ai.response.id":_r.id,"ai.response.model":_r.modelId,"ai.response.timestamp":_r.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ed),"ai.usage.inputTokens":rr.inputTokens,"ai.usage.outputTokens":rr.outputTokens,"ai.usage.totalTokens":rr.totalTokens,"ai.usage.reasoningTokens":rr.reasoningTokens,"ai.usage.cachedInputTokens":rr.cachedInputTokens,"gen_ai.response.finish_reasons":[us],"gen_ai.response.id":_r.id,"gen_ai.response.model":_r.modelId,"gen_ai.usage.input_tokens":rr.inputTokens,"gen_ai.usage.output_tokens":rr.outputTokens}}))}catch{}finally{Ar.end()}we.enqueue({type:"finish-step",finishReason:us,usage:rr,providerMetadata:ed,response:{..._r,headers:nt?.headers}});const So=Jg(He,rr);await U.promise;const To=Oi.filter(Mr=>Mr.providerExecuted!==!0),Ai=Yu.filter(Mr=>Mr.providerExecuted!==!0);if(To.length>0&&Ai.length===To.length&&!await tv({stopConditions:f,steps:H})){he.push(...Mu({content:H[H.length-1].content,tools:c}));try{await X({currentStep:ue+1,responseMessages:he,usage:So})}catch(Mr){we.enqueue({type:"error",error:Mr}),G.closeStream()}}else we.enqueue({type:"finish",finishReason:us,totalUsage:So}),G.closeStream()}})))}await X({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(K=>{G.addStream(new ReadableStream({start(X){X.enqueue({type:"error",error:K}),X.close()}})),G.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return wi(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return wi(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await r7({stream:this.fullStream,onError:t?.onError})}catch(r){(e=t?.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new tg;return wi(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s=!0,sendSources:o=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=Kn}={}){const c=e!=null?W8({originalMessages:t,responseMessageId:e}):void 0,u={},p=d=>{var f,w;const m=u[d];return((w=(f=this.tools)==null?void 0:f[m])==null?void 0:w.type)==="dynamic"?!0:void 0},h=this.fullStream.pipeThrough(new TransformStream({transform:async(d,f)=>{const w=n?.({part:d}),m=d.type;switch(m){case"text-start":{f.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{s&&f.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{o&&d.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),o&&d.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const y=p(d.id);f.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const y=p(d.toolCallId);d.invalid?f.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(d.error)}):f.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-result":{const y=p(d.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=p(d.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...y!=null?{dynamic:y}:{}});break}case"error":{f.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...w!=null?{messageMetadata:w}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",finishReason:d.finishReason,...w!=null?{messageMetadata:w}:{}});break}case"abort":{f.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const y=m;throw new Error(`Unknown chunk type: ${y}`)}}w!=null&&m!=="start"&&m!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:w})}}));return wi(e7({stream:h,messageId:c??e?.(),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){t7({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:n,messageMetadata:s,sendReasoning:o,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(t,e){J8({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:l,...c}={}){return G8({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(t){return B8({textStream:this.textStream,...t})}};ao({prefix:"aiobj",size:24}),ao({prefix:"aiobj",size:24});var c7={};QC(c7,{object:()=>d7,text:()=>u7});var u7=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),d7=({schema:t})=>{const e=pi(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const n=await cv(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:r},n){const s=await wn({text:r});if(!s.success)throw new hg({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});const o=await Kt({value:s.value,schema:e});if(!o.success)throw new hg({message:"No object generated: response did not match schema.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value}}},p7="AI_MCPClientError",pv=`vercel.ai.error.${p7}`,f7=Symbol.for(pv),fv,hv,De=class extends(hv=ve,fv=f7,hv){constructor({name:t="MCPClientError",message:e,cause:r,data:n,code:s}){super({name:t,message:e,cause:r}),this[fv]=!0,this.data=n,this.code=s}static isInstance(t){return ve.hasMarker(t,pv)}},ss="2025-06-18",h7=[ss,"2025-03-26","2024-11-05"],m7=Ye({name:v(),version:v()}),bi=Ye({_meta:Q(C({}).loose())}),Ir=bi,mv=C({method:v(),params:Q(bi)}),gv=C({applyDefaults:Q(ge())}).loose(),g7=Ye({experimental:Q(C({}).loose()),logging:Q(C({}).loose()),prompts:Q(Ye({listChanged:Q(ge())})),resources:Q(Ye({subscribe:Q(ge()),listChanged:Q(ge())})),tools:Q(Ye({listChanged:Q(ge())})),elicitation:Q(gv)});C({elicitation:Q(gv)}).loose();var v7=Ir.extend({protocolVersion:v(),capabilities:g7,serverInfo:m7,instructions:Q(v())}),ju=Ir.extend({nextCursor:Q(v())}),_7=C({name:v(),description:Q(v()),inputSchema:C({type:j("object"),properties:Q(C({}).loose())}).loose()}).loose(),y7=ju.extend({tools:N(_7)}),vv=C({type:j("text"),text:v()}).loose(),_v=C({type:j("image"),data:Nf(),mimeType:v()}).loose(),w7=C({uri:v(),name:v(),title:Q(v()),description:Q(v()),mimeType:Q(v()),size:Q(L())}).loose(),b7=ju.extend({resources:N(w7)}),yv=C({uri:v(),name:Q(v()),title:Q(v()),mimeType:Q(v())}).loose(),wv=yv.extend({text:v()}),bv=yv.extend({blob:Nf()}),kv=C({type:j("resource"),resource:ce([wv,bv])}).loose(),k7=Ir.extend({content:N(ce([vv,_v,kv])),isError:ge().default(!1).optional()}).or(Ir.extend({toolResult:Le()})),S7=C({uriTemplate:v(),name:v(),title:Q(v()),description:Q(v()),mimeType:Q(v())}).loose(),T7=Ir.extend({resourceTemplates:N(S7)}),C7=Ir.extend({contents:N(ce([wv,bv]))}),$7=C({name:v(),description:Q(v()),required:Q(ge())}).loose(),E7=C({name:v(),title:Q(v()),description:Q(v()),arguments:Q(N($7))}).loose(),x7=ju.extend({prompts:N(E7)}),I7=C({role:ce([j("user"),j("assistant")]),content:ce([vv,_v,kv])}).loose(),R7=Ir.extend({description:Q(v()),messages:N(I7)}),P7=bi.extend({message:v(),requestedSchema:Le()}),Sv=mv.extend({method:j("elicitation/create"),params:P7}),O7=Ir.extend({action:ce([j("accept"),j("decline"),j("cancel")]),content:Q(Se(v(),Le()))}),ki="2.0",A7=C({jsonrpc:j(ki),id:ce([v(),L().int()])}).merge(mv).strict(),M7=C({jsonrpc:j(ki),id:ce([v(),L().int()]),result:Ir}).strict(),N7=C({jsonrpc:j(ki),id:ce([v(),L().int()]),error:C({code:L().int(),message:v(),data:Q(Le())})}).strict(),L7=C({jsonrpc:j(ki)}).merge(C({method:v(),params:Q(bi)})).strict(),yo=ce([A7,L7,M7,N7]),Tv=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",Cv=C({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:L().optional(),scope:v().optional(),refresh_token:v().optional()}).strip(),$t=v().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Bf.custom,message:"URL must be parseable",fatal:!0}),Fp}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),j7=C({resource:v().url(),authorization_servers:N($t).optional(),jwks_uri:v().url().optional(),scopes_supported:N(v()).optional(),bearer_methods_supported:N(v()).optional(),resource_signing_alg_values_supported:N(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:ge().optional(),authorization_details_types_supported:N(v()).optional(),dpop_signing_alg_values_supported:N(v()).optional(),dpop_bound_access_tokens_required:ge().optional()}).passthrough(),$v=C({issuer:v(),authorization_endpoint:$t,token_endpoint:$t,registration_endpoint:$t.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),grant_types_supported:N(v()).optional(),code_challenge_methods_supported:N(v()),token_endpoint_auth_methods_supported:N(v()).optional(),token_endpoint_auth_signing_alg_values_supported:N(v()).optional()}).passthrough(),q7=C({issuer:v(),authorization_endpoint:$t,token_endpoint:$t,userinfo_endpoint:$t.optional(),jwks_uri:$t,registration_endpoint:$t.optional(),scopes_supported:N(v()).optional(),response_types_supported:N(v()),grant_types_supported:N(v()).optional(),subject_types_supported:N(v()),id_token_signing_alg_values_supported:N(v()),claims_supported:N(v()).optional(),token_endpoint_auth_methods_supported:N(v()).optional()}).passthrough(),z7=q7.merge($v.pick({code_challenge_methods_supported:!0})),D7=C({client_id:v(),client_secret:v().optional(),client_id_issued_at:L().optional(),client_secret_expires_at:L().optional()}).strip(),U7=C({redirect_uris:N($t),token_endpoint_auth_method:v().optional(),grant_types:N(v()).optional(),response_types:N(v()).optional(),client_name:v().optional(),client_uri:$t.optional(),logo_uri:$t.optional(),scope:v().optional(),contacts:N(v()).optional(),tos_uri:$t.optional(),policy_uri:v().optional(),jwks_uri:$t.optional(),jwks:ht().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),Z7=C({error:v(),error_description:v().optional(),error_uri:v().optional()}),F7=U7.merge(D7),V7="AI_MCPClientOAuthError",Ev=`vercel.ai.error.${V7}`,H7=Symbol.for(Ev),xv,Iv,wo=class extends(Iv=ve,xv=H7,Iv){constructor({name:t="MCPClientOAuthError",message:e,cause:r}){super({name:t,message:e,cause:r}),this[xv]=!0}static isInstance(t){return ve.hasMarker(t,Ev)}},os=class extends wo{};os.errorCode="server_error";var Si=class extends wo{};Si.errorCode="invalid_client";var Ti=class extends wo{};Ti.errorCode="invalid_grant";var Ci=class extends wo{};Ci.errorCode="unauthorized_client";var B7={[os.errorCode]:os,[Si.errorCode]:Si,[Ti.errorCode]:Ti,[Ci.errorCode]:Ci};function J7(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function G7({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return s.startsWith(o)}var $i=class extends Error{constructor(t="Unauthorized"){super(t),this.name="UnauthorizedError"}};function Ei(t){var e;const r=(e=t.headers.get("www-authenticate"))!=null?e:t.headers.get("WWW-Authenticate");if(!r)return;const[n,s]=r.split(" ");if(n.toLowerCase()!=="bearer"||!s)return;const o=/resource_metadata="([^"]*)"/,a=r.match(o);if(a)try{return new URL(a[1])}catch{return}}function W7(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function qu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?qu(t,void 0,r):void 0;throw n}}async function Rv(t,e,r=fetch){return await qu(t,{"MCP-Protocol-Version":e},r)}function K7(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Y7(t,e,r,n){var s,o;const a=new URL(t),i=(s=n?.protocolVersion)!=null?s:ss;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=W7(e,a.pathname);l=new URL(u,(o=n?.metadataServerUrl)!=null?o:a),l.search=a.search}let c=await Rv(l,i,r);if(!n?.metadataUrl&&K7(c,a.pathname)){const u=new URL(`/.well-known/${e}`,a);c=await Rv(u,i,r)}return c}async function Q7(t,e,r=fetch){const n=await Y7(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.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 j7.parse(await n.json())}function X7(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function e$(t,{fetchFn:e=fetch,protocolVersion:r=ss}={}){var n;const s={"MCP-Protocol-Version":r},o=X7(t);for(const{url:a,type:i}of o){const l=await qu(a,s,e);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return $v.parse(await l.json());{const c=z7.parse(await l.json());if(!((n=c.code_challenge_methods_supported)!=null&&n.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return c}}}}async function t$(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:s,state:o,resource:a}){const i="code",l="S256";let c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",t);const u=await r0(),p=u.code_verifier,h=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",h),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),o&&c.searchParams.set("state",o),s&&c.searchParams.set("scope",s),s?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:p}}function Pv(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Ov(t,e,r,n){const{client_id:s,client_secret:o}=e;switch(t){case"client_secret_basic":r$(s,o,r);return;case"client_secret_post":n$(s,o,n);return;case"none":s$(s,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function r$(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function n$(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function s$(t,e){e.set("client_id",t)}async function zu(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const n=Z7.parse(JSON.parse(r)),{error:s,error_description:o,error_uri:a}=n,i=B7[s]||os;return new i({message:o||"",cause:a})}catch(n){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new os({message:s})}}async function o$(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:s,redirectUri:o,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",p=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:n,code_verifier:s,redirect_uri:String(o)});if(i)i(h,d,t,e);else{const w=(c=e?.token_endpoint_auth_methods_supported)!=null?c:[],m=Pv(r,w);Ov(m,r,h,d)}a&&d.set("resource",a.href);const f=await(l??fetch)(p,{method:"POST",headers:h,body:d});if(!f.ok)throw await zu(f);return Cv.parse(await f.json())}async function a$(t,{metadata:e,clientInformation:r,refreshToken:n,resource:s,addClientAuthentication:o,fetchFn:a}){var i;const l="refresh_token";let c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),p=new URLSearchParams({grant_type:l,refresh_token:n});if(o)o(u,p,t,e);else{const d=(i=e?.token_endpoint_auth_methods_supported)!=null?i:[],f=Pv(r,d);Ov(f,r,u,p)}s&&p.set("resource",s.href);const h=await(a??fetch)(c,{method:"POST",headers:u,body:p});if(!h.ok)throw await zu(h);return Cv.parse({refresh_token:n,...await h.json()})}async function i$(t,{metadata:e,clientMetadata:r,fetchFn:n}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const o=await(n??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await zu(o);return F7.parse(await o.json())}async function xi(t,e){var r,n;try{return await Du(t,e)}catch(s){if(s instanceof Si||s instanceof Ci)return await((r=t.invalidateCredentials)==null?void 0:r.call(t,"all")),await Du(t,e);if(s instanceof Ti)return await((n=t.invalidateCredentials)==null?void 0:n.call(t,"tokens")),await Du(t,e);throw s}}async function l$(t,e,r){const n=J7(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!G7({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 Du(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:s,fetchFn:o}){let a,i;try{a=await Q7(e,{resourceMetadataUrl:s},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=e);const l=await l$(e,t,a),c=await e$(i,{fetchFn:o});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const w=await i$(i,{metadata:c,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(w),u=w}if(r!==void 0){const w=await t.codeVerifier(),m=await o$(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:w,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(m),"AUTHORIZED"}const p=await t.tokens();if(p?.refresh_token)try{const w=await a$(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof wo)||w instanceof os))throw w}const h=t.state?await t.state():void 0,{authorizationUrl:d,codeVerifier:f}=await t$(i,{metadata:c,clientInformation:u,state:h,redirectUrl:t.redirectUrl,scope:n||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(f),await t.redirectToAuthorization(d),"REDIRECT"}var c$=class{constructor({url:t,headers:e,authProvider:r}){this.connected=!1,this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":ss};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Wr(e,`ai-sdk/${Tv}`,lo())}async start(){return new Promise((t,e)=>{if(this.connected)return t();this.abortController=new AbortController;const r=async(n=!1)=>{var s,o,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(s=this.abortController)==null?void 0:s.signal});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ei(u);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new $i;return(o=this.onerror)==null||o.call(this,w),e(w)}}catch(f){return(a=this.onerror)==null||a.call(this,f),e(f)}return r(!0)}if(!u.ok||!u.body){let f=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(f+=". This server does not support SSE transport. Try using `http` transport instead");const w=new De({message:f});return(i=this.onerror)==null||i.call(this,w),e(w)}const h=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).getReader(),d=async()=>{var f,w,m;try{for(;;){const{done:y,value:_}=await h.read();if(y){if(this.connected)throw this.connected=!1,new De({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:g,data:b}=_;if(g==="endpoint"){if(this.endpoint=new URL(b,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,t()}else if(g==="message")try{const k=yo.parse(JSON.parse(b));(f=this.onmessage)==null||f.call(this,k)}catch(k){const S=new De({message:"MCP SSE Transport Error: Failed to parse message",cause:k});(w=this.onerror)==null||w.call(this,S)}}}catch(y){if(y instanceof Error&&y.name==="AbortError")return;(m=this.onerror)==null||m.call(this,y),e(y)}};this.sseConnection={close:()=>h.cancel()},d()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),e(c)}};r()})}async close(){var t,e,r;this.connected=!1,(t=this.sseConnection)==null||t.close(),(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){if(!this.endpoint||!this.connected)throw new De({message:"MCP SSE Transport Error: Not connected"});const e=this.endpoint,r=async(n=!1)=>{var s,o,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(t),signal:(s=this.abortController)==null?void 0:s.signal},p=await fetch(e,u);if(p.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Ei(p);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const d=new $i;(o=this.onerror)==null||o.call(this,d);return}}catch(h){(a=this.onerror)==null||a.call(this,h);return}return r(!0)}if(!p.ok){const h=await p.text().catch(()=>null),d=new De({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${p.status}): ${h}`});(i=this.onerror)==null||i.call(this,d);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},u$=class{constructor({url:t,headers:e,authProvider:r}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(t),this.headers=e,this.authProvider=r}async commonHeaders(t){const e={...this.headers,...t,"mcp-protocol-version":ss};if(this.sessionId&&(e["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(e.Authorization=`Bearer ${r.access_token}`)}return Wr(e,`ai-sdk/${Tv}`,lo())}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 t,e,r;(t=this.inboundSseConnection)==null||t.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{}(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){const e=async(r=!1)=>{var n,s,o,a,i,l,c;try{const p={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(t),signal:(n=this.abortController)==null?void 0:n.signal},h=await fetch(this.url,p),d=h.headers.get("mcp-session-id");if(d&&(this.sessionId=d),h.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Ei(h);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new $i}catch(m){throw(s=this.onerror)==null||s.call(this,m),m}return e(!0)}if(h.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!h.ok){const m=await h.text().catch(()=>null);let y=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${h.status}): ${m}`;h.status===404&&(y+=". This server does not support HTTP transport. Try using `sse` transport instead");const _=new De({message:y});throw(o=this.onerror)==null||o.call(this,_),_}const f=h.headers.get("content-type")||"";if(f.includes("application/json")){const m=await h.json(),y=Array.isArray(m)?m.map(_=>yo.parse(_)):[yo.parse(m)];for(const _ of y)(a=this.onmessage)==null||a.call(this,_);return}if(f.includes("text/event-stream")){if(!h.body){const g=new De({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,g),g}const y=h.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).getReader();(async()=>{var g,b,k;try{for(;;){const{done:S,value:T}=await y.read();if(S)return;const{event:x,data:I}=T;if(x==="message")try{const A=yo.parse(JSON.parse(I));(g=this.onmessage)==null||g.call(this,A)}catch(A){const P=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:A});(b=this.onerror)==null||b.call(this,P)}}}catch(S){if(S instanceof Error&&S.name==="AbortError")return;(k=this.onerror)==null||k.call(this,S)}})();return}const w=new De({message:`MCP HTTP Transport Error: Unexpected content type: ${f}`});throw(l=this.onerror)==null||l.call(this,w),w}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await e()}getNextReconnectionDelay(t){const{initialReconnectionDelay:e,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(e*Math.pow(r,t),n)}scheduleInboundSseReconnection(){var t;const{maxRetries:e}=this.reconnectionOptions;if(e>0&&this.inboundReconnectAttempts>=e){(t=this.onerror)==null||t.call(this,new De({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${e}) 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(t=!1,e){var r,n,s,o,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});e&&(l["last-event-id"]=e);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&&!t){this.resourceMetadataUrl=Ei(c);try{if(await xi(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const w=new $i;(n=this.onerror)==null||n.call(this,w);return}}catch(f){(s=this.onerror)==null||s.call(this,f);return}return this.openInboundSse(!0,e)}if(c.status===405)return;if(!c.ok||!c.body){const f=new De({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(o=this.onerror)==null||o.call(this,f);return}const h=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).getReader(),d=async()=>{var f,w,m,y;try{for(;;){const{done:_,value:g}=await h.read();if(_)return;const{event:b,data:k,id:S}=g;if(S&&(this.lastInboundEventId=S),b==="message")try{const T=yo.parse(JSON.parse(k));(f=this.onmessage)==null||f.call(this,T)}catch(T){const x=new De({message:"MCP HTTP Transport Error: Failed to parse message",cause:T});(w=this.onerror)==null||w.call(this,x)}}}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;(m=this.onerror)==null||m.call(this,_),(y=this.abortController)!=null&&y.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>h.cancel()},this.inboundReconnectAttempts=0,d()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function d$(t){switch(t.type){case"sse":return new c$(t);case"http":return new u$(t);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 p$(t){return"start"in t&&typeof t.start=="function"&&"send"in t&&typeof t.send=="function"&&"close"in t&&typeof t.close=="function"}var f$="1.0.0";async function h$(t){const e=new m$(t);return await e.init(),e}var m$=class{constructor({transport:t,name:e="ai-sdk-mcp-client",version:r=f$,onUncaughtError:n,capabilities:s}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=s??{},p$(t)?this.transport=t:this.transport=d$(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=o=>this.onError(o),this.transport.onmessage=o=>{if("method"in o){"id"in o?this.onRequestMessage(o):this.onError(new De({message:"Unsupported message type"}));return}this.onResponse(o)},this.clientInfo={name:e,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const t=await this.request({request:{method:"initialize",params:{protocolVersion:ss,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:v7});if(t===void 0)throw new De({message:"Server sent invalid initialize result"});if(!h7.includes(t.protocolVersion))throw new De({message:`Server's protocol version is not supported: ${t.protocolVersion}`});return this.serverCapabilities=t.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(t){throw await this.close(),t}}async close(){var t;this.isClosed||(await((t=this.transport)==null?void 0:t.close()),this.onClose())}assertCapability(t){switch(t){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: ${t}`})}}async request({request:t,resultSchema:e,options:r}){return new Promise((n,s)=>{if(this.isClosed)return s(new De({message:"Attempted to send a request from a closed client"}));this.assertCapability(t.method);const o=r?.signal;o?.throwIfAborted();const a=this.requestMessageId++,i={...t,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(o?.aborted)return s(new De({message:"Request was aborted",cause:o.reason}));if(c instanceof Error)return s(c);try{const u=e.parse(c.result);n(u)}catch(u){const p=new De({message:"Failed to parse server response",cause:u});s(p)}}),this.transport.send(i).catch(c=>{l(),s(c)})})}async listTools({params:t,options:e}={}){try{return this.request({request:{method:"tools/list",params:t},resultSchema:y7,options:e})}catch(r){throw r}}async callTool({name:t,args:e,options:r}){try{return this.request({request:{method:"tools/call",params:{name:t,arguments:e}},resultSchema:k7,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:t,options:e}={}){try{return this.request({request:{method:"resources/list",params:t},resultSchema:b7,options:e})}catch(r){throw r}}async readResourceInternal({uri:t,options:e}){try{return this.request({request:{method:"resources/read",params:{uri:t}},resultSchema:C7,options:e})}catch(r){throw r}}async listResourceTemplatesInternal({options:t}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:T7,options:t})}catch(e){throw e}}async listPromptsInternal({params:t,options:e}={}){try{return this.request({request:{method:"prompts/list",params:t},resultSchema:x7,options:e})}catch(r){throw r}}async getPromptInternal({name:t,args:e,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:t,arguments:e}},resultSchema:R7,options:r})}catch(n){throw n}}async notification(t){const e={...t,jsonrpc:"2.0"};await this.transport.send(e)}async tools({schemas:t="automatic"}={}){var e;const r={};try{const n=await this.listTools();for(const{name:s,description:o,inputSchema:a}of n.tools){if(t!=="automatic"&&!(s in t))continue;const i=this,l=async(u,p)=>{var h;return(h=p?.abortSignal)==null||h.throwIfAborted(),i.callTool({name:s,args:u,options:p})},c=t==="automatic"?Xm({description:o,inputSchema:co({...a,properties:(e=a.properties)!=null?e:{},additionalProperties:!1}),execute:l}):{description:o,inputSchema:t[s].inputSchema,execute:l};r[s]=c}return r}catch(n){throw n}}listResources({params:t,options:e}={}){return this.listResourcesInternal({params:t,options:e})}readResource({uri:t,options:e}){return this.readResourceInternal({uri:t,options:e})}listResourceTemplates({options:t}={}){return this.listResourceTemplatesInternal({options:t})}listPrompts({params:t,options:e}={}){return this.listPromptsInternal({params:t,options:e})}getPrompt({name:t,arguments:e,options:r}){return this.getPromptInternal({name:t,args:e,options:r})}onElicitationRequest(t,e){if(t!==Sv)throw new De({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=e}async onRequestMessage(t){try{if(t.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`Unsupported request method: ${t.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const e=Sv.safeParse({method:t.method,params:t.params});if(!e.success){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32602,message:`Invalid elicitation request: ${e.error.message}`,data:e.error.issues}});return}try{const r=await this.elicitationRequestHandler(e.data),n=O7.parse(r);await this.transport.send({jsonrpc:"2.0",id:t.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(e){this.onError(e)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const t=new De({message:"Connection closed"});for(const e of this.responseHandlers.values())e(t);this.responseHandlers.clear()}onError(t){this.onUncaughtError&&this.onUncaughtError(t)}onResponse(t){const e=Number(t.id),r=this.responseHandlers.get(e);if(r===void 0)throw new De({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(t)}`});this.responseHandlers.delete(e),r("result"in t?t:new De({message:t.error.message,code:t.error.code,data:t.error.data,cause:t.error}))}};function gr(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function bo(t){return Object.fromEntries([...t.headers])}var g$=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=()=>{const o=r.length,a=new Array(e);for(let i=0;i<e;i++)a[i]=r[Math.random()*o|0];return a.join("")};if(t==null)return s;if(r.includes(n))throw new li({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${t}${n}${s()}`},Xt=g$();function Uu(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var v$=["fetch failed","failed to fetch"];function _$({error:t,url:e,requestBodyValues:r}){if(Uu(t))return t;if(t instanceof TypeError&&v$.includes(t.message.toLowerCase())){const n=t.cause;if(n!=null)return new Ve({message:`Cannot connect to API: ${n.message}`,cause:n,url:e,requestBodyValues:r,isRetryable:!0})}return t}function y$(t=globalThis){var e,r,n;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(n=(r=t.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function w$(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((r,n)=>{e[n.toLowerCase()]=r});else{Array.isArray(t)||(t=Object.entries(t));for(const[r,n]of t)n!=null&&(e[r.toLowerCase()]=n)}return e}function Av(t,...e){const r=new Headers(w$(t)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var b$="3.0.19";function k$({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Gr({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Gr({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Gr({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function S$({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function T$(t){var e;const[r,n=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?e:n}var C$=/"__proto__"\s*:/,$$=/"constructor"\s*:/;function Mv(t){const e=JSON.parse(t);return e===null||typeof e!="object"||C$.test(t)===!1&&$$.test(t)===!1?e:E$(e)}function E$(t){let e=[t];for(;e.length;){const r=e;e=[];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 s in n){const o=n[s];o&&typeof o=="object"&&e.push(o)}}}return t}function Zu(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return Mv(t)}try{return Mv(t)}finally{Error.stackTraceLimit=e}}var Ii=Symbol.for("vercel.ai.validator");function x$(t){return{[Ii]:!0,validate:t}}function I$(t){return typeof t=="object"&&t!==null&&Ii in t&&t[Ii]===!0&&"validate"in t}function vt(t){let e;return()=>(e==null&&(e=t()),e)}function R$(t){return I$(t)?t:typeof t=="function"?t():P$(t)}function P$(t){return x$(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new dr({value:e,cause:r.issues})}})}async function Yr({value:t,schema:e}){const r=await Fu({value:t,schema:e});if(!r.success)throw dr.wrap({value:t,cause:r.error});return r.value}async function Fu({value:t,schema:e}){const r=R$(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const n=await r.validate(t);return n.success?{success:!0,value:n.value,rawValue:t}:{success:!1,error:dr.wrap({value:t,cause:n.error}),rawValue:t}}catch(n){return{success:!1,error:dr.wrap({value:t,cause:n}),rawValue:t}}}async function O$({text:t,schema:e}){try{const r=Zu(t);return e==null?r:Yr({value:r,schema:e})}catch(r){throw Jr.isInstance(r)||dr.isInstance(r)?r:new Jr({text:t,cause:r})}}async function Nv({text:t,schema:e}){try{const r=Zu(t);return e==null?{success:!0,value:r,rawValue:r}:await Fu({value:r,schema:e})}catch(r){return{success:!1,error:Jr.isInstance(r)?r:new Jr({text:t,cause:r}),rawValue:void 0}}}function Lv(t){try{return Zu(t),!0}catch{return!1}}function A$({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Bn).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Nv({text:r,schema:e}))}}))}async function Qr({provider:t,providerOptions:e,schema:r}){if(e?.[t]==null)return;const n=await Fu({value:e[t],schema:r});if(!n.success)throw new li({argument:"providerOptions",message:`invalid ${t} provider options`,cause:n.error});return n.value}var M$=()=>globalThis.fetch,Rr=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>jv({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),N$=async({url:t,headers:e,formData:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a})=>jv({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:o,fetch:a}),jv=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:o,fetch:a=M$()})=>{try{const i=await a(t,{method:"POST",headers:Av(e,`ai-sdk/provider-utils/${b$}`,y$()),body:r.content,signal:o}),l=bo(i);if(!i.ok){let c;try{c=await s({response:i,url:t,requestBodyValues:r.values})}catch(u){throw Uu(u)||Ve.isInstance(u)?u:new Ve({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Uu(c)||Ve.isInstance(c))?c:new Ve({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw _$({error:i,url:t,requestBodyValues:r.values})}};function CI(t){return t}function as({id:t,name:e,inputSchema:r,outputSchema:n}){return({execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:t,name:e,args:c,inputSchema:r,outputSchema:n,execute:s,toModelOutput:o,onInputStart:a,onInputDelta:i,onInputAvailable:l})}var L$=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:o})=>{const a=await n.text(),i=bo(n);if(a.trim()==="")return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await O$({text:a,schema:t});return{responseHeaders:i,value:new Ve({message:e(l),url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new Ve({message:n.statusText,url:s,requestBodyValues:o,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Vu=t=>async({response:e})=>{const r=bo(e);if(e.body==null)throw new vm({});return{responseHeaders:r,value:A$({stream:e.body,schema:t})}},is=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),o=await Nv({text:s,schema:t}),a=bo(e);if(!o.success)throw new Ve({message:"Invalid JSON response",cause:o.error,statusCode:e.status,responseHeaders:a,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:a,value:o.value,rawValue:o.rawValue}},j$=()=>async({response:t,url:e,requestBodyValues:r})=>{const n=bo(t);if(!t.body)throw new Ve({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0});try{const s=await t.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(s)}}catch(s){throw new Ve({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:n,responseBody:void 0,cause:s})}};function Ri(t){if(t.type==="object"){t.additionalProperties=!1;const e=t.properties;if(e!=null)for(const r in e)e[r]=Ri(e[r])}return t.type==="array"&&t.items!=null&&(Array.isArray(t.items)?t.items=t.items.map(e=>Ri(e)):t.items=Ri(t.items)),t}var q$=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},z$=Symbol("Let zodToJsonSchema decide on which parser to use"),qv={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"},D$=t=>typeof t=="string"?{...qv,name:t}:{...qv,...t};function Nt(){return{}}function U$(t,e){var r,n,s;const o={type:"array"};return(r=t.type)!=null&&r._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==z.ZodAny&&(o.items=Ue(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(o.minItems=t.minLength.value),t.maxLength&&(o.maxItems=t.maxLength.value),t.exactLength&&(o.minItems=t.exactLength.value,o.maxItems=t.exactLength.value),o}function Z$(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function F$(){return{type:"boolean"}}function zv(t,e){return Ue(t.type._def,e)}var V$=(t,e)=>Ue(t.innerType._def,e);function Dv(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Dv(t,e,s))};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 H$(t)}}var H$=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function B$(t,e){return{...Ue(t.innerType._def,e),default:t.defaultValue()}}function J$(t,e){return e.effectStrategy==="input"?Ue(t.schema._def,e):Nt()}function G$(t){return{type:"string",enum:Array.from(t.values)}}var W$=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function K$(t,e){const r=[Ue(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ue(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=[];return r.forEach(s=>{if(W$(s))n.push(...s.allOf);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...i}=s;o=i}n.push(o)}}),n.length?{allOf:n}:void 0}function Y$(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Hu=void 0,er={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:()=>(Hu===void 0&&(Hu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Hu),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 Uv(t,e){const r={type:"string"};if(t.checks)for(const n of t.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(e.emailStrategy){case"format:email":tr(r,"email",n.message,e);break;case"format:idn-email":tr(r,"idn-email",n.message,e);break;case"pattern:zod":_t(r,er.email,n.message,e);break}break;case"url":tr(r,"uri",n.message,e);break;case"uuid":tr(r,"uuid",n.message,e);break;case"regex":_t(r,n.regex,n.message,e);break;case"cuid":_t(r,er.cuid,n.message,e);break;case"cuid2":_t(r,er.cuid2,n.message,e);break;case"startsWith":_t(r,RegExp(`^${Bu(n.value,e)}`),n.message,e);break;case"endsWith":_t(r,RegExp(`${Bu(n.value,e)}$`),n.message,e);break;case"datetime":tr(r,"date-time",n.message,e);break;case"date":tr(r,"date",n.message,e);break;case"time":tr(r,"time",n.message,e);break;case"duration":tr(r,"duration",n.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{_t(r,RegExp(Bu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&tr(r,"ipv4",n.message,e),n.version!=="v4"&&tr(r,"ipv6",n.message,e);break}case"base64url":_t(r,er.base64url,n.message,e);break;case"jwt":_t(r,er.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&_t(r,er.ipv4Cidr,n.message,e),n.version!=="v4"&&_t(r,er.ipv6Cidr,n.message,e);break}case"emoji":_t(r,er.emoji(),n.message,e);break;case"ulid":{_t(r,er.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{tr(r,"binary",n.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{_t(r,er.base64,n.message,e);break}}break}case"nanoid":_t(r,er.nanoid,n.message,e)}return r}function Bu(t,e){return e.patternStrategy==="escape"?X$(t):t}var Q$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function X$(t){let e="";for(let r=0;r<t.length;r++)Q$.has(t[r])||(e+="\\"),e+=t[r];return e}function tr(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function _t(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Zv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Zv(e,n)}function Zv(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=n.i?t.source.toLowerCase():t.source;let o="",a=!1,i=!1,l=!1;for(let c=0;c<s.length;c++){if(a){o+=s[c],a=!1;continue}if(n.i){if(i){if(s[c].match(/[a-z]/)){l?(o+=s[c],o+=`${s[c-2]}-${s[c]}`.toUpperCase(),l=!1):s[c+1]==="-"&&((r=s[c+2])!=null&&r.match(/[a-z]/))?(o+=s[c],l=!0):o+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){o+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(n.m){if(s[c]==="^"){o+=`(^|(?<=[\r
574
574
  ]))`;continue}else if(s[c]==="$"){o+=`($|(?=[\r
575
575
  ]))`;continue}}if(n.s&&s[c]==="."){o+=i?`${s[c]}\r
576
576
  `:`[${s[c]}\r
577
- ]`;continue}o+=s[c],s[c]==="\\"?a=!0:i&&s[c]==="]"?i=!1:!i&&s[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Fv(t,e){var r,n,s,o,a,i;const l={type:"object",additionalProperties:(r=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=Uv(t.keyType._def,e);return{...l,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=zv(t.keyType._def,e);return{...l,propertyNames:u}}}return l}function eE(t,e){if(e.mapStrategy==="record")return Fv(t,e);const r=Ue(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Nt(),n=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Nt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function tE(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function rE(){return{not:Nt()}}function nE(){return{type:"null"}}var Gu={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sE(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Gu&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Gu[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return oE(t,e)}var oE=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ue(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function aE(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Gu[t.innerType._def.typeName],"null"]};const r=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function iE(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function lE(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const l=uE(i),c=Ue(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const o=cE(t,e);return o!==void 0&&(r.additionalProperties=o),r}function cE(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ue(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function uE(t){try{return t.isOptional()}catch{return!0}}var dE=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ue(t.innerType._def,e);const n=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Nt()},n]}:Nt()},pE=(t,e)=>{if(e.pipeStrategy==="input")return Ue(t.in._def,e);if(e.pipeStrategy==="output")return Ue(t.out._def,e);const r=Ue(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ue(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function fE(t,e){return Ue(t.type._def,e)}function hE(t,e){const n={type:"array",uniqueItems:!0,items:Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function mE(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ue(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function gE(){return{not:Nt()}}function vE(){return Nt()}var _E=(t,e)=>Ue(t.innerType._def,e),yE=(t,e,r)=>{switch(e){case z.ZodString:return Uv(t,r);case z.ZodNumber:return iE(t);case z.ZodObject:return lE(t,r);case z.ZodBigInt:return Z$(t);case z.ZodBoolean:return F$();case z.ZodDate:return Dv(t,r);case z.ZodUndefined:return gE();case z.ZodNull:return nE();case z.ZodArray:return U$(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return sE(t,r);case z.ZodIntersection:return K$(t,r);case z.ZodTuple:return mE(t,r);case z.ZodRecord:return Fv(t,r);case z.ZodLiteral:return Y$(t);case z.ZodEnum:return G$(t);case z.ZodNativeEnum:return tE(t);case z.ZodNullable:return aE(t,r);case z.ZodOptional:return dE(t,r);case z.ZodMap:return eE(t,r);case z.ZodSet:return hE(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return fE(t,r);case z.ZodNaN:case z.ZodNever:return rE();case z.ZodEffects:return J$(t,r);case z.ZodAny:return Nt();case z.ZodUnknown:return vE();case z.ZodDefault:return B$(t,r);case z.ZodBranded:return zv(t,r);case z.ZodReadonly:return _E(t,r);case z.ZodCatch:return V$(t,r);case z.ZodPipeline:return pE(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Ue(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const l=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(l!==z$)return l}if(s&&!r){const l=wE(s,e);if(l!==void 0)return l}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=yE(t,t.typeName,e),i=typeof a=="function"?Ue(a(),e):a;if(i&&bE(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return o.jsonSchema=i,l}return o.jsonSchema=i,i}var wE=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:q$(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Nt()):e.$refStrategy==="seen"?Nt():void 0}},bE=(t,e,r)=>(t.description&&(r.description=t.description),r),kE=t=>{const e=D$(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},SE=(t,e)=>{var r;const n=kE(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,p])=>{var h;return{...c,[u]:(h=Ue(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Nt()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=Ue(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Nt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const l=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},TE=SE;function CE(t,e){var r;const n=(r=void 0)!=null?r:!1;return Vv(()=>TE(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function $E(t,e){var r;const n=(r=void 0)!=null?r:!1;return Vv(()=>Ri(ul(t,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async s=>{const o=await dl(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function EE(t){return"_zod"in t}function Ne(t,e){return EE(t)?$E(t):CE(t)}var xE=Symbol.for("vercel.ai.schema");function dt(t){let e;return()=>(e==null&&(e=t()),e)}function Vv(t,{validate:e}={}){return{[xE]:!0,_type:void 0,[Ii]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}var{btoa:IE,atob:RE}=globalThis;function PE(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=RE(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function OE(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return IE(e)}function ls(t){return t instanceof Uint8Array?OE(t):t}function AE(t){return t?.replace(/\/$/,"")}var Wu=C({error:C({message:v(),type:v().nullish(),param:ht().nullish(),code:ce([v(),L()]).nullish()})}),vr=L$({errorSchema:Wu,errorToMessage:t=>t.error.message});function Hv(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),n=!(t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("chatgpt-4o")||t.startsWith("gpt-5-chat")),s=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:e,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:s}}function ME({prompt:t,systemMessageMode:e="system"}){const r=[],n=[];for(const{role:s,content:o}of t)switch(s){case"system":{switch(e){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=e;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((a,i)=>{var l,c,u;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const 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,${ls(a.data)}`,detail:(c=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Wt({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:ls(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:ls(a.data),format:"mp3"}};default:throw new Wt({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Wt({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(u=a.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${ls(a.data)}`}}}else throw new Wt({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of o)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of o){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:r,warnings:n}}function Ku({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r?new Date(r*1e3):void 0}}function Bv(t){switch(t){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 NE=vt(()=>Ne(C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({message:C({role:j("assistant").nullish(),content:v().nullish(),tool_calls:N(C({id:v().nullish(),type:j("function"),function:C({name:v(),arguments:v()})})).nullish(),annotations:N(C({type:j("url_citation"),url_citation:C({start_index:L(),end_index:L(),url:v(),title:v()})})).nullish()}),index:L(),logprobs:C({content:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:C({prompt_tokens:L().nullish(),completion_tokens:L().nullish(),total_tokens:L().nullish(),prompt_tokens_details:C({cached_tokens:L().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:L().nullish(),accepted_prediction_tokens:L().nullish(),rejected_prediction_tokens:L().nullish()}).nullish()}).nullish()}))),LE=vt(()=>Ne(ce([C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({delta:C({role:Ce(["assistant"]).nullish(),content:v().nullish(),tool_calls:N(C({index:L(),id:v().nullish(),type:j("function").nullish(),function:C({name:v().nullish(),arguments:v().nullish()})})).nullish(),annotations:N(C({type:j("url_citation"),url_citation:C({start_index:L(),end_index:L(),url:v(),title:v()})})).nullish()}).nullish(),logprobs:C({content:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish()}).nullish(),finish_reason:v().nullish(),index:L()})),usage:C({prompt_tokens:L().nullish(),completion_tokens:L().nullish(),total_tokens:L().nullish(),prompt_tokens_details:C({cached_tokens:L().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:L().nullish(),accepted_prediction_tokens:L().nullish(),rejected_prediction_tokens:L().nullish()}).nullish()}).nullish()}),Wu]))),jE=vt(()=>Ne(C({logitBias:Se(Gf(),L()).optional(),logprobs:ce([ge(),L()]).optional(),parallelToolCalls:ge().optional(),user:v().optional(),reasoningEffort:Ce(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:L().optional(),store:ge().optional(),metadata:Se(v().max(64),v().max(512)).optional(),prediction:Se(v(),ht()).optional(),structuredOutputs:ge().optional(),serviceTier:Ce(["auto","flex","priority","default"]).optional(),strictJsonSchema:ge().optional(),textVerbosity:Ce(["low","medium","high"]).optional(),promptCacheKey:v().optional(),promptCacheRetention:Ce(["in_memory","24h"]).optional(),safetyIdentifier:v().optional()})));function qE({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:n}){t=t?.length?t:void 0;const s=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const o=[];for(const i of t)switch(i.type){case"function":o.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?n:void 0}});break;default:s.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:o,toolChoice:void 0,toolWarnings:s};const a=e.type;switch(a){case"auto":case"none":case"required":return{tools:o,toolChoice:a,toolWarnings:s};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:s};default:{const i=a;throw new Wt({functionality:`tool choice type: ${i}`})}}}var zE=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:p,providerOptions:h}){var d,f,w,m;const y=[],_=(d=await Qr({provider:"openai",providerOptions:h,schema:jE}))!=null?d:{},g=(f=_.structuredOutputs)!=null?f:!0,b=Hv(this.modelId);s!=null&&y.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!g&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:k,warnings:S}=ME({prompt:t,systemMessageMode:b.systemMessageMode});y.push(...S);const T=(w=_.strictJsonSchema)!=null?w:!1,x={model:this.modelId,logit_bias:_.logitBias,logprobs:_.logprobs===!0||typeof _.logprobs=="number"?!0:void 0,top_logprobs:typeof _.logprobs=="number"?_.logprobs:typeof _.logprobs=="boolean"&&_.logprobs?0:void 0,user:_.user,parallel_tool_calls:_.parallelToolCalls,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:l?.type==="json"?g&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:T,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:_.textVerbosity,max_completion_tokens:_.maxCompletionTokens,store:_.store,metadata:_.metadata,prediction:_.prediction,reasoning_effort:_.reasoningEffort,service_tier:_.serviceTier,prompt_cache_key:_.promptCacheKey,prompt_cache_retention:_.promptCacheRetention,safety_identifier:_.safetyIdentifier,messages:k};b.isReasoningModel?((_.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,y.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,y.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,y.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,y.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,y.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,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),_.serviceTier==="flex"&&!b.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),_.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:I,toolChoice:A,toolWarnings:P}=qE({tools:u,toolChoice:p,structuredOutputs:g,strictJsonSchema:T});return{args:{...x,tools:I,tool_choice:A},warnings:[...y,...P]}}async doGenerate(t){var e,r,n,s,o,a,i,l,c,u,p,h,d,f;const{args:w,warnings:m}=await this.getArgs(t),{responseHeaders:y,value:_,rawValue:g}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:w,failedResponseHandler:vr,successfulResponseHandler:is(NE),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=_.choices[0],k=[],S=b.message.content;S!=null&&S.length>0&&k.push({type:"text",text:S});for(const A of(e=b.message.tool_calls)!=null?e:[])k.push({type:"tool-call",toolCallId:(r=A.id)!=null?r:Xt(),toolName:A.function.name,input:A.function.arguments});for(const A of(n=b.message.annotations)!=null?n:[])k.push({type:"source",sourceType:"url",id:Xt(),url:A.url_citation.url,title:A.url_citation.title});const T=(s=_.usage)==null?void 0:s.completion_tokens_details,x=(o=_.usage)==null?void 0:o.prompt_tokens_details,I={openai:{}};return T?.accepted_prediction_tokens!=null&&(I.openai.acceptedPredictionTokens=T?.accepted_prediction_tokens),T?.rejected_prediction_tokens!=null&&(I.openai.rejectedPredictionTokens=T?.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(I.openai.logprobs=b.logprobs.content),{content:k,finishReason:Bv(b.finish_reason),usage:{inputTokens:(l=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=_.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(h=(p=_.usage)==null?void 0:p.total_tokens)!=null?h:void 0,reasoningTokens:(d=T?.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(f=x?.cached_tokens)!=null?f:void 0},request:{body:w},response:{...Ku(_),headers:y,body:g},warnings:m,providerMetadata:I}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:n,failedResponseHandler:vr,successfulResponseHandler:Hu(LE),abortSignal:t.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,u=!1;const p={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:r})},transform(h,d){var f,w,m,y,_,g,b,k,S,T,x,I,A,P,D,U,V,se,fe,de,re,_e,H,O;if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){i="error",d.enqueue({type:"error",error:h.error});return}const F=h.value;if("error"in F){i="error",d.enqueue({type:"error",error:F.error});return}if(!c){const R=Ku(F);Object.values(R).some(Boolean)&&(c=!0,d.enqueue({type:"response-metadata",...Ku(F)}))}F.usage!=null&&(l.inputTokens=(f=F.usage.prompt_tokens)!=null?f:void 0,l.outputTokens=(w=F.usage.completion_tokens)!=null?w:void 0,l.totalTokens=(m=F.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(_=(y=F.usage.completion_tokens_details)==null?void 0:y.reasoning_tokens)!=null?_:void 0,l.cachedInputTokens=(b=(g=F.usage.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?b:void 0,((k=F.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(p.openai.acceptedPredictionTokens=(S=F.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((T=F.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(p.openai.rejectedPredictionTokens=(x=F.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens));const q=F.choices[0];if(q?.finish_reason!=null&&(i=Bv(q.finish_reason)),((I=q?.logprobs)==null?void 0:I.content)!=null&&(p.openai.logprobs=q.logprobs.content),q?.delta==null)return;const E=q.delta;if(E.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:E.content})),E.tool_calls!=null)for(const R of E.tool_calls){const $=R.index;if(a[$]==null){if(R.type!=="function")throw new so({data:R,message:"Expected 'function' type."});if(R.id==null)throw new so({data:R,message:"Expected 'id' to be a string."});if(((A=R.function)==null?void 0:A.name)==null)throw new so({data:R,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:R.id,toolName:R.function.name}),a[$]={id:R.id,type:"function",function:{name:R.function.name,arguments:(P=R.function.arguments)!=null?P:""},hasFinished:!1};const W=a[$];((D=W.function)==null?void 0:D.name)!=null&&((U=W.function)==null?void 0:U.arguments)!=null&&(W.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:W.id,delta:W.function.arguments}),Lv(W.function.arguments)&&(d.enqueue({type:"tool-input-end",id:W.id}),d.enqueue({type:"tool-call",toolCallId:(V=W.id)!=null?V:Xt(),toolName:W.function.name,input:W.function.arguments}),W.hasFinished=!0));continue}const B=a[$];B.hasFinished||(((se=R.function)==null?void 0:se.arguments)!=null&&(B.function.arguments+=(de=(fe=R.function)==null?void 0:fe.arguments)!=null?de:""),d.enqueue({type:"tool-input-delta",id:B.id,delta:(re=R.function.arguments)!=null?re:""}),((_e=B.function)==null?void 0:_e.name)!=null&&((H=B.function)==null?void 0:H.arguments)!=null&&Lv(B.function.arguments)&&(d.enqueue({type:"tool-input-end",id:B.id}),d.enqueue({type:"tool-call",toolCallId:(O=B.id)!=null?O:Xt(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}if(E.annotations!=null)for(const R of E.annotations)d.enqueue({type:"source",sourceType:"url",id:Xt(),url:R.url_citation.url,title:R.url_citation.title})},flush(h){u&&h.enqueue({type:"text-end",id:"0"}),h.enqueue({type:"finish",finishReason:i,usage:l,...p!=null?{providerMetadata:p}:{}})}})),request:{body:n},response:{headers:s}}}};function DE({prompt:t,user:e="user",assistant:r="assistant"}){let n="";t[0].role==="system"&&(n+=`${t[0].content}
577
+ ]`;continue}o+=s[c],s[c]==="\\"?a=!0:i&&s[c]==="]"?i=!1:!i&&s[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Fv(t,e){var r,n,s,o,a,i;const l={type:"object",additionalProperties:(r=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((n=t.keyType)==null?void 0:n._def.typeName)===z.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=Uv(t.keyType._def,e);return{...l,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===z.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=zv(t.keyType._def,e);return{...l,propertyNames:u}}}return l}function eE(t,e){if(e.mapStrategy==="record")return Fv(t,e);const r=Ue(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Nt(),n=Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Nt();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function tE(t){const e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function rE(){return{not:Nt()}}function nE(){return{type:"null"}}var Ju={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sE(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ju&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,o)=>{const a=Ju[o._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...s,a];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((o,a,i)=>i.indexOf(o)===a);return{type:s.length>1?s:s[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return oE(t,e)}var oE=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Ue(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function aE(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ju[t.innerType._def.typeName],"null"]};const r=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function iE(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function lE(t,e){const r={type:"object",properties:{}},n=[],s=t.shape();for(const a in s){let i=s[a];if(i===void 0||i._def===void 0)continue;const l=uE(i),c=Ue(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const o=cE(t,e);return o!==void 0&&(r.additionalProperties=o),r}function cE(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ue(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function uE(t){try{return t.isOptional()}catch{return!0}}var dE=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ue(t.innerType._def,e);const n=Ue(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Nt()},n]}:Nt()},pE=(t,e)=>{if(e.pipeStrategy==="input")return Ue(t.in._def,e);if(e.pipeStrategy==="output")return Ue(t.out._def,e);const r=Ue(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Ue(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function fE(t,e){return Ue(t.type._def,e)}function hE(t,e){const n={type:"array",uniqueItems:!0,items:Ue(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(n.minItems=t.minSize.value),t.maxSize&&(n.maxItems=t.maxSize.value),n}function mE(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ue(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Ue(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function gE(){return{not:Nt()}}function vE(){return Nt()}var _E=(t,e)=>Ue(t.innerType._def,e),yE=(t,e,r)=>{switch(e){case z.ZodString:return Uv(t,r);case z.ZodNumber:return iE(t);case z.ZodObject:return lE(t,r);case z.ZodBigInt:return Z$(t);case z.ZodBoolean:return F$();case z.ZodDate:return Dv(t,r);case z.ZodUndefined:return gE();case z.ZodNull:return nE();case z.ZodArray:return U$(t,r);case z.ZodUnion:case z.ZodDiscriminatedUnion:return sE(t,r);case z.ZodIntersection:return K$(t,r);case z.ZodTuple:return mE(t,r);case z.ZodRecord:return Fv(t,r);case z.ZodLiteral:return Y$(t);case z.ZodEnum:return G$(t);case z.ZodNativeEnum:return tE(t);case z.ZodNullable:return aE(t,r);case z.ZodOptional:return dE(t,r);case z.ZodMap:return eE(t,r);case z.ZodSet:return hE(t,r);case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return fE(t,r);case z.ZodNaN:case z.ZodNever:return rE();case z.ZodEffects:return J$(t,r);case z.ZodAny:return Nt();case z.ZodUnknown:return vE();case z.ZodDefault:return B$(t,r);case z.ZodBranded:return zv(t,r);case z.ZodReadonly:return _E(t,r);case z.ZodCatch:return V$(t,r);case z.ZodPipeline:return pE(t,r);case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:return;default:return(n=>{})()}};function Ue(t,e,r=!1){var n;const s=e.seen.get(t);if(e.override){const l=(n=e.override)==null?void 0:n.call(e,t,e,s,r);if(l!==z$)return l}if(s&&!r){const l=wE(s,e);if(l!==void 0)return l}const o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);const a=yE(t,t.typeName,e),i=typeof a=="function"?Ue(a(),e):a;if(i&&bE(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return o.jsonSchema=i,l}return o.jsonSchema=i,i}var wE=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:q$(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Nt()):e.$refStrategy==="seen"?Nt():void 0}},bE=(t,e,r)=>(t.description&&(r.description=t.description),r),kE=t=>{const e=D$(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},SE=(t,e)=>{var r;const n=kE(e);let s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,p])=>{var h;return{...c,[u]:(h=Ue(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?h:Nt()}},{}):void 0;const o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(r=Ue(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1))!=null?r:Nt(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const l=o===void 0?s?{...a,[n.definitionPath]:s}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...s,[o]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},TE=SE;function CE(t,e){var r;const n=(r=void 0)!=null?r:!1;return Vv(()=>TE(t,{$refStrategy:n?"root":"none"}),{validate:async s=>{const o=await t.safeParseAsync(s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function $E(t,e){var r;const n=(r=void 0)!=null?r:!1;return Vv(()=>Ri(ul(t,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async s=>{const o=await dl(t,s);return o.success?{success:!0,value:o.data}:{success:!1,error:o.error}}})}function EE(t){return"_zod"in t}function Ne(t,e){return EE(t)?$E(t):CE(t)}var xE=Symbol.for("vercel.ai.schema");function dt(t){let e;return()=>(e==null&&(e=t()),e)}function Vv(t,{validate:e}={}){return{[xE]:!0,_type:void 0,[Ii]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}var{btoa:IE,atob:RE}=globalThis;function PE(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=RE(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function OE(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return IE(e)}function ls(t){return t instanceof Uint8Array?OE(t):t}function AE(t){return t?.replace(/\/$/,"")}var Gu=C({error:C({message:v(),type:v().nullish(),param:ht().nullish(),code:ce([v(),L()]).nullish()})}),vr=L$({errorSchema:Gu,errorToMessage:t=>t.error.message});function Hv(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),n=!(t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("chatgpt-4o")||t.startsWith("gpt-5-chat")),s=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:e,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:s}}function ME({prompt:t,systemMessageMode:e="system"}){const r=[],n=[];for(const{role:s,content:o}of t)switch(s){case"system":{switch(e){case"system":{r.push({role:"system",content:o});break}case"developer":{r.push({role:"developer",content:o});break}case"remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=e;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(o.length===1&&o[0].type==="text"){r.push({role:"user",content:o[0].text});break}r.push({role:"user",content:o.map((a,i)=>{var l,c,u;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const 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,${ls(a.data)}`,detail:(c=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new Wt({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:ls(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:ls(a.data),format:"mp3"}};default:throw new Wt({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new Wt({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(u=a.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${ls(a.data)}`}}}else throw new Wt({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of o)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of o){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return{messages:r,warnings:n}}function Wu({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r?new Date(r*1e3):void 0}}function Bv(t){switch(t){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 NE=vt(()=>Ne(C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({message:C({role:j("assistant").nullish(),content:v().nullish(),tool_calls:N(C({id:v().nullish(),type:j("function"),function:C({name:v(),arguments:v()})})).nullish(),annotations:N(C({type:j("url_citation"),url_citation:C({start_index:L(),end_index:L(),url:v(),title:v()})})).nullish()}),index:L(),logprobs:C({content:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:C({prompt_tokens:L().nullish(),completion_tokens:L().nullish(),total_tokens:L().nullish(),prompt_tokens_details:C({cached_tokens:L().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:L().nullish(),accepted_prediction_tokens:L().nullish(),rejected_prediction_tokens:L().nullish()}).nullish()}).nullish()}))),LE=vt(()=>Ne(ce([C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({delta:C({role:Ce(["assistant"]).nullish(),content:v().nullish(),tool_calls:N(C({index:L(),id:v().nullish(),type:j("function").nullish(),function:C({name:v().nullish(),arguments:v().nullish()})})).nullish(),annotations:N(C({type:j("url_citation"),url_citation:C({start_index:L(),end_index:L(),url:v(),title:v()})})).nullish()}).nullish(),logprobs:C({content:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish()}).nullish(),finish_reason:v().nullish(),index:L()})),usage:C({prompt_tokens:L().nullish(),completion_tokens:L().nullish(),total_tokens:L().nullish(),prompt_tokens_details:C({cached_tokens:L().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:L().nullish(),accepted_prediction_tokens:L().nullish(),rejected_prediction_tokens:L().nullish()}).nullish()}).nullish()}),Gu]))),jE=vt(()=>Ne(C({logitBias:Se(Jf(),L()).optional(),logprobs:ce([ge(),L()]).optional(),parallelToolCalls:ge().optional(),user:v().optional(),reasoningEffort:Ce(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:L().optional(),store:ge().optional(),metadata:Se(v().max(64),v().max(512)).optional(),prediction:Se(v(),ht()).optional(),structuredOutputs:ge().optional(),serviceTier:Ce(["auto","flex","priority","default"]).optional(),strictJsonSchema:ge().optional(),textVerbosity:Ce(["low","medium","high"]).optional(),promptCacheKey:v().optional(),promptCacheRetention:Ce(["in_memory","24h"]).optional(),safetyIdentifier:v().optional()})));function qE({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:n}){t=t?.length?t:void 0;const s=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:s};const o=[];for(const i of t)switch(i.type){case"function":o.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?n:void 0}});break;default:s.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:o,toolChoice:void 0,toolWarnings:s};const a=e.type;switch(a){case"auto":case"none":case"required":return{tools:o,toolChoice:a,toolWarnings:s};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:s};default:{const i=a;throw new Wt({functionality:`tool choice type: ${i}`})}}}var zE=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:p,providerOptions:h}){var d,f,w,m;const y=[],_=(d=await Qr({provider:"openai",providerOptions:h,schema:jE}))!=null?d:{},g=(f=_.structuredOutputs)!=null?f:!0,b=Hv(this.modelId);s!=null&&y.push({type:"unsupported-setting",setting:"topK"}),l?.type==="json"&&l.schema!=null&&!g&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:k,warnings:S}=ME({prompt:t,systemMessageMode:b.systemMessageMode});y.push(...S);const T=(w=_.strictJsonSchema)!=null?w:!1,x={model:this.modelId,logit_bias:_.logitBias,logprobs:_.logprobs===!0||typeof _.logprobs=="number"?!0:void 0,top_logprobs:typeof _.logprobs=="number"?_.logprobs:typeof _.logprobs=="boolean"&&_.logprobs?0:void 0,user:_.user,parallel_tool_calls:_.parallelToolCalls,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:l?.type==="json"?g&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:T,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:_.textVerbosity,max_completion_tokens:_.maxCompletionTokens,store:_.store,metadata:_.metadata,prediction:_.prediction,reasoning_effort:_.reasoningEffort,service_tier:_.serviceTier,prompt_cache_key:_.promptCacheKey,prompt_cache_retention:_.promptCacheRetention,safety_identifier:_.safetyIdentifier,messages:k};b.isReasoningModel?((_.reasoningEffort!=="none"||!b.supportsNonReasoningParameters)&&(x.temperature!=null&&(x.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,y.push({type:"other",message:"logprobs is not supported for reasoning models"}))),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,y.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,y.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,y.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,y.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,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),_.serviceTier==="flex"&&!b.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),x.service_tier=void 0),_.serviceTier==="priority"&&!b.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),x.service_tier=void 0);const{tools:I,toolChoice:A,toolWarnings:P}=qE({tools:u,toolChoice:p,structuredOutputs:g,strictJsonSchema:T});return{args:{...x,tools:I,tool_choice:A},warnings:[...y,...P]}}async doGenerate(t){var e,r,n,s,o,a,i,l,c,u,p,h,d,f;const{args:w,warnings:m}=await this.getArgs(t),{responseHeaders:y,value:_,rawValue:g}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:w,failedResponseHandler:vr,successfulResponseHandler:is(NE),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=_.choices[0],k=[],S=b.message.content;S!=null&&S.length>0&&k.push({type:"text",text:S});for(const A of(e=b.message.tool_calls)!=null?e:[])k.push({type:"tool-call",toolCallId:(r=A.id)!=null?r:Xt(),toolName:A.function.name,input:A.function.arguments});for(const A of(n=b.message.annotations)!=null?n:[])k.push({type:"source",sourceType:"url",id:Xt(),url:A.url_citation.url,title:A.url_citation.title});const T=(s=_.usage)==null?void 0:s.completion_tokens_details,x=(o=_.usage)==null?void 0:o.prompt_tokens_details,I={openai:{}};return T?.accepted_prediction_tokens!=null&&(I.openai.acceptedPredictionTokens=T?.accepted_prediction_tokens),T?.rejected_prediction_tokens!=null&&(I.openai.rejectedPredictionTokens=T?.rejected_prediction_tokens),((a=b.logprobs)==null?void 0:a.content)!=null&&(I.openai.logprobs=b.logprobs.content),{content:k,finishReason:Bv(b.finish_reason),usage:{inputTokens:(l=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=_.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(h=(p=_.usage)==null?void 0:p.total_tokens)!=null?h:void 0,reasoningTokens:(d=T?.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(f=x?.cached_tokens)!=null?f:void 0},request:{body:w},response:{...Wu(_),headers:y,body:g},warnings:m,providerMetadata:I}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:n,failedResponseHandler:vr,successfulResponseHandler:Vu(LE),abortSignal:t.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,u=!1;const p={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:r})},transform(h,d){var f,w,m,y,_,g,b,k,S,T,x,I,A,P,D,U,V,se,fe,de,re,_e,H,O;if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){i="error",d.enqueue({type:"error",error:h.error});return}const F=h.value;if("error"in F){i="error",d.enqueue({type:"error",error:F.error});return}if(!c){const R=Wu(F);Object.values(R).some(Boolean)&&(c=!0,d.enqueue({type:"response-metadata",...Wu(F)}))}F.usage!=null&&(l.inputTokens=(f=F.usage.prompt_tokens)!=null?f:void 0,l.outputTokens=(w=F.usage.completion_tokens)!=null?w:void 0,l.totalTokens=(m=F.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(_=(y=F.usage.completion_tokens_details)==null?void 0:y.reasoning_tokens)!=null?_:void 0,l.cachedInputTokens=(b=(g=F.usage.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?b:void 0,((k=F.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(p.openai.acceptedPredictionTokens=(S=F.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((T=F.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(p.openai.rejectedPredictionTokens=(x=F.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens));const q=F.choices[0];if(q?.finish_reason!=null&&(i=Bv(q.finish_reason)),((I=q?.logprobs)==null?void 0:I.content)!=null&&(p.openai.logprobs=q.logprobs.content),q?.delta==null)return;const E=q.delta;if(E.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:E.content})),E.tool_calls!=null)for(const R of E.tool_calls){const $=R.index;if(a[$]==null){if(R.type!=="function")throw new so({data:R,message:"Expected 'function' type."});if(R.id==null)throw new so({data:R,message:"Expected 'id' to be a string."});if(((A=R.function)==null?void 0:A.name)==null)throw new so({data:R,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:R.id,toolName:R.function.name}),a[$]={id:R.id,type:"function",function:{name:R.function.name,arguments:(P=R.function.arguments)!=null?P:""},hasFinished:!1};const W=a[$];((D=W.function)==null?void 0:D.name)!=null&&((U=W.function)==null?void 0:U.arguments)!=null&&(W.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:W.id,delta:W.function.arguments}),Lv(W.function.arguments)&&(d.enqueue({type:"tool-input-end",id:W.id}),d.enqueue({type:"tool-call",toolCallId:(V=W.id)!=null?V:Xt(),toolName:W.function.name,input:W.function.arguments}),W.hasFinished=!0));continue}const B=a[$];B.hasFinished||(((se=R.function)==null?void 0:se.arguments)!=null&&(B.function.arguments+=(de=(fe=R.function)==null?void 0:fe.arguments)!=null?de:""),d.enqueue({type:"tool-input-delta",id:B.id,delta:(re=R.function.arguments)!=null?re:""}),((_e=B.function)==null?void 0:_e.name)!=null&&((H=B.function)==null?void 0:H.arguments)!=null&&Lv(B.function.arguments)&&(d.enqueue({type:"tool-input-end",id:B.id}),d.enqueue({type:"tool-call",toolCallId:(O=B.id)!=null?O:Xt(),toolName:B.function.name,input:B.function.arguments}),B.hasFinished=!0))}if(E.annotations!=null)for(const R of E.annotations)d.enqueue({type:"source",sourceType:"url",id:Xt(),url:R.url_citation.url,title:R.url_citation.title})},flush(h){u&&h.enqueue({type:"text-end",id:"0"}),h.enqueue({type:"finish",finishReason:i,usage:l,...p!=null?{providerMetadata:p}:{}})}})),request:{body:n},response:{headers:s}}}};function DE({prompt:t,user:e="user",assistant:r="assistant"}){let n="";t[0].role==="system"&&(n+=`${t[0].content}
578
578
 
579
579
  `,t=t.slice(1));for(const{role:s,content:o}of t)switch(s){case"system":throw new _n({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const a=o.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${e}:
580
580
  ${a}
@@ -584,7 +584,7 @@ ${a}
584
584
 
585
585
  `;break}case"tool":throw new Wt({functionality:"tool messages"});default:{const a=s;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
586
586
  `,{prompt:n,stopSequences:[`
587
- ${e}:`]}}function Jv({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Gv(t){switch(t){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 UE=vt(()=>Ne(C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({text:v(),finish_reason:v(),logprobs:C({tokens:N(v()),token_logprobs:N(L()),top_logprobs:N(Se(v(),L())).nullish()}).nullish()})),usage:C({prompt_tokens:L(),completion_tokens:L(),total_tokens:L()}).nullish()}))),ZE=vt(()=>Ne(ce([C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({text:v(),finish_reason:v().nullish(),index:L(),logprobs:C({tokens:N(v()),token_logprobs:N(L()),top_logprobs:N(Se(v(),L())).nullish()}).nullish()})),usage:C({prompt_tokens:L(),completion_tokens:L(),total_tokens:L()}).nullish()}),Wu]))),Wv=vt(()=>Ne(C({echo:ge().optional(),logitBias:Se(v(),L()).optional(),suffix:v().optional(),user:v().optional(),logprobs:ce([ge(),L()]).optional()}))),FE=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:p,providerOptions:h}){const d=[],f={...await Qr({provider:"openai",providerOptions:h,schema:Wv}),...await Qr({provider:this.providerOptionsName,providerOptions:h,schema:Wv})};s!=null&&d.push({type:"unsupported-setting",setting:"topK"}),c?.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:w,stopSequences:m}=DE({prompt:t}),y=[...m??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,seed:p,prompt:w,stop:y.length>0?y:void 0},warnings:d}}async doGenerate(t){var e,r,n;const{args:s,warnings:o}=await this.getArgs(t),{responseHeaders:a,value:i,rawValue:l}=await Rr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:s,failedResponseHandler:vr,successfulResponseHandler:is(UE),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(n=i.usage)==null?void 0:n.total_tokens},finishReason:Gv(c.finish_reason),request:{body:s},response:{...Jv(i),headers:a,body:l},providerMetadata:u,warnings:o}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Rr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:n,failedResponseHandler:vr,successfulResponseHandler:Hu(ZE),abortSignal:t.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:o.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,p){if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",p.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){a="error",p.enqueue({type:"error",error:h.error});return}c&&(c=!1,p.enqueue({type:"response-metadata",...Jv(h)}),p.enqueue({type:"text-start",id:"0"})),h.usage!=null&&(l.inputTokens=h.usage.prompt_tokens,l.outputTokens=h.usage.completion_tokens,l.totalTokens=h.usage.total_tokens);const d=h.choices[0];d?.finish_reason!=null&&(a=Gv(d.finish_reason)),d?.logprobs!=null&&(i.openai.logprobs=d.logprobs),d?.text!=null&&d.text.length>0&&p.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:n},response:{headers:s}}}},VE=vt(()=>Ne(C({dimensions:L().optional(),user:v().optional()}))),HE=vt(()=>Ne(C({data:N(C({embedding:N(L())})),usage:C({prompt_tokens:L()}).nullish()}))),BE=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new J5({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(s=await Qr({provider:"openai",providerOptions:n,schema:VE}))!=null?s:{},{responseHeaders:a,value:i,rawValue:l}=await Rr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:gr(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:vr,successfulResponseHandler:is(HE),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},JE=vt(()=>Ne(C({created:L().nullish(),data:N(C({b64_json:v(),revised_prompt:v().nullish()})),background:v().nullish(),output_format:v().nullish(),size:v().nullish(),quality:v().nullish(),usage:C({input_tokens:L().nullish(),output_tokens:L().nullish(),total_tokens:L().nullish(),input_tokens_details:C({image_tokens:L().nullish(),text_tokens:L().nullish()}).nullish()}).nullish()}))),GE={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},WE=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),KE=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=GE[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var l,c,u,p;const h=[];n!=null&&h.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&h.push({type:"unsupported-setting",setting:"seed"});const d=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:f,responseHeaders:w}=await Rr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:gr(this.config.headers(),a),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=o.openai)!=null?p:{},...WE.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:vr,successfulResponseHandler:is(JE),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(m=>m.b64_json),warnings:h,response:{timestamp:d,modelId:this.modelId,headers:w},providerMetadata:{openai:{images:f.data.map(m=>({...m.revised_prompt?{revisedPrompt:m.revised_prompt}:{},...f.created!=null?{created:f.created}:{},...f.size!=null?{size:f.size}:{},...f.quality!=null?{quality:f.quality}:{},...f.background!=null?{background:f.background}:{},...f.output_format!=null?{outputFormat:f.output_format}:{}}))}}}}},YE=dt(()=>Ne(C({code:v().nullish(),containerId:v()}))),QE=dt(()=>Ne(C({outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullish()}))),XE=dt(()=>Ne(C({container:ce([v(),C({fileIds:N(v()).optional()})]).optional()}))),ex=as({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:YE,outputSchema:QE}),tx=(t={})=>ex(t),Kv=C({key:v(),type:Ce(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ce([v(),L(),ge(),N(v())])}),Yv=C({type:Ce(["and","or"]),filters:N(ce([Kv,Vf(()=>Yv)]))}),rx=dt(()=>Ne(C({vectorStoreIds:N(v()),maxNumResults:L().optional(),ranking:C({ranker:v().optional(),scoreThreshold:L().optional()}).optional(),filters:ce([Kv,Yv]).optional()}))),nx=dt(()=>Ne(C({queries:N(v()),results:N(C({attributes:Se(v(),Le()),fileId:v(),filename:v(),score:L(),text:v()})).nullable()}))),sx=as({id:"openai.file_search",name:"file_search",inputSchema:C({}),outputSchema:nx}),ox=dt(()=>Ne(C({background:Ce(["auto","opaque","transparent"]).optional(),inputFidelity:Ce(["low","high"]).optional(),inputImageMask:C({fileId:v().optional(),imageUrl:v().optional()}).optional(),model:v().optional(),moderation:Ce(["auto"]).optional(),outputCompression:L().int().min(0).max(100).optional(),outputFormat:Ce(["png","jpeg","webp"]).optional(),partialImages:L().int().min(0).max(3).optional(),quality:Ce(["auto","low","medium","high"]).optional(),size:Ce(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),ax=dt(()=>Ne(C({}))),ix=dt(()=>Ne(C({result:v()}))),lx=as({id:"openai.image_generation",name:"image_generation",inputSchema:ax,outputSchema:ix}),cx=(t={})=>lx(t),Qv=dt(()=>Ne(C({action:C({type:j("exec"),command:N(v()),timeoutMs:L().optional(),user:v().optional(),workingDirectory:v().optional(),env:Se(v(),v()).optional()})}))),Xv=dt(()=>Ne(C({output:v()}))),ux=as({id:"openai.local_shell",name:"local_shell",inputSchema:Qv,outputSchema:Xv}),dx=dt(()=>Ne(C({externalWebAccess:ge().optional(),filters:C({allowedDomains:N(v()).optional()}).optional(),searchContextSize:Ce(["low","medium","high"]).optional(),userLocation:C({type:j("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),px=dt(()=>Ne(C({}))),fx=dt(()=>Ne(C({action:et("type",[C({type:j("search"),query:v().optional()}),C({type:j("openPage"),url:v().nullish()}),C({type:j("findInPage"),url:v().nullish(),pattern:v().nullish()})]),sources:N(et("type",[C({type:j("url"),url:v()}),C({type:j("api"),name:v()})])).optional()}))),hx=as({id:"openai.web_search",name:"web_search",inputSchema:px,outputSchema:fx}),mx=(t={})=>hx(t),gx=dt(()=>Ne(C({searchContextSize:Ce(["low","medium","high"]).optional(),userLocation:C({type:j("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),vx=dt(()=>Ne(C({}))),_x=dt(()=>Ne(C({action:et("type",[C({type:j("search"),query:v().optional()}),C({type:j("openPage"),url:v().nullish()}),C({type:j("findInPage"),url:v().nullish(),pattern:v().nullish()})])}))),yx=as({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:vx,outputSchema:_x}),wx={codeInterpreter:tx,fileSearch:sx,imageGeneration:cx,localShell:ux,webSearchPreview:yx,webSearch:mx};function e_(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function bx({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:n,hasLocalShellTool:s=!1}){var o,a,i,l;const c=[],u=[];for(const{role:p,content:h}of t)switch(p){case"system":{switch(e){case"system":{c.push({role:"system",content:h});break}case"developer":{c.push({role:"developer",content:h});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=e;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{c.push({role:"user",content:h.map((d,f)=>{var w,m,y;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const _=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&e_(d.data,r)?{file_id:d.data}:{image_url:`data:${_};base64,${ls(d.data)}`},detail:(m=(w=d.providerOptions)==null?void 0:w.openai)==null?void 0:m.imageDetail}}else{if(d.mediaType==="application/pdf")return d.data instanceof URL?{type:"input_file",file_url:d.data.toString()}:{type:"input_file",...typeof d.data=="string"&&e_(d.data,r)?{file_id:d.data}:{filename:(y=d.filename)!=null?y:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${ls(d.data)}`}};throw new Wt({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},f={};for(const w of h)switch(w.type){case"text":{const m=(a=(o=w.providerOptions)==null?void 0:o.openai)==null?void 0:a.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:w.text}],id:m});break}case"tool-call":{if(f[w.toolCallId]=w,w.providerExecuted)break;const m=(l=(i=w.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}if(s&&w.toolName==="local_shell"){const y=await Yr({value:w.input,schema:Qv});c.push({type:"local_shell_call",call_id:w.toolCallId,id:m,action:{type:"exec",command:y.action.command,timeout_ms:y.action.timeoutMs,user:y.action.user,working_directory:y.action.workingDirectory,env:y.action.env}});break}c.push({type:"function_call",call_id:w.toolCallId,name:w.toolName,arguments:JSON.stringify(w.input),id:m});break}case"tool-result":{n?c.push({type:"item_reference",id:w.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${w.toolName} are not sent to the API when store is false`});break}case"reasoning":{const m=await Qr({provider:"openai",providerOptions:w.providerOptions,schema:kx}),y=m?.itemId;if(y!=null){const _=d[y];if(n)_===void 0&&(c.push({type:"item_reference",id:y}),d[y]={type:"reasoning",id:y,summary:[]});else{const g=[];w.text.length>0?g.push({type:"summary_text",text:w.text}):_!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(w)}.`}),_===void 0?(d[y]={type:"reasoning",id:y,encrypted_content:m?.reasoningEncryptedContent,summary:g},c.push(d[y])):(_.summary.push(...g),m?.reasoningEncryptedContent!=null&&(_.encrypted_content=m.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(w)}.`});break}}break}case"tool":{for(const d of h){const f=d.output;if(s&&d.toolName==="local_shell"&&f.type==="json"){const m=await Yr({value:f.value,schema:Xv});c.push({type:"local_shell_call_output",call_id:d.toolCallId,output:m.output});break}let w;switch(f.type){case"text":case"error-text":w=f.value;break;case"json":case"error-json":w=JSON.stringify(f.value);break;case"content":w=f.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}c.push({type:"function_call_output",call_id:d.toolCallId,output:w})}break}default:{const d=p;throw new Error(`Unsupported role: ${d}`)}}return{input:c,warnings:u}}var kx=C({itemId:v().nullish(),reasoningEncryptedContent:v().nullish()});function t_({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var Sx=vt(()=>Ne(ce([C({type:j("response.output_text.delta"),item_id:v(),delta:v(),logprobs:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish()}),C({type:Ce(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:v()}).nullish(),usage:C({input_tokens:L(),input_tokens_details:C({cached_tokens:L().nullish()}).nullish(),output_tokens:L(),output_tokens_details:C({reasoning_tokens:L().nullish()}).nullish()}),service_tier:v().nullish()})}),C({type:j("response.created"),response:C({id:v(),created_at:L(),model:v(),service_tier:v().nullish()})}),C({type:j("response.output_item.added"),output_index:L(),item:et("type",[C({type:j("message"),id:v()}),C({type:j("reasoning"),id:v(),encrypted_content:v().nullish()}),C({type:j("function_call"),id:v(),call_id:v(),name:v(),arguments:v()}),C({type:j("web_search_call"),id:v(),status:v()}),C({type:j("computer_call"),id:v(),status:v()}),C({type:j("file_search_call"),id:v()}),C({type:j("image_generation_call"),id:v()}),C({type:j("code_interpreter_call"),id:v(),container_id:v(),code:v().nullable(),outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullable(),status:v()})])}),C({type:j("response.output_item.done"),output_index:L(),item:et("type",[C({type:j("message"),id:v()}),C({type:j("reasoning"),id:v(),encrypted_content:v().nullish()}),C({type:j("function_call"),id:v(),call_id:v(),name:v(),arguments:v(),status:j("completed")}),C({type:j("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullable()}),C({type:j("image_generation_call"),id:v(),result:v()}),C({type:j("web_search_call"),id:v(),status:v(),action:et("type",[C({type:j("search"),query:v().nullish(),sources:N(et("type",[C({type:j("url"),url:v()}),C({type:j("api"),name:v()})])).nullish()}),C({type:j("open_page"),url:v().nullish()}),C({type:j("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),C({type:j("file_search_call"),id:v(),queries:N(v()),results:N(C({attributes:Se(v(),Le()),file_id:v(),filename:v(),score:L(),text:v()})).nullish()}),C({type:j("local_shell_call"),id:v(),call_id:v(),action:C({type:j("exec"),command:N(v()),timeout_ms:L().optional(),user:v().optional(),working_directory:v().optional(),env:Se(v(),v()).optional()})}),C({type:j("computer_call"),id:v(),status:j("completed")})])}),C({type:j("response.function_call_arguments.delta"),item_id:v(),output_index:L(),delta:v()}),C({type:j("response.image_generation_call.partial_image"),item_id:v(),output_index:L(),partial_image_b64:v()}),C({type:j("response.code_interpreter_call_code.delta"),item_id:v(),output_index:L(),delta:v()}),C({type:j("response.code_interpreter_call_code.done"),item_id:v(),output_index:L(),code:v()}),C({type:j("response.output_text.annotation.added"),annotation:et("type",[C({type:j("url_citation"),start_index:L(),end_index:L(),url:v(),title:v()}),C({type:j("file_citation"),file_id:v(),filename:v().nullish(),index:L().nullish(),start_index:L().nullish(),end_index:L().nullish(),quote:v().nullish()})])}),C({type:j("response.reasoning_summary_part.added"),item_id:v(),summary_index:L()}),C({type:j("response.reasoning_summary_text.delta"),item_id:v(),summary_index:L(),delta:v()}),C({type:j("response.reasoning_summary_part.done"),item_id:v(),summary_index:L()}),C({type:j("error"),sequence_number:L(),error:C({type:v(),code:v(),message:v(),param:v().nullish()})}),C({type:v()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),Tx=vt(()=>Ne(C({id:v().optional(),created_at:L().optional(),error:C({message:v(),type:v(),param:v().nullish(),code:v()}).nullish(),model:v().optional(),output:N(et("type",[C({type:j("message"),role:j("assistant"),id:v(),content:N(C({type:j("output_text"),text:v(),logprobs:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish(),annotations:N(et("type",[C({type:j("url_citation"),start_index:L(),end_index:L(),url:v(),title:v()}),C({type:j("file_citation"),file_id:v(),filename:v().nullish(),index:L().nullish(),start_index:L().nullish(),end_index:L().nullish(),quote:v().nullish()}),C({type:j("container_file_citation"),container_id:v(),file_id:v(),filename:v().nullish(),start_index:L().nullish(),end_index:L().nullish(),index:L().nullish()}),C({type:j("file_path"),file_id:v(),index:L().nullish()})]))}))}),C({type:j("web_search_call"),id:v(),status:v(),action:et("type",[C({type:j("search"),query:v().nullish(),sources:N(et("type",[C({type:j("url"),url:v()}),C({type:j("api"),name:v()})])).nullish()}),C({type:j("open_page"),url:v().nullish()}),C({type:j("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),C({type:j("file_search_call"),id:v(),queries:N(v()),results:N(C({attributes:Se(v(),ce([v(),L(),ge()])),file_id:v(),filename:v(),score:L(),text:v()})).nullish()}),C({type:j("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullable()}),C({type:j("image_generation_call"),id:v(),result:v()}),C({type:j("local_shell_call"),id:v(),call_id:v(),action:C({type:j("exec"),command:N(v()),timeout_ms:L().optional(),user:v().optional(),working_directory:v().optional(),env:Se(v(),v()).optional()})}),C({type:j("function_call"),call_id:v(),name:v(),arguments:v(),id:v()}),C({type:j("computer_call"),id:v(),status:v().optional()}),C({type:j("reasoning"),id:v(),encrypted_content:v().nullish(),summary:N(C({type:j("summary_text"),text:v()}))})])).optional(),service_tier:v().nullish(),incomplete_details:C({reason:v()}).nullish(),usage:C({input_tokens:L(),input_tokens_details:C({cached_tokens:L().nullish()}).nullish(),output_tokens:L(),output_tokens_details:C({reasoning_tokens:L().nullish()}).nullish()}).optional()}))),r_=20,Cx=vt(()=>Ne(C({conversation:v().nullish(),include:N(Ce(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:v().nullish(),logprobs:ce([ge(),L().min(1).max(r_)]).optional(),maxToolCalls:L().nullish(),metadata:ht().nullish(),parallelToolCalls:ge().nullish(),previousResponseId:v().nullish(),promptCacheKey:v().nullish(),promptCacheRetention:Ce(["in_memory","24h"]).nullish(),reasoningEffort:v().nullish(),reasoningSummary:v().nullish(),safetyIdentifier:v().nullish(),serviceTier:Ce(["auto","flex","priority","default"]).nullish(),store:ge().nullish(),strictJsonSchema:ge().nullish(),textVerbosity:Ce(["low","medium","high"]).nullish(),truncation:Ce(["auto","disabled"]).nullish(),user:v().nullish()})));async function $x({tools:t,toolChoice:e,strictJsonSchema:r}){t=t?.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const a of t)switch(a.type){case"function":s.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await Yr({value:a.args,schema:rx});s.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{s.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await Yr({value:a.args,schema:gx});s.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await Yr({value:a.args,schema:dx});s.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,external_web_access:i.externalWebAccess,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await Yr({value:a.args,schema:XE});s.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await Yr({value:a.args,schema:ox});s.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:n};default:{const a=o;throw new Wt({functionality:`tool choice type: ${a}`})}}}var Ex=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:n,topK:s,presencePenalty:o,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:p,responseFormat:h}){var d,f,w,m;const y=[],_=Hv(this.modelId);s!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),o!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const g=await Qr({provider:"openai",providerOptions:c,schema:Cx});g?.conversation&&g?.previousResponseId&&y.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:k}=await bx({prompt:l,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=g?.store)!=null?d:!0,hasLocalShellTool:I("openai.local_shell")});y.push(...k);const S=(f=g?.strictJsonSchema)!=null?f:!1;let T=g?.include;function x(de){T==null?T=[de]:T.includes(de)||(T=[...T,de])}function I(de){return u?.find(re=>re.type==="provider-defined"&&re.id===de)!=null}const A=typeof g?.logprobs=="number"?g?.logprobs:g?.logprobs===!0?r_:void 0;A&&x("message.output_text.logprobs");const P=(w=u?.find(de=>de.type==="provider-defined"&&(de.id==="openai.web_search"||de.id==="openai.web_search_preview")))==null?void 0:w.name;P&&x("web_search_call.action.sources"),I("openai.code_interpreter")&&x("code_interpreter_call.outputs");const D=g?.store;D===!1&&_.isReasoningModel&&x("reasoning.encrypted_content");const U={model:this.modelId,input:b,temperature:e,top_p:n,max_output_tokens:t,...(h?.type==="json"||g?.textVerbosity)&&{text:{...h?.type==="json"&&{format:h.schema!=null?{type:"json_schema",strict:S,name:(m=h.name)!=null?m:"response",description:h.description,schema:h.schema}:{type:"json_object"}},...g?.textVerbosity&&{verbosity:g.textVerbosity}}},conversation:g?.conversation,max_tool_calls:g?.maxToolCalls,metadata:g?.metadata,parallel_tool_calls:g?.parallelToolCalls,previous_response_id:g?.previousResponseId,store:D,user:g?.user,instructions:g?.instructions,service_tier:g?.serviceTier,include:T,prompt_cache_key:g?.promptCacheKey,prompt_cache_retention:g?.promptCacheRetention,safety_identifier:g?.safetyIdentifier,top_logprobs:A,truncation:g?.truncation,..._.isReasoningModel&&(g?.reasoningEffort!=null||g?.reasoningSummary!=null)&&{reasoning:{...g?.reasoningEffort!=null&&{effort:g.reasoningEffort},...g?.reasoningSummary!=null&&{summary:g.reasoningSummary}}}};_.isReasoningModel?g?.reasoningEffort==="none"&&_.supportsNonReasoningParameters||(U.temperature!=null&&(U.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),U.top_p!=null&&(U.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(g?.reasoningEffort!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),g?.reasoningSummary!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),g?.serviceTier==="flex"&&!_.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete U.service_tier),g?.serviceTier==="priority"&&!_.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete U.service_tier);const{tools:V,toolChoice:se,toolWarnings:fe}=await $x({tools:u,toolChoice:p,strictJsonSchema:S});return{webSearchToolName:P,args:{...U,tools:V,tool_choice:se},warnings:[...y,...fe],store:D}}async doGenerate(t){var e,r,n,s,o,a,i,l,c,u,p,h,d,f,w,m,y,_,g,b,k,S,T,x,I,A,P,D;const{args:U,warnings:V,webSearchToolName:se}=await this.getArgs(t),fe=this.config.url({path:"/responses",modelId:this.modelId}),de=this.config.provider.replace(".responses",""),{responseHeaders:re,value:_e,rawValue:H}=await Rr({url:fe,headers:gr(this.config.headers(),t.headers),body:U,failedResponseHandler:vr,successfulResponseHandler:is(Tx),abortSignal:t.abortSignal,fetch:this.config.fetch});if(_e.error)throw new Ve({message:_e.error.message,url:fe,requestBodyValues:U,statusCode:400,responseHeaders:re,responseBody:H,isRetryable:!1});const O=[],F=[];let q=!1;for(const $ of _e.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const B of $.summary)O.push({type:"reasoning",text:B.text,providerMetadata:{[de]:{itemId:$.id,reasoningEncryptedContent:(e=$.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{O.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[de]:{itemId:$.id}}});break}case"message":{for(const B of $.content){(n=(r=t.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&B.logprobs&&F.push(B.logprobs),O.push({type:"text",text:B.text,providerMetadata:{[de]:{itemId:$.id}}});for(const W of B.annotations)W.type==="url_citation"?O.push({type:"source",sourceType:"url",id:(a=(o=(s=this.config).generateId)==null?void 0:o.call(s))!=null?a:Xt(),url:W.url,title:W.title}):W.type==="file_citation"?O.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:Xt(),mediaType:"text/plain",title:(p=(u=W.quote)!=null?u:W.filename)!=null?p:"Document",filename:(h=W.filename)!=null?h:W.file_id,...W.file_id?{providerMetadata:{[de]:{fileId:W.file_id}}}:{}}):W.type==="container_file_citation"?O.push({type:"source",sourceType:"document",id:(w=(f=(d=this.config).generateId)==null?void 0:f.call(d))!=null?w:Xt(),mediaType:"text/plain",title:(y=(m=W.filename)!=null?m:W.file_id)!=null?y:"Document",filename:(_=W.filename)!=null?_:W.file_id,providerMetadata:{[de]:{fileId:W.file_id,containerId:W.container_id,...W.index!=null?{index:W.index}:{}}}}):W.type==="file_path"&&O.push({type:"source",sourceType:"document",id:(k=(b=(g=this.config).generateId)==null?void 0:b.call(g))!=null?k:Xt(),mediaType:"application/octet-stream",title:W.file_id,filename:W.file_id,providerMetadata:{[de]:{fileId:W.file_id,...W.index!=null?{index:W.index}:{}}}})}break}case"function_call":{q=!0,O.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[de]:{itemId:$.id}}});break}case"web_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:se??"web_search",input:JSON.stringify({}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:se??"web_search",result:s_($.action),providerExecuted:!0});break}case"computer_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(T=(S=$.results)==null?void 0:S.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?T:null},providerExecuted:!0});break}case"code_interpreter_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const E={[de]:{..._e.id!=null?{responseId:_e.id}:{}}};F.length>0&&(E[de].logprobs=F),typeof _e.service_tier=="string"&&(E[de].serviceTier=_e.service_tier);const R=_e.usage;return{content:O,finishReason:t_({finishReason:(x=_e.incomplete_details)==null?void 0:x.reason,hasFunctionCall:q}),usage:{inputTokens:R.input_tokens,outputTokens:R.output_tokens,totalTokens:R.input_tokens+R.output_tokens,reasoningTokens:(A=(I=R.output_tokens_details)==null?void 0:I.reasoning_tokens)!=null?A:void 0,cachedInputTokens:(D=(P=R.input_tokens_details)==null?void 0:P.cached_tokens)!=null?D:void 0},request:{body:U},response:{id:_e.id,timestamp:new Date(_e.created_at*1e3),modelId:_e.model,headers:re,body:H},providerMetadata:E,warnings:V}}async doStream(t){const{args:e,warnings:r,webSearchToolName:n,store:s}=await this.getArgs(t),{responseHeaders:o,value:a}=await Rr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:vr,successfulResponseHandler:Hu(Sx),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this,l=this.config.provider.replace(".responses","");let c="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},p=[];let h=null;const d={},f=[];let w=!1;const m={};let y;return{stream:a.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,g){var b,k,S,T,x,I,A,P,D,U,V,se,fe,de,re,_e,H,O,F,q,E,R;if(t.includeRawChunks&&g.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){c="error",g.enqueue({type:"error",error:_.error});return}const $=_.value;if(n_($))$.item.type==="function_call"?(d[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},g.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(d[$.output_index]={toolName:n??"web_search",toolCallId:$.item.id},g.enqueue({type:"tool-input-start",id:$.item.id,toolName:n??"web_search",providerExecuted:!0}),g.enqueue({type:"tool-input-end",id:$.item.id}),g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(d[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},g.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(d[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},g.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),g.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(f.splice(0,f.length),g.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id}}})):n_($)&&$.item.type==="reasoning"&&(m[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},g.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(Ix($)){if($.item.type==="message")g.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id,...f.length>0&&{annotations:f}}}});else if($.item.type==="function_call")d[$.output_index]=void 0,w=!0,g.enqueue({type:"tool-input-end",id:$.item.call_id}),g.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")d[$.output_index]=void 0,g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:n??"web_search",result:s_($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")d[$.output_index]=void 0,g.enqueue({type:"tool-input-end",id:$.item.id}),g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")d[$.output_index]=void 0,g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(S=(k=$.item.results)==null?void 0:k.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?S:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")d[$.output_index]=void 0,g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")d[$.output_index]=void 0,g.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const B=m[$.item.id],W=Object.entries(B.summaryParts).filter(([ye,pe])=>pe==="active"||pe==="can-conclude").map(([ye])=>ye);for(const ye of W)g.enqueue({type:"reasoning-end",id:`${$.item.id}:${ye}`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(T=$.item.encrypted_content)!=null?T:null}}});delete m[$.item.id]}}else if(Ox($)){const B=d[$.output_index];B!=null&&g.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:$.delta})}else if(Ax($)){const B=d[$.output_index];B!=null&&g.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(Mx($)){const B=d[$.output_index];B!=null&&(g.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}'}),g.enqueue({type:"tool-input-end",id:B.toolCallId}),g.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:B.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Px($))h=$.response.id,g.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(xx($))g.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(I=(x=t.providerOptions)==null?void 0:x.openai)!=null&&I.logprobs&&$.logprobs&&p.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const B=m[$.item_id];B.summaryParts[$.summary_index]="active";for(const W of Object.keys(B.summaryParts))B.summaryParts[W]==="can-conclude"&&(g.enqueue({type:"reasoning-end",id:`${$.item_id}:${W}`,providerMetadata:{[l]:{itemId:$.item_id}}}),B.summaryParts[W]="concluded");g.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id,reasoningEncryptedContent:(P=(A=m[$.item_id])==null?void 0:A.encryptedContent)!=null?P:null}}})}}else $.type==="response.reasoning_summary_text.delta"?g.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[l]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(g.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id}}}),m[$.item_id].summaryParts[$.summary_index]="concluded"):m[$.item_id].summaryParts[$.summary_index]="can-conclude":Rx($)?(c=t_({finishReason:(D=$.response.incomplete_details)==null?void 0:D.reason,hasFunctionCall:w}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(V=(U=$.response.usage.output_tokens_details)==null?void 0:U.reasoning_tokens)!=null?V:void 0,u.cachedInputTokens=(fe=(se=$.response.usage.input_tokens_details)==null?void 0:se.cached_tokens)!=null?fe:void 0,typeof $.response.service_tier=="string"&&(y=$.response.service_tier)):Nx($)?(f.push($.annotation),$.annotation.type==="url_citation"?g.enqueue({type:"source",sourceType:"url",id:(_e=(re=(de=i.config).generateId)==null?void 0:re.call(de))!=null?_e:Xt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&g.enqueue({type:"source",sourceType:"document",id:(F=(O=(H=i.config).generateId)==null?void 0:O.call(H))!=null?F:Xt(),mediaType:"text/plain",title:(E=(q=$.annotation.quote)!=null?q:$.annotation.filename)!=null?E:"Document",filename:(R=$.annotation.filename)!=null?R:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[l]:{fileId:$.annotation.file_id}}}:{}})):Lx($)&&g.enqueue({type:"error",error:$})},flush(_){const g={[l]:{responseId:h}};p.length>0&&(g[l].logprobs=p),y!==void 0&&(g[l].serviceTier=y),_.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:g})}})),request:{body:e},response:{headers:o}}}};function xx(t){return t.type==="response.output_text.delta"}function Ix(t){return t.type==="response.output_item.done"}function Rx(t){return t.type==="response.completed"||t.type==="response.incomplete"}function Px(t){return t.type==="response.created"}function Ox(t){return t.type==="response.function_call_arguments.delta"}function Ax(t){return t.type==="response.code_interpreter_call_code.delta"}function Mx(t){return t.type==="response.code_interpreter_call_code.done"}function n_(t){return t.type==="response.output_item.added"}function Nx(t){return t.type==="response.output_text.annotation.added"}function Lx(t){return t.type==="error"}function s_(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}var jx=vt(()=>Ne(C({instructions:v().nullish(),speed:L().min(.25).max(4).default(1).nullish()}))),qx=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:n,instructions:s,language:o,providerOptions:a}){const i=[],l=await Qr({provider:"openai",providerOptions:a,schema:jx}),c={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:n,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const p in u){const h=u[p];h!==void 0&&(c[p]=h)}}return o&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(t){var e,r,n;const s=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{requestBody:o,warnings:a}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:c}=await Rr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:o,failedResponseHandler:vr,successfulResponseHandler:j$(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(o)},response:{timestamp:s,modelId:this.modelId,headers:l,body:c}}}},zx=vt(()=>Ne(C({text:v(),language:v().nullish(),duration:L().nullish(),words:N(C({word:v(),start:L(),end:L()})).nullish(),segments:N(C({id:L(),seek:L(),start:L(),end:L(),text:v(),tokens:N(L()),temperature:L(),avg_logprob:L(),compression_ratio:L(),no_speech_prob:L()})).nullish()}))),Dx=vt(()=>Ne(C({include:N(v()).optional(),language:v().optional(),prompt:v().optional(),temperature:L().min(0).max(1).default(0).optional(),timestampGranularities:N(Ce(["word","segment"])).default(["segment"]).optional()}))),o_={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"},Ux=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const n=[],s=await Qr({provider:"openai",providerOptions:r,schema:Dx}),o=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([PE(t)]);o.append("model",this.modelId);const i=T$(e);if(o.append("file",new File([a],"audio",{type:e}),`audio.${i}`),s){const l={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const p of u)o.append(`${c}[]`,String(p));else o.append(c,String(u))}return{formData:o,warnings:n}}async doGenerate(t){var e,r,n,s,o,a,i,l;const c=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{formData:u,warnings:p}=await this.getArgs(t),{value:h,responseHeaders:d,rawValue:f}=await N$({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),formData:u,failedResponseHandler:vr,successfulResponseHandler:is(zx),abortSignal:t.abortSignal,fetch:this.config.fetch}),w=h.language!=null&&h.language in o_?o_[h.language]:void 0;return{text:h.text,segments:(i=(a=(s=h.segments)==null?void 0:s.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?a:(o=h.words)==null?void 0:o.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:w,durationInSeconds:(l=h.duration)!=null?l:void 0,warnings:p,response:{timestamp:c,modelId:this.modelId,headers:d,body:f}}}},Zx="2.0.88";function a_(t={}){var e,r;const n=(e=AE(S$({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",s=(r=t.name)!=null?r:"openai",o=()=>Av({Authorization:`Bearer ${k$({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${Zx}`),a=w=>new zE(w,{provider:`${s}.chat`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),i=w=>new FE(w,{provider:`${s}.completion`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),l=w=>new BE(w,{provider:`${s}.embedding`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),c=w=>new KE(w,{provider:`${s}.image`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),u=w=>new Ux(w,{provider:`${s}.transcription`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),p=w=>new qx(w,{provider:`${s}.speech`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),h=w=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(w)},d=w=>new Ex(w,{provider:`${s}.responses`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch,fileIdPrefixes:["file-"]}),f=function(w){return h(w)};return f.languageModel=h,f.chat=a,f.completion=i,f.responses=d,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=u,f.transcriptionModel=u,f.speech=p,f.speechModel=p,f.tools=wx,f}a_();function ko(t){var e,r;return(r=(e=t?.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function Fx(t){const e=[];for(const{role:r,content:n,...s}of t){const o=ko({...s});switch(r){case"system":{e.push({role:"system",content:n,...o});break}case"user":{if(n.length===1&&n[0].type==="text"){e.push({role:"user",content:n[0].text,...ko(n[0])});break}e.push({role:"user",content:n.map(a=>{const i=ko(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${iT(a.data)}`},...i}}else throw new Wt({functionality:`file part media type ${a.mediaType}`})}}),...o});break}case"assistant":{let a="";const i=[];for(const l of n){const c=ko(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}e.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...o});break}case"tool":{for(const a of n){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=ko(a);e.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return e}function i_({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function l_(t){switch(t){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 Yu=C({user:v().optional(),reasoningEffort:v().optional(),textVerbosity:v().optional()}),Vx=C({error:C({message:v(),type:v().nullish(),param:ht().nullish(),code:ce([v(),L()]).nullish()})}),Hx={errorSchema:Vx,errorToMessage:t=>t.error.message};function Bx({tools:t,toolChoice:e}){t=t?.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const o of t)o.type==="provider-defined"?r.push({type:"unsupported-tool",tool:o}):n.push({type:"function",function:{name:o.name,description:o.description,parameters:o.inputSchema}});if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const o=s;throw new Wt({functionality:`tool choice type: ${o}`})}}}var Jx=class{constructor(t,e){this.specificationVersion="v2";var r,n;this.modelId=t,this.config=e;const s=(r=e.errorStructure)!=null?r:Hx;this.chunkSchema=Wx(s.errorSchema),this.failedResponseHandler=bn(s),this.supportsStructuredOutputs=(n=e.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:p,tools:h}){var d,f,w,m;const y=[],_=Object.assign((d=await Qm({provider:"openai-compatible",providerOptions:i,schema:Yu}))!=null?d:{},(f=await Qm({provider:this.providerOptionsName,providerOptions:i,schema:Yu}))!=null?f:{});s!=null&&y.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:g,toolChoice:b,toolWarnings:k}=Bx({tools:h,toolChoice:p});return{args:{model:this.modelId,user:_.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(w=c.name)!=null?w:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((m=i?.[this.providerOptionsName])!=null?m:{}).filter(([S])=>!Object.keys(Yu.shape).includes(S))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:Fx(t),tools:g,tool_choice:b},warnings:[...y,...k]}}async doGenerate(t){var e,r,n,s,o,a,i,l,c,u,p,h,d,f,w,m,y;const{args:_,warnings:g}=await this.getArgs({...t}),b=JSON.stringify(_),{responseHeaders:k,value:S,rawValue:T}=await Xn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Yn(this.config.headers(),t.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:es(Gx),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=S.choices[0],I=[],A=x.message.content;A!=null&&A.length>0&&I.push({type:"text",text:A});const P=(e=x.message.reasoning_content)!=null?e:x.message.reasoning;if(P!=null&&P.length>0&&I.push({type:"reasoning",text:P}),x.message.tool_calls!=null)for(const V of x.message.tool_calls)I.push({type:"tool-call",toolCallId:(r=V.id)!=null?r:io(),toolName:V.function.name,input:V.function.arguments});const D={[this.providerOptionsName]:{},...await((s=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:s.call(n,{parsedBody:T}))},U=(o=S.usage)==null?void 0:o.completion_tokens_details;return U?.accepted_prediction_tokens!=null&&(D[this.providerOptionsName].acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(D[this.providerOptionsName].rejectedPredictionTokens=U?.rejected_prediction_tokens),{content:I,finishReason:l_(x.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=S.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(p=(u=S.usage)==null?void 0:u.total_tokens)!=null?p:void 0,reasoningTokens:(f=(d=(h=S.usage)==null?void 0:h.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(y=(m=(w=S.usage)==null?void 0:w.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?y:void 0},providerMetadata:D,request:{body:b},response:{...i_(S),headers:k,body:T},warnings:g}}async doStream(t){var e;const{args:r,warnings:n}=await this.getArgs({...t}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:a,value:i}=await Xn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Yn(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:e2(this.chunkSchema),abortSignal:t.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 p=!0;const h=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,m){var y,_,g,b,k,S,T,x,I,A,P,D,U;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",m.enqueue({type:"error",error:w.error});return}const V=w.value;if(o?.processChunk(w.rawValue),"error"in V){c="error",m.enqueue({type:"error",error:V.error.message});return}if(p&&(p=!1,m.enqueue({type:"response-metadata",...i_(V)})),V.usage!=null){const{prompt_tokens:re,completion_tokens:_e,total_tokens:H,prompt_tokens_details:O,completion_tokens_details:F}=V.usage;u.promptTokens=re??void 0,u.completionTokens=_e??void 0,u.totalTokens=H??void 0,F?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=F?.reasoning_tokens),F?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=F?.rejected_prediction_tokens),O?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=O?.cached_tokens)}const se=V.choices[0];if(se?.finish_reason!=null&&(c=l_(se.finish_reason)),se?.delta==null)return;const fe=se.delta,de=(y=fe.reasoning_content)!=null?y:fe.reasoning;if(de&&(d||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:de})),fe.content&&(f||(m.enqueue({type:"text-start",id:"txt-0"}),f=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:fe.content})),fe.tool_calls!=null)for(const re of fe.tool_calls){const _e=re.index;if(l[_e]==null){if(re.id==null)throw new so({data:re,message:"Expected 'id' to be a string."});if(((_=re.function)==null?void 0:_.name)==null)throw new so({data:re,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),l[_e]={id:re.id,type:"function",function:{name:re.function.name,arguments:(g=re.function.arguments)!=null?g:""},hasFinished:!1};const O=l[_e];((b=O.function)==null?void 0:b.name)!=null&&((k=O.function)==null?void 0:k.arguments)!=null&&(O.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:O.id,delta:O.function.arguments}),Ym(O.function.arguments)&&(m.enqueue({type:"tool-input-end",id:O.id}),m.enqueue({type:"tool-call",toolCallId:(S=O.id)!=null?S:io(),toolName:O.function.name,input:O.function.arguments}),O.hasFinished=!0));continue}const H=l[_e];H.hasFinished||(((T=re.function)==null?void 0:T.arguments)!=null&&(H.function.arguments+=(I=(x=re.function)==null?void 0:x.arguments)!=null?I:""),m.enqueue({type:"tool-input-delta",id:H.id,delta:(A=re.function.arguments)!=null?A:""}),((P=H.function)==null?void 0:P.name)!=null&&((D=H.function)==null?void 0:D.arguments)!=null&&Ym(H.function.arguments)&&(m.enqueue({type:"tool-input-end",id:H.id}),m.enqueue({type:"tool-call",toolCallId:(U=H.id)!=null?U:io(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(w){var m,y,_,g,b,k;d&&w.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&w.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(x=>!x.hasFinished))w.enqueue({type:"tool-input-end",id:T.id}),w.enqueue({type:"tool-call",toolCallId:(m=T.id)!=null?m:io(),toolName:T.function.name,input:T.function.arguments});const S={[h]:{},...o?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(S[h].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(S[h].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),w.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(y=u.promptTokens)!=null?y:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(g=u.totalTokens)!=null?g:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:S})}})),request:{body:s},response:{headers:a}}}},c_=C({prompt_tokens:L().nullish(),completion_tokens:L().nullish(),total_tokens:L().nullish(),prompt_tokens_details:C({cached_tokens:L().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:L().nullish(),accepted_prediction_tokens:L().nullish(),rejected_prediction_tokens:L().nullish()}).nullish()}).nullish(),Gx=C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({message:C({role:j("assistant").nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:N(C({id:v().nullish(),function:C({name:v(),arguments:v()})})).nullish()}),finish_reason:v().nullish()})),usage:c_}),Wx=t=>ce([C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({delta:C({role:Ce(["assistant"]).nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:N(C({index:L(),id:v().nullish(),function:C({name:v().nullish(),arguments:v().nullish()})})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:c_}),t]);C({echo:ge().optional(),logitBias:Se(v(),L()).optional(),suffix:v().optional(),user:v().optional()});var Kx=C({prompt_tokens:L(),completion_tokens:L(),total_tokens:L()});C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({text:v(),finish_reason:v()})),usage:Kx.nullish()}),C({dimensions:L().optional(),user:v().optional()}),C({data:N(C({embedding:N(L())})),usage:C({prompt_tokens:L()}).nullish(),providerMetadata:Se(v(),Se(v(),ht())).optional()}),C({data:N(C({b64_json:v()}))});var u_=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},Yx={extractMetadata:async({parsedBody:t})=>{const e=await Kt({value:t,schema:Qx});return!e.success||e.value.usage==null?void 0:u_(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,n;const s=await Kt({value:e,schema:Xx});s.success&&((n=(r=s.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&s.value.usage&&(t=s.value.usage)},buildMetadata:()=>u_(t)}}},d_=C({prompt_cache_hit_tokens:L().nullish(),prompt_cache_miss_tokens:L().nullish()}),Qx=C({usage:d_.nullish()}),Xx=C({choices:N(C({finish_reason:v().nullish()})).nullish(),usage:d_.nullish()}),eI="1.0.30";function p_(t={}){var e;const r=i2((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),n=()=>Wr({Authorization:`Bearer ${rS({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${eI}`);class s extends Jx{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const h=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:h}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const o=i=>new s(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:t.fetch,metadataExtractor:Yx}),a=i=>o(i);return a.languageModel=o,a.chat=o,a.textEmbeddingModel=i=>{throw new Lm({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Lm({modelId:i,modelType:"imageModel"})},a}p_();const f_=async t=>{const e={};try{const r=await t.listTools();for(const{name:n,description:s,inputSchema:o}of r.tools){const a=async(i,l)=>t.callTool({name:n,arguments:i},{signal:l?.abortSignal});e[n]=Xm({description:s,inputSchema:co({...o,properties:o.properties??{},additionalProperties:!1}),execute:a})}return e}catch(r){throw r}};function tI(t){const e=Object.entries(t);if(e.length===0)return"";let r=`
587
+ ${e}:`]}}function Jv({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Gv(t){switch(t){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 UE=vt(()=>Ne(C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({text:v(),finish_reason:v(),logprobs:C({tokens:N(v()),token_logprobs:N(L()),top_logprobs:N(Se(v(),L())).nullish()}).nullish()})),usage:C({prompt_tokens:L(),completion_tokens:L(),total_tokens:L()}).nullish()}))),ZE=vt(()=>Ne(ce([C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({text:v(),finish_reason:v().nullish(),index:L(),logprobs:C({tokens:N(v()),token_logprobs:N(L()),top_logprobs:N(Se(v(),L())).nullish()}).nullish()})),usage:C({prompt_tokens:L(),completion_tokens:L(),total_tokens:L()}).nullish()}),Gu]))),Wv=vt(()=>Ne(C({echo:ge().optional(),logitBias:Se(v(),L()).optional(),suffix:v().optional(),user:v().optional(),logprobs:ce([ge(),L()]).optional()}))),FE=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:p,providerOptions:h}){const d=[],f={...await Qr({provider:"openai",providerOptions:h,schema:Wv}),...await Qr({provider:this.providerOptionsName,providerOptions:h,schema:Wv})};s!=null&&d.push({type:"unsupported-setting",setting:"topK"}),c?.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:w,stopSequences:m}=DE({prompt:t}),y=[...m??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:f?.logprobs===!0?0:f?.logprobs===!1?void 0:f?.logprobs,suffix:f.suffix,user:f.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,seed:p,prompt:w,stop:y.length>0?y:void 0},warnings:d}}async doGenerate(t){var e,r,n;const{args:s,warnings:o}=await this.getArgs(t),{responseHeaders:a,value:i,rawValue:l}=await Rr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:s,failedResponseHandler:vr,successfulResponseHandler:is(UE),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(n=i.usage)==null?void 0:n.total_tokens},finishReason:Gv(c.finish_reason),request:{body:s},response:{...Jv(i),headers:a,body:l},providerMetadata:u,warnings:o}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),n={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:o}=await Rr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:n,failedResponseHandler:vr,successfulResponseHandler:Vu(ZE),abortSignal:t.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:o.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,p){if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a="error",p.enqueue({type:"error",error:u.error});return}const h=u.value;if("error"in h){a="error",p.enqueue({type:"error",error:h.error});return}c&&(c=!1,p.enqueue({type:"response-metadata",...Jv(h)}),p.enqueue({type:"text-start",id:"0"})),h.usage!=null&&(l.inputTokens=h.usage.prompt_tokens,l.outputTokens=h.usage.completion_tokens,l.totalTokens=h.usage.total_tokens);const d=h.choices[0];d?.finish_reason!=null&&(a=Gv(d.finish_reason)),d?.logprobs!=null&&(i.openai.logprobs=d.logprobs),d?.text!=null&&d.text.length>0&&p.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:n},response:{headers:s}}}},VE=vt(()=>Ne(C({dimensions:L().optional(),user:v().optional()}))),HE=vt(()=>Ne(C({data:N(C({embedding:N(L())})),usage:C({prompt_tokens:L()}).nullish()}))),BE=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:n}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new J5({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const o=(s=await Qr({provider:"openai",providerOptions:n,schema:VE}))!=null?s:{},{responseHeaders:a,value:i,rawValue:l}=await Rr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:gr(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:vr,successfulResponseHandler:is(HE),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},JE=vt(()=>Ne(C({created:L().nullish(),data:N(C({b64_json:v(),revised_prompt:v().nullish()})),background:v().nullish(),output_format:v().nullish(),size:v().nullish(),quality:v().nullish(),usage:C({input_tokens:L().nullish(),output_tokens:L().nullish(),total_tokens:L().nullish(),input_tokens_details:C({image_tokens:L().nullish(),text_tokens:L().nullish()}).nullish()}).nullish()}))),GE={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},WE=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5"]),KE=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=GE[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:o,headers:a,abortSignal:i}){var l,c,u,p;const h=[];n!=null&&h.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&h.push({type:"unsupported-setting",setting:"seed"});const d=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:f,responseHeaders:w}=await Rr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:gr(this.config.headers(),a),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=o.openai)!=null?p:{},...WE.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:vr,successfulResponseHandler:is(JE),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(m=>m.b64_json),warnings:h,response:{timestamp:d,modelId:this.modelId,headers:w},providerMetadata:{openai:{images:f.data.map(m=>({...m.revised_prompt?{revisedPrompt:m.revised_prompt}:{},...f.created!=null?{created:f.created}:{},...f.size!=null?{size:f.size}:{},...f.quality!=null?{quality:f.quality}:{},...f.background!=null?{background:f.background}:{},...f.output_format!=null?{outputFormat:f.output_format}:{}}))}}}}},YE=dt(()=>Ne(C({code:v().nullish(),containerId:v()}))),QE=dt(()=>Ne(C({outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullish()}))),XE=dt(()=>Ne(C({container:ce([v(),C({fileIds:N(v()).optional()})]).optional()}))),ex=as({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:YE,outputSchema:QE}),tx=(t={})=>ex(t),Kv=C({key:v(),type:Ce(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ce([v(),L(),ge(),N(v())])}),Yv=C({type:Ce(["and","or"]),filters:N(ce([Kv,Ff(()=>Yv)]))}),rx=dt(()=>Ne(C({vectorStoreIds:N(v()),maxNumResults:L().optional(),ranking:C({ranker:v().optional(),scoreThreshold:L().optional()}).optional(),filters:ce([Kv,Yv]).optional()}))),nx=dt(()=>Ne(C({queries:N(v()),results:N(C({attributes:Se(v(),Le()),fileId:v(),filename:v(),score:L(),text:v()})).nullable()}))),sx=as({id:"openai.file_search",name:"file_search",inputSchema:C({}),outputSchema:nx}),ox=dt(()=>Ne(C({background:Ce(["auto","opaque","transparent"]).optional(),inputFidelity:Ce(["low","high"]).optional(),inputImageMask:C({fileId:v().optional(),imageUrl:v().optional()}).optional(),model:v().optional(),moderation:Ce(["auto"]).optional(),outputCompression:L().int().min(0).max(100).optional(),outputFormat:Ce(["png","jpeg","webp"]).optional(),partialImages:L().int().min(0).max(3).optional(),quality:Ce(["auto","low","medium","high"]).optional(),size:Ce(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),ax=dt(()=>Ne(C({}))),ix=dt(()=>Ne(C({result:v()}))),lx=as({id:"openai.image_generation",name:"image_generation",inputSchema:ax,outputSchema:ix}),cx=(t={})=>lx(t),Qv=dt(()=>Ne(C({action:C({type:j("exec"),command:N(v()),timeoutMs:L().optional(),user:v().optional(),workingDirectory:v().optional(),env:Se(v(),v()).optional()})}))),Xv=dt(()=>Ne(C({output:v()}))),ux=as({id:"openai.local_shell",name:"local_shell",inputSchema:Qv,outputSchema:Xv}),dx=dt(()=>Ne(C({externalWebAccess:ge().optional(),filters:C({allowedDomains:N(v()).optional()}).optional(),searchContextSize:Ce(["low","medium","high"]).optional(),userLocation:C({type:j("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),px=dt(()=>Ne(C({}))),fx=dt(()=>Ne(C({action:et("type",[C({type:j("search"),query:v().optional()}),C({type:j("openPage"),url:v().nullish()}),C({type:j("findInPage"),url:v().nullish(),pattern:v().nullish()})]),sources:N(et("type",[C({type:j("url"),url:v()}),C({type:j("api"),name:v()})])).optional()}))),hx=as({id:"openai.web_search",name:"web_search",inputSchema:px,outputSchema:fx}),mx=(t={})=>hx(t),gx=dt(()=>Ne(C({searchContextSize:Ce(["low","medium","high"]).optional(),userLocation:C({type:j("approximate"),country:v().optional(),city:v().optional(),region:v().optional(),timezone:v().optional()}).optional()}))),vx=dt(()=>Ne(C({}))),_x=dt(()=>Ne(C({action:et("type",[C({type:j("search"),query:v().optional()}),C({type:j("openPage"),url:v().nullish()}),C({type:j("findInPage"),url:v().nullish(),pattern:v().nullish()})])}))),yx=as({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:vx,outputSchema:_x}),wx={codeInterpreter:tx,fileSearch:sx,imageGeneration:cx,localShell:ux,webSearchPreview:yx,webSearch:mx};function e_(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function bx({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:n,hasLocalShellTool:s=!1}){var o,a,i,l;const c=[],u=[];for(const{role:p,content:h}of t)switch(p){case"system":{switch(e){case"system":{c.push({role:"system",content:h});break}case"developer":{c.push({role:"developer",content:h});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=e;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{c.push({role:"user",content:h.map((d,f)=>{var w,m,y;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const _=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&e_(d.data,r)?{file_id:d.data}:{image_url:`data:${_};base64,${ls(d.data)}`},detail:(m=(w=d.providerOptions)==null?void 0:w.openai)==null?void 0:m.imageDetail}}else{if(d.mediaType==="application/pdf")return d.data instanceof URL?{type:"input_file",file_url:d.data.toString()}:{type:"input_file",...typeof d.data=="string"&&e_(d.data,r)?{file_id:d.data}:{filename:(y=d.filename)!=null?y:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${ls(d.data)}`}};throw new Wt({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},f={};for(const w of h)switch(w.type){case"text":{const m=(a=(o=w.providerOptions)==null?void 0:o.openai)==null?void 0:a.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:w.text}],id:m});break}case"tool-call":{if(f[w.toolCallId]=w,w.providerExecuted)break;const m=(l=(i=w.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(n&&m!=null){c.push({type:"item_reference",id:m});break}if(s&&w.toolName==="local_shell"){const y=await Yr({value:w.input,schema:Qv});c.push({type:"local_shell_call",call_id:w.toolCallId,id:m,action:{type:"exec",command:y.action.command,timeout_ms:y.action.timeoutMs,user:y.action.user,working_directory:y.action.workingDirectory,env:y.action.env}});break}c.push({type:"function_call",call_id:w.toolCallId,name:w.toolName,arguments:JSON.stringify(w.input),id:m});break}case"tool-result":{n?c.push({type:"item_reference",id:w.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${w.toolName} are not sent to the API when store is false`});break}case"reasoning":{const m=await Qr({provider:"openai",providerOptions:w.providerOptions,schema:kx}),y=m?.itemId;if(y!=null){const _=d[y];if(n)_===void 0&&(c.push({type:"item_reference",id:y}),d[y]={type:"reasoning",id:y,summary:[]});else{const g=[];w.text.length>0?g.push({type:"summary_text",text:w.text}):_!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(w)}.`}),_===void 0?(d[y]={type:"reasoning",id:y,encrypted_content:m?.reasoningEncryptedContent,summary:g},c.push(d[y])):(_.summary.push(...g),m?.reasoningEncryptedContent!=null&&(_.encrypted_content=m.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(w)}.`});break}}break}case"tool":{for(const d of h){const f=d.output;if(s&&d.toolName==="local_shell"&&f.type==="json"){const m=await Yr({value:f.value,schema:Xv});c.push({type:"local_shell_call_output",call_id:d.toolCallId,output:m.output});break}let w;switch(f.type){case"text":case"error-text":w=f.value;break;case"json":case"error-json":w=JSON.stringify(f.value);break;case"content":w=f.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}c.push({type:"function_call_output",call_id:d.toolCallId,output:w})}break}default:{const d=p;throw new Error(`Unsupported role: ${d}`)}}return{input:c,warnings:u}}var kx=C({itemId:v().nullish(),reasoningEncryptedContent:v().nullish()});function t_({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var Sx=vt(()=>Ne(ce([C({type:j("response.output_text.delta"),item_id:v(),delta:v(),logprobs:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish()}),C({type:Ce(["response.completed","response.incomplete"]),response:C({incomplete_details:C({reason:v()}).nullish(),usage:C({input_tokens:L(),input_tokens_details:C({cached_tokens:L().nullish()}).nullish(),output_tokens:L(),output_tokens_details:C({reasoning_tokens:L().nullish()}).nullish()}),service_tier:v().nullish()})}),C({type:j("response.created"),response:C({id:v(),created_at:L(),model:v(),service_tier:v().nullish()})}),C({type:j("response.output_item.added"),output_index:L(),item:et("type",[C({type:j("message"),id:v()}),C({type:j("reasoning"),id:v(),encrypted_content:v().nullish()}),C({type:j("function_call"),id:v(),call_id:v(),name:v(),arguments:v()}),C({type:j("web_search_call"),id:v(),status:v()}),C({type:j("computer_call"),id:v(),status:v()}),C({type:j("file_search_call"),id:v()}),C({type:j("image_generation_call"),id:v()}),C({type:j("code_interpreter_call"),id:v(),container_id:v(),code:v().nullable(),outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullable(),status:v()})])}),C({type:j("response.output_item.done"),output_index:L(),item:et("type",[C({type:j("message"),id:v()}),C({type:j("reasoning"),id:v(),encrypted_content:v().nullish()}),C({type:j("function_call"),id:v(),call_id:v(),name:v(),arguments:v(),status:j("completed")}),C({type:j("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullable()}),C({type:j("image_generation_call"),id:v(),result:v()}),C({type:j("web_search_call"),id:v(),status:v(),action:et("type",[C({type:j("search"),query:v().nullish(),sources:N(et("type",[C({type:j("url"),url:v()}),C({type:j("api"),name:v()})])).nullish()}),C({type:j("open_page"),url:v().nullish()}),C({type:j("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),C({type:j("file_search_call"),id:v(),queries:N(v()),results:N(C({attributes:Se(v(),Le()),file_id:v(),filename:v(),score:L(),text:v()})).nullish()}),C({type:j("local_shell_call"),id:v(),call_id:v(),action:C({type:j("exec"),command:N(v()),timeout_ms:L().optional(),user:v().optional(),working_directory:v().optional(),env:Se(v(),v()).optional()})}),C({type:j("computer_call"),id:v(),status:j("completed")})])}),C({type:j("response.function_call_arguments.delta"),item_id:v(),output_index:L(),delta:v()}),C({type:j("response.image_generation_call.partial_image"),item_id:v(),output_index:L(),partial_image_b64:v()}),C({type:j("response.code_interpreter_call_code.delta"),item_id:v(),output_index:L(),delta:v()}),C({type:j("response.code_interpreter_call_code.done"),item_id:v(),output_index:L(),code:v()}),C({type:j("response.output_text.annotation.added"),annotation:et("type",[C({type:j("url_citation"),start_index:L(),end_index:L(),url:v(),title:v()}),C({type:j("file_citation"),file_id:v(),filename:v().nullish(),index:L().nullish(),start_index:L().nullish(),end_index:L().nullish(),quote:v().nullish()})])}),C({type:j("response.reasoning_summary_part.added"),item_id:v(),summary_index:L()}),C({type:j("response.reasoning_summary_text.delta"),item_id:v(),summary_index:L(),delta:v()}),C({type:j("response.reasoning_summary_part.done"),item_id:v(),summary_index:L()}),C({type:j("error"),sequence_number:L(),error:C({type:v(),code:v(),message:v(),param:v().nullish()})}),C({type:v()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),Tx=vt(()=>Ne(C({id:v().optional(),created_at:L().optional(),error:C({message:v(),type:v(),param:v().nullish(),code:v()}).nullish(),model:v().optional(),output:N(et("type",[C({type:j("message"),role:j("assistant"),id:v(),content:N(C({type:j("output_text"),text:v(),logprobs:N(C({token:v(),logprob:L(),top_logprobs:N(C({token:v(),logprob:L()}))})).nullish(),annotations:N(et("type",[C({type:j("url_citation"),start_index:L(),end_index:L(),url:v(),title:v()}),C({type:j("file_citation"),file_id:v(),filename:v().nullish(),index:L().nullish(),start_index:L().nullish(),end_index:L().nullish(),quote:v().nullish()}),C({type:j("container_file_citation"),container_id:v(),file_id:v(),filename:v().nullish(),start_index:L().nullish(),end_index:L().nullish(),index:L().nullish()}),C({type:j("file_path"),file_id:v(),index:L().nullish()})]))}))}),C({type:j("web_search_call"),id:v(),status:v(),action:et("type",[C({type:j("search"),query:v().nullish(),sources:N(et("type",[C({type:j("url"),url:v()}),C({type:j("api"),name:v()})])).nullish()}),C({type:j("open_page"),url:v().nullish()}),C({type:j("find_in_page"),url:v().nullish(),pattern:v().nullish()})])}),C({type:j("file_search_call"),id:v(),queries:N(v()),results:N(C({attributes:Se(v(),ce([v(),L(),ge()])),file_id:v(),filename:v(),score:L(),text:v()})).nullish()}),C({type:j("code_interpreter_call"),id:v(),code:v().nullable(),container_id:v(),outputs:N(et("type",[C({type:j("logs"),logs:v()}),C({type:j("image"),url:v()})])).nullable()}),C({type:j("image_generation_call"),id:v(),result:v()}),C({type:j("local_shell_call"),id:v(),call_id:v(),action:C({type:j("exec"),command:N(v()),timeout_ms:L().optional(),user:v().optional(),working_directory:v().optional(),env:Se(v(),v()).optional()})}),C({type:j("function_call"),call_id:v(),name:v(),arguments:v(),id:v()}),C({type:j("computer_call"),id:v(),status:v().optional()}),C({type:j("reasoning"),id:v(),encrypted_content:v().nullish(),summary:N(C({type:j("summary_text"),text:v()}))})])).optional(),service_tier:v().nullish(),incomplete_details:C({reason:v()}).nullish(),usage:C({input_tokens:L(),input_tokens_details:C({cached_tokens:L().nullish()}).nullish(),output_tokens:L(),output_tokens_details:C({reasoning_tokens:L().nullish()}).nullish()}).optional()}))),r_=20,Cx=vt(()=>Ne(C({conversation:v().nullish(),include:N(Ce(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:v().nullish(),logprobs:ce([ge(),L().min(1).max(r_)]).optional(),maxToolCalls:L().nullish(),metadata:ht().nullish(),parallelToolCalls:ge().nullish(),previousResponseId:v().nullish(),promptCacheKey:v().nullish(),promptCacheRetention:Ce(["in_memory","24h"]).nullish(),reasoningEffort:v().nullish(),reasoningSummary:v().nullish(),safetyIdentifier:v().nullish(),serviceTier:Ce(["auto","flex","priority","default"]).nullish(),store:ge().nullish(),strictJsonSchema:ge().nullish(),textVerbosity:Ce(["low","medium","high"]).nullish(),truncation:Ce(["auto","disabled"]).nullish(),user:v().nullish()})));async function $x({tools:t,toolChoice:e,strictJsonSchema:r}){t=t?.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const a of t)switch(a.type){case"function":s.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:r});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=await Yr({value:a.args,schema:rx});s.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{s.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await Yr({value:a.args,schema:gx});s.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await Yr({value:a.args,schema:dx});s.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,external_web_access:i.externalWebAccess,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await Yr({value:a.args,schema:XE});s.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await Yr({value:a.args,schema:ox});s.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:n.push({type:"unsupported-tool",tool:a});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:n};default:{const a=o;throw new Wt({functionality:`tool choice type: ${a}`})}}}var Ex=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:n,topK:s,presencePenalty:o,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:p,responseFormat:h}){var d,f,w,m;const y=[],_=Hv(this.modelId);s!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),o!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const g=await Qr({provider:"openai",providerOptions:c,schema:Cx});g?.conversation&&g?.previousResponseId&&y.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:b,warnings:k}=await bx({prompt:l,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=g?.store)!=null?d:!0,hasLocalShellTool:I("openai.local_shell")});y.push(...k);const S=(f=g?.strictJsonSchema)!=null?f:!1;let T=g?.include;function x(de){T==null?T=[de]:T.includes(de)||(T=[...T,de])}function I(de){return u?.find(re=>re.type==="provider-defined"&&re.id===de)!=null}const A=typeof g?.logprobs=="number"?g?.logprobs:g?.logprobs===!0?r_:void 0;A&&x("message.output_text.logprobs");const P=(w=u?.find(de=>de.type==="provider-defined"&&(de.id==="openai.web_search"||de.id==="openai.web_search_preview")))==null?void 0:w.name;P&&x("web_search_call.action.sources"),I("openai.code_interpreter")&&x("code_interpreter_call.outputs");const D=g?.store;D===!1&&_.isReasoningModel&&x("reasoning.encrypted_content");const U={model:this.modelId,input:b,temperature:e,top_p:n,max_output_tokens:t,...(h?.type==="json"||g?.textVerbosity)&&{text:{...h?.type==="json"&&{format:h.schema!=null?{type:"json_schema",strict:S,name:(m=h.name)!=null?m:"response",description:h.description,schema:h.schema}:{type:"json_object"}},...g?.textVerbosity&&{verbosity:g.textVerbosity}}},conversation:g?.conversation,max_tool_calls:g?.maxToolCalls,metadata:g?.metadata,parallel_tool_calls:g?.parallelToolCalls,previous_response_id:g?.previousResponseId,store:D,user:g?.user,instructions:g?.instructions,service_tier:g?.serviceTier,include:T,prompt_cache_key:g?.promptCacheKey,prompt_cache_retention:g?.promptCacheRetention,safety_identifier:g?.safetyIdentifier,top_logprobs:A,truncation:g?.truncation,..._.isReasoningModel&&(g?.reasoningEffort!=null||g?.reasoningSummary!=null)&&{reasoning:{...g?.reasoningEffort!=null&&{effort:g.reasoningEffort},...g?.reasoningSummary!=null&&{summary:g.reasoningSummary}}}};_.isReasoningModel?g?.reasoningEffort==="none"&&_.supportsNonReasoningParameters||(U.temperature!=null&&(U.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),U.top_p!=null&&(U.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(g?.reasoningEffort!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),g?.reasoningSummary!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),g?.serviceTier==="flex"&&!_.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete U.service_tier),g?.serviceTier==="priority"&&!_.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete U.service_tier);const{tools:V,toolChoice:se,toolWarnings:fe}=await $x({tools:u,toolChoice:p,strictJsonSchema:S});return{webSearchToolName:P,args:{...U,tools:V,tool_choice:se},warnings:[...y,...fe],store:D}}async doGenerate(t){var e,r,n,s,o,a,i,l,c,u,p,h,d,f,w,m,y,_,g,b,k,S,T,x,I,A,P,D;const{args:U,warnings:V,webSearchToolName:se}=await this.getArgs(t),fe=this.config.url({path:"/responses",modelId:this.modelId}),de=this.config.provider.replace(".responses",""),{responseHeaders:re,value:_e,rawValue:H}=await Rr({url:fe,headers:gr(this.config.headers(),t.headers),body:U,failedResponseHandler:vr,successfulResponseHandler:is(Tx),abortSignal:t.abortSignal,fetch:this.config.fetch});if(_e.error)throw new Ve({message:_e.error.message,url:fe,requestBodyValues:U,statusCode:400,responseHeaders:re,responseBody:H,isRetryable:!1});const O=[],F=[];let q=!1;for(const $ of _e.output)switch($.type){case"reasoning":{$.summary.length===0&&$.summary.push({type:"summary_text",text:""});for(const B of $.summary)O.push({type:"reasoning",text:B.text,providerMetadata:{[de]:{itemId:$.id,reasoningEncryptedContent:(e=$.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"image_generation",result:{result:$.result},providerExecuted:!0});break}case"local_shell_call":{O.push({type:"tool-call",toolCallId:$.call_id,toolName:"local_shell",input:JSON.stringify({action:$.action}),providerMetadata:{[de]:{itemId:$.id}}});break}case"message":{for(const B of $.content){(n=(r=t.providerOptions)==null?void 0:r.openai)!=null&&n.logprobs&&B.logprobs&&F.push(B.logprobs),O.push({type:"text",text:B.text,providerMetadata:{[de]:{itemId:$.id}}});for(const W of B.annotations)W.type==="url_citation"?O.push({type:"source",sourceType:"url",id:(a=(o=(s=this.config).generateId)==null?void 0:o.call(s))!=null?a:Xt(),url:W.url,title:W.title}):W.type==="file_citation"?O.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:Xt(),mediaType:"text/plain",title:(p=(u=W.quote)!=null?u:W.filename)!=null?p:"Document",filename:(h=W.filename)!=null?h:W.file_id,...W.file_id?{providerMetadata:{[de]:{fileId:W.file_id}}}:{}}):W.type==="container_file_citation"?O.push({type:"source",sourceType:"document",id:(w=(f=(d=this.config).generateId)==null?void 0:f.call(d))!=null?w:Xt(),mediaType:"text/plain",title:(y=(m=W.filename)!=null?m:W.file_id)!=null?y:"Document",filename:(_=W.filename)!=null?_:W.file_id,providerMetadata:{[de]:{fileId:W.file_id,containerId:W.container_id,...W.index!=null?{index:W.index}:{}}}}):W.type==="file_path"&&O.push({type:"source",sourceType:"document",id:(k=(b=(g=this.config).generateId)==null?void 0:b.call(g))!=null?k:Xt(),mediaType:"application/octet-stream",title:W.file_id,filename:W.file_id,providerMetadata:{[de]:{fileId:W.file_id,...W.index!=null?{index:W.index}:{}}}})}break}case"function_call":{q=!0,O.push({type:"tool-call",toolCallId:$.call_id,toolName:$.name,input:$.arguments,providerMetadata:{[de]:{itemId:$.id}}});break}case"web_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:se??"web_search",input:JSON.stringify({}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:se??"web_search",result:s_($.action),providerExecuted:!0});break}case"computer_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"computer_use",input:"",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.status||"completed"},providerExecuted:!0});break}case"file_search_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"file_search",input:"{}",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"file_search",result:{queries:$.queries,results:(T=(S=$.results)==null?void 0:S.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?T:null},providerExecuted:!0});break}case"code_interpreter_call":{O.push({type:"tool-call",toolCallId:$.id,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:$.container_id}),providerExecuted:!0}),O.push({type:"tool-result",toolCallId:$.id,toolName:"code_interpreter",result:{outputs:$.outputs},providerExecuted:!0});break}}const E={[de]:{..._e.id!=null?{responseId:_e.id}:{}}};F.length>0&&(E[de].logprobs=F),typeof _e.service_tier=="string"&&(E[de].serviceTier=_e.service_tier);const R=_e.usage;return{content:O,finishReason:t_({finishReason:(x=_e.incomplete_details)==null?void 0:x.reason,hasFunctionCall:q}),usage:{inputTokens:R.input_tokens,outputTokens:R.output_tokens,totalTokens:R.input_tokens+R.output_tokens,reasoningTokens:(A=(I=R.output_tokens_details)==null?void 0:I.reasoning_tokens)!=null?A:void 0,cachedInputTokens:(D=(P=R.input_tokens_details)==null?void 0:P.cached_tokens)!=null?D:void 0},request:{body:U},response:{id:_e.id,timestamp:new Date(_e.created_at*1e3),modelId:_e.model,headers:re,body:H},providerMetadata:E,warnings:V}}async doStream(t){const{args:e,warnings:r,webSearchToolName:n,store:s}=await this.getArgs(t),{responseHeaders:o,value:a}=await Rr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:vr,successfulResponseHandler:Vu(Sx),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this,l=this.config.provider.replace(".responses","");let c="unknown";const u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},p=[];let h=null;const d={},f=[];let w=!1;const m={};let y;return{stream:a.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:r})},transform(_,g){var b,k,S,T,x,I,A,P,D,U,V,se,fe,de,re,_e,H,O,F,q,E,R;if(t.includeRawChunks&&g.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){c="error",g.enqueue({type:"error",error:_.error});return}const $=_.value;if(n_($))$.item.type==="function_call"?(d[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},g.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name})):$.item.type==="web_search_call"?(d[$.output_index]={toolName:n??"web_search",toolCallId:$.item.id},g.enqueue({type:"tool-input-start",id:$.item.id,toolName:n??"web_search",providerExecuted:!0}),g.enqueue({type:"tool-input-end",id:$.item.id}),g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:n??"web_search",input:JSON.stringify({}),providerExecuted:!0})):$.item.type==="computer_call"?(d[$.output_index]={toolName:"computer_use",toolCallId:$.item.id},g.enqueue({type:"tool-input-start",id:$.item.id,toolName:"computer_use",providerExecuted:!0})):$.item.type==="code_interpreter_call"?(d[$.output_index]={toolName:"code_interpreter",toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},g.enqueue({type:"tool-input-start",id:$.item.id,toolName:"code_interpreter",providerExecuted:!0}),g.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`})):$.item.type==="file_search_call"?g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):$.item.type==="image_generation_call"?g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):$.item.type==="message"?(f.splice(0,f.length),g.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id}}})):n_($)&&$.item.type==="reasoning"&&(m[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},g.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(b=$.item.encrypted_content)!=null?b:null}}}));else if(Ix($)){if($.item.type==="message")g.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[l]:{itemId:$.item.id,...f.length>0&&{annotations:f}}}});else if($.item.type==="function_call")d[$.output_index]=void 0,w=!0,g.enqueue({type:"tool-input-end",id:$.item.call_id}),g.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="web_search_call")d[$.output_index]=void 0,g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:n??"web_search",result:s_($.item.action),providerExecuted:!0});else if($.item.type==="computer_call")d[$.output_index]=void 0,g.enqueue({type:"tool-input-end",id:$.item.id}),g.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:$.item.status||"completed"},providerExecuted:!0});else if($.item.type==="file_search_call")d[$.output_index]=void 0,g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"file_search",result:{queries:$.item.queries,results:(S=(k=$.item.results)==null?void 0:k.map(B=>({attributes:B.attributes,fileId:B.file_id,filename:B.filename,score:B.score,text:B.text})))!=null?S:null},providerExecuted:!0});else if($.item.type==="code_interpreter_call")d[$.output_index]=void 0,g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"code_interpreter",result:{outputs:$.item.outputs},providerExecuted:!0});else if($.item.type==="image_generation_call")g.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:"image_generation",result:{result:$.item.result},providerExecuted:!0});else if($.item.type==="local_shell_call")d[$.output_index]=void 0,g.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[l]:{itemId:$.item.id}}});else if($.item.type==="reasoning"){const B=m[$.item.id],W=Object.entries(B.summaryParts).filter(([ye,pe])=>pe==="active"||pe==="can-conclude").map(([ye])=>ye);for(const ye of W)g.enqueue({type:"reasoning-end",id:`${$.item.id}:${ye}`,providerMetadata:{[l]:{itemId:$.item.id,reasoningEncryptedContent:(T=$.item.encrypted_content)!=null?T:null}}});delete m[$.item.id]}}else if(Ox($)){const B=d[$.output_index];B!=null&&g.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:$.delta})}else if(Ax($)){const B=d[$.output_index];B!=null&&g.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:JSON.stringify($.delta).slice(1,-1)})}else if(Mx($)){const B=d[$.output_index];B!=null&&(g.enqueue({type:"tool-input-delta",id:B.toolCallId,delta:'"}'}),g.enqueue({type:"tool-input-end",id:B.toolCallId}),g.enqueue({type:"tool-call",toolCallId:B.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:$.code,containerId:B.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Px($))h=$.response.id,g.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(xx($))g.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(I=(x=t.providerOptions)==null?void 0:x.openai)!=null&&I.logprobs&&$.logprobs&&p.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const B=m[$.item_id];B.summaryParts[$.summary_index]="active";for(const W of Object.keys(B.summaryParts))B.summaryParts[W]==="can-conclude"&&(g.enqueue({type:"reasoning-end",id:`${$.item_id}:${W}`,providerMetadata:{[l]:{itemId:$.item_id}}}),B.summaryParts[W]="concluded");g.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id,reasoningEncryptedContent:(P=(A=m[$.item_id])==null?void 0:A.encryptedContent)!=null?P:null}}})}}else $.type==="response.reasoning_summary_text.delta"?g.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[l]:{itemId:$.item_id}}}):$.type==="response.reasoning_summary_part.done"?s?(g.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[l]:{itemId:$.item_id}}}),m[$.item_id].summaryParts[$.summary_index]="concluded"):m[$.item_id].summaryParts[$.summary_index]="can-conclude":Rx($)?(c=t_({finishReason:(D=$.response.incomplete_details)==null?void 0:D.reason,hasFunctionCall:w}),u.inputTokens=$.response.usage.input_tokens,u.outputTokens=$.response.usage.output_tokens,u.totalTokens=$.response.usage.input_tokens+$.response.usage.output_tokens,u.reasoningTokens=(V=(U=$.response.usage.output_tokens_details)==null?void 0:U.reasoning_tokens)!=null?V:void 0,u.cachedInputTokens=(fe=(se=$.response.usage.input_tokens_details)==null?void 0:se.cached_tokens)!=null?fe:void 0,typeof $.response.service_tier=="string"&&(y=$.response.service_tier)):Nx($)?(f.push($.annotation),$.annotation.type==="url_citation"?g.enqueue({type:"source",sourceType:"url",id:(_e=(re=(de=i.config).generateId)==null?void 0:re.call(de))!=null?_e:Xt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"&&g.enqueue({type:"source",sourceType:"document",id:(F=(O=(H=i.config).generateId)==null?void 0:O.call(H))!=null?F:Xt(),mediaType:"text/plain",title:(E=(q=$.annotation.quote)!=null?q:$.annotation.filename)!=null?E:"Document",filename:(R=$.annotation.filename)!=null?R:$.annotation.file_id,...$.annotation.file_id?{providerMetadata:{[l]:{fileId:$.annotation.file_id}}}:{}})):Lx($)&&g.enqueue({type:"error",error:$})},flush(_){const g={[l]:{responseId:h}};p.length>0&&(g[l].logprobs=p),y!==void 0&&(g[l].serviceTier=y),_.enqueue({type:"finish",finishReason:c,usage:u,providerMetadata:g})}})),request:{body:e},response:{headers:o}}}};function xx(t){return t.type==="response.output_text.delta"}function Ix(t){return t.type==="response.output_item.done"}function Rx(t){return t.type==="response.completed"||t.type==="response.incomplete"}function Px(t){return t.type==="response.created"}function Ox(t){return t.type==="response.function_call_arguments.delta"}function Ax(t){return t.type==="response.code_interpreter_call_code.delta"}function Mx(t){return t.type==="response.code_interpreter_call_code.done"}function n_(t){return t.type==="response.output_item.added"}function Nx(t){return t.type==="response.output_text.annotation.added"}function Lx(t){return t.type==="error"}function s_(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}var jx=vt(()=>Ne(C({instructions:v().nullish(),speed:L().min(.25).max(4).default(1).nullish()}))),qx=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:n,instructions:s,language:o,providerOptions:a}){const i=[],l=await Qr({provider:"openai",providerOptions:a,schema:jx}),c={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:n,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const p in u){const h=u[p];h!==void 0&&(c[p]=h)}}return o&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(t){var e,r,n;const s=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{requestBody:o,warnings:a}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:c}=await Rr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),body:o,failedResponseHandler:vr,successfulResponseHandler:j$(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(o)},response:{timestamp:s,modelId:this.modelId,headers:l,body:c}}}},zx=vt(()=>Ne(C({text:v(),language:v().nullish(),duration:L().nullish(),words:N(C({word:v(),start:L(),end:L()})).nullish(),segments:N(C({id:L(),seek:L(),start:L(),end:L(),text:v(),tokens:N(L()),temperature:L(),avg_logprob:L(),compression_ratio:L(),no_speech_prob:L()})).nullish()}))),Dx=vt(()=>Ne(C({include:N(v()).optional(),language:v().optional(),prompt:v().optional(),temperature:L().min(0).max(1).default(0).optional(),timestampGranularities:N(Ce(["word","segment"])).default(["segment"]).optional()}))),o_={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"},Ux=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const n=[],s=await Qr({provider:"openai",providerOptions:r,schema:Dx}),o=new FormData,a=t instanceof Uint8Array?new Blob([t]):new Blob([PE(t)]);o.append("model",this.modelId);const i=T$(e);if(o.append("file",new File([a],"audio",{type:e}),`audio.${i}`),s){const l={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const p of u)o.append(`${c}[]`,String(p));else o.append(c,String(u))}return{formData:o,warnings:n}}async doGenerate(t){var e,r,n,s,o,a,i,l;const c=(n=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?n:new Date,{formData:u,warnings:p}=await this.getArgs(t),{value:h,responseHeaders:d,rawValue:f}=await N$({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:gr(this.config.headers(),t.headers),formData:u,failedResponseHandler:vr,successfulResponseHandler:is(zx),abortSignal:t.abortSignal,fetch:this.config.fetch}),w=h.language!=null&&h.language in o_?o_[h.language]:void 0;return{text:h.text,segments:(i=(a=(s=h.segments)==null?void 0:s.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?a:(o=h.words)==null?void 0:o.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:w,durationInSeconds:(l=h.duration)!=null?l:void 0,warnings:p,response:{timestamp:c,modelId:this.modelId,headers:d,body:f}}}},Zx="2.0.88";function a_(t={}){var e,r;const n=(e=AE(S$({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",s=(r=t.name)!=null?r:"openai",o=()=>Av({Authorization:`Bearer ${k$({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${Zx}`),a=w=>new zE(w,{provider:`${s}.chat`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),i=w=>new FE(w,{provider:`${s}.completion`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),l=w=>new BE(w,{provider:`${s}.embedding`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),c=w=>new KE(w,{provider:`${s}.image`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),u=w=>new Ux(w,{provider:`${s}.transcription`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),p=w=>new qx(w,{provider:`${s}.speech`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch}),h=w=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(w)},d=w=>new Ex(w,{provider:`${s}.responses`,url:({path:m})=>`${n}${m}`,headers:o,fetch:t.fetch,fileIdPrefixes:["file-"]}),f=function(w){return h(w)};return f.languageModel=h,f.chat=a,f.completion=i,f.responses=d,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=u,f.transcriptionModel=u,f.speech=p,f.speechModel=p,f.tools=wx,f}a_();function ko(t){var e,r;return(r=(e=t?.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function Fx(t){const e=[];for(const{role:r,content:n,...s}of t){const o=ko({...s});switch(r){case"system":{e.push({role:"system",content:n,...o});break}case"user":{if(n.length===1&&n[0].type==="text"){e.push({role:"user",content:n[0].text,...ko(n[0])});break}e.push({role:"user",content:n.map(a=>{const i=ko(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${iT(a.data)}`},...i}}else throw new Wt({functionality:`file part media type ${a.mediaType}`})}}),...o});break}case"assistant":{let a="";const i=[];for(const l of n){const c=ko(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}e.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...o});break}case"tool":{for(const a of n){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=ko(a);e.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return e}function i_({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function l_(t){switch(t){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 Ku=C({user:v().optional(),reasoningEffort:v().optional(),textVerbosity:v().optional()}),Vx=C({error:C({message:v(),type:v().nullish(),param:ht().nullish(),code:ce([v(),L()]).nullish()})}),Hx={errorSchema:Vx,errorToMessage:t=>t.error.message};function Bx({tools:t,toolChoice:e}){t=t?.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const o of t)o.type==="provider-defined"?r.push({type:"unsupported-tool",tool:o}):n.push({type:"function",function:{name:o.name,description:o.description,parameters:o.inputSchema}});if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const o=s;throw new Wt({functionality:`tool choice type: ${o}`})}}}var Jx=class{constructor(t,e){this.specificationVersion="v2";var r,n;this.modelId=t,this.config=e;const s=(r=e.errorStructure)!=null?r:Hx;this.chunkSchema=Wx(s.errorSchema),this.failedResponseHandler=bn(s),this.supportsStructuredOutputs=(n=e.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:n,topK:s,frequencyPenalty:o,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:p,tools:h}){var d,f,w,m;const y=[],_=Object.assign((d=await Qm({provider:"openai-compatible",providerOptions:i,schema:Ku}))!=null?d:{},(f=await Qm({provider:this.providerOptionsName,providerOptions:i,schema:Ku}))!=null?f:{});s!=null&&y.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:g,toolChoice:b,toolWarnings:k}=Bx({tools:h,toolChoice:p});return{args:{model:this.modelId,user:_.user,max_tokens:e,temperature:r,top_p:n,frequency_penalty:o,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(w=c.name)!=null?w:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((m=i?.[this.providerOptionsName])!=null?m:{}).filter(([S])=>!Object.keys(Ku.shape).includes(S))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:Fx(t),tools:g,tool_choice:b},warnings:[...y,...k]}}async doGenerate(t){var e,r,n,s,o,a,i,l,c,u,p,h,d,f,w,m,y;const{args:_,warnings:g}=await this.getArgs({...t}),b=JSON.stringify(_),{responseHeaders:k,value:S,rawValue:T}=await Xn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Yn(this.config.headers(),t.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:es(Gx),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=S.choices[0],I=[],A=x.message.content;A!=null&&A.length>0&&I.push({type:"text",text:A});const P=(e=x.message.reasoning_content)!=null?e:x.message.reasoning;if(P!=null&&P.length>0&&I.push({type:"reasoning",text:P}),x.message.tool_calls!=null)for(const V of x.message.tool_calls)I.push({type:"tool-call",toolCallId:(r=V.id)!=null?r:io(),toolName:V.function.name,input:V.function.arguments});const D={[this.providerOptionsName]:{},...await((s=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:s.call(n,{parsedBody:T}))},U=(o=S.usage)==null?void 0:o.completion_tokens_details;return U?.accepted_prediction_tokens!=null&&(D[this.providerOptionsName].acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(D[this.providerOptionsName].rejectedPredictionTokens=U?.rejected_prediction_tokens),{content:I,finishReason:l_(x.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=S.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(p=(u=S.usage)==null?void 0:u.total_tokens)!=null?p:void 0,reasoningTokens:(f=(d=(h=S.usage)==null?void 0:h.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(y=(m=(w=S.usage)==null?void 0:w.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?y:void 0},providerMetadata:D,request:{body:b},response:{...i_(S),headers:k,body:T},warnings:g}}async doStream(t){var e;const{args:r,warnings:n}=await this.getArgs({...t}),s={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},o=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:a,value:i}=await Xn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Yn(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:e2(this.chunkSchema),abortSignal:t.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 p=!0;const h=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:n})},transform(w,m){var y,_,g,b,k,S,T,x,I,A,P,D,U;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:w.rawValue}),!w.success){c="error",m.enqueue({type:"error",error:w.error});return}const V=w.value;if(o?.processChunk(w.rawValue),"error"in V){c="error",m.enqueue({type:"error",error:V.error.message});return}if(p&&(p=!1,m.enqueue({type:"response-metadata",...i_(V)})),V.usage!=null){const{prompt_tokens:re,completion_tokens:_e,total_tokens:H,prompt_tokens_details:O,completion_tokens_details:F}=V.usage;u.promptTokens=re??void 0,u.completionTokens=_e??void 0,u.totalTokens=H??void 0,F?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=F?.reasoning_tokens),F?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=F?.accepted_prediction_tokens),F?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=F?.rejected_prediction_tokens),O?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=O?.cached_tokens)}const se=V.choices[0];if(se?.finish_reason!=null&&(c=l_(se.finish_reason)),se?.delta==null)return;const fe=se.delta,de=(y=fe.reasoning_content)!=null?y:fe.reasoning;if(de&&(d||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:de})),fe.content&&(f||(m.enqueue({type:"text-start",id:"txt-0"}),f=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:fe.content})),fe.tool_calls!=null)for(const re of fe.tool_calls){const _e=re.index;if(l[_e]==null){if(re.id==null)throw new so({data:re,message:"Expected 'id' to be a string."});if(((_=re.function)==null?void 0:_.name)==null)throw new so({data:re,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:re.id,toolName:re.function.name}),l[_e]={id:re.id,type:"function",function:{name:re.function.name,arguments:(g=re.function.arguments)!=null?g:""},hasFinished:!1};const O=l[_e];((b=O.function)==null?void 0:b.name)!=null&&((k=O.function)==null?void 0:k.arguments)!=null&&(O.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:O.id,delta:O.function.arguments}),Ym(O.function.arguments)&&(m.enqueue({type:"tool-input-end",id:O.id}),m.enqueue({type:"tool-call",toolCallId:(S=O.id)!=null?S:io(),toolName:O.function.name,input:O.function.arguments}),O.hasFinished=!0));continue}const H=l[_e];H.hasFinished||(((T=re.function)==null?void 0:T.arguments)!=null&&(H.function.arguments+=(I=(x=re.function)==null?void 0:x.arguments)!=null?I:""),m.enqueue({type:"tool-input-delta",id:H.id,delta:(A=re.function.arguments)!=null?A:""}),((P=H.function)==null?void 0:P.name)!=null&&((D=H.function)==null?void 0:D.arguments)!=null&&Ym(H.function.arguments)&&(m.enqueue({type:"tool-input-end",id:H.id}),m.enqueue({type:"tool-call",toolCallId:(U=H.id)!=null?U:io(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0))}},flush(w){var m,y,_,g,b,k;d&&w.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&w.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(x=>!x.hasFinished))w.enqueue({type:"tool-input-end",id:T.id}),w.enqueue({type:"tool-call",toolCallId:(m=T.id)!=null?m:io(),toolName:T.function.name,input:T.function.arguments});const S={[h]:{},...o?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(S[h].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(S[h].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),w.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(y=u.promptTokens)!=null?y:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(g=u.totalTokens)!=null?g:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(k=u.promptTokensDetails.cachedTokens)!=null?k:void 0},providerMetadata:S})}})),request:{body:s},response:{headers:a}}}},c_=C({prompt_tokens:L().nullish(),completion_tokens:L().nullish(),total_tokens:L().nullish(),prompt_tokens_details:C({cached_tokens:L().nullish()}).nullish(),completion_tokens_details:C({reasoning_tokens:L().nullish(),accepted_prediction_tokens:L().nullish(),rejected_prediction_tokens:L().nullish()}).nullish()}).nullish(),Gx=C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({message:C({role:j("assistant").nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:N(C({id:v().nullish(),function:C({name:v(),arguments:v()})})).nullish()}),finish_reason:v().nullish()})),usage:c_}),Wx=t=>ce([C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({delta:C({role:Ce(["assistant"]).nullish(),content:v().nullish(),reasoning_content:v().nullish(),reasoning:v().nullish(),tool_calls:N(C({index:L(),id:v().nullish(),function:C({name:v().nullish(),arguments:v().nullish()})})).nullish()}).nullish(),finish_reason:v().nullish()})),usage:c_}),t]);C({echo:ge().optional(),logitBias:Se(v(),L()).optional(),suffix:v().optional(),user:v().optional()});var Kx=C({prompt_tokens:L(),completion_tokens:L(),total_tokens:L()});C({id:v().nullish(),created:L().nullish(),model:v().nullish(),choices:N(C({text:v(),finish_reason:v()})),usage:Kx.nullish()}),C({dimensions:L().optional(),user:v().optional()}),C({data:N(C({embedding:N(L())})),usage:C({prompt_tokens:L()}).nullish(),providerMetadata:Se(v(),Se(v(),ht())).optional()}),C({data:N(C({b64_json:v()}))});var u_=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},Yx={extractMetadata:async({parsedBody:t})=>{const e=await Kt({value:t,schema:Qx});return!e.success||e.value.usage==null?void 0:u_(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,n;const s=await Kt({value:e,schema:Xx});s.success&&((n=(r=s.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&s.value.usage&&(t=s.value.usage)},buildMetadata:()=>u_(t)}}},d_=C({prompt_cache_hit_tokens:L().nullish(),prompt_cache_miss_tokens:L().nullish()}),Qx=C({usage:d_.nullish()}),Xx=C({choices:N(C({finish_reason:v().nullish()})).nullish(),usage:d_.nullish()}),eI="1.0.30";function p_(t={}){var e;const r=i2((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),n=()=>Wr({Authorization:`Bearer ${rS({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${eI}`);class s extends Jx{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const h=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:h}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const o=i=>new s(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:t.fetch,metadataExtractor:Yx}),a=i=>o(i);return a.languageModel=o,a.chat=o,a.textEmbeddingModel=i=>{throw new Lm({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new Lm({modelId:i,modelType:"imageModel"})},a}p_();const f_=async t=>{const e={};try{const r=await t.listTools();for(const{name:n,description:s,inputSchema:o}of r.tools){const a=async(i,l)=>t.callTool({name:n,arguments:i},{signal:l?.abortSignal});e[n]=Xm({description:s,inputSchema:co({...o,properties:o.properties??{},additionalProperties:!1}),execute:a})}return e}catch(r){throw r}};function tI(t){const e=Object.entries(t);if(e.length===0)return"";let r=`
588
588
 
589
589
  # 工具调用
590
590
 
@@ -618,10 +618,10 @@ ${e}:`]}}function Jv({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??vo
618
618
  `,r+=`- 必须严格按照 XML 格式调用工具
619
619
  `,r+=`- arguments 必须是有效的 JSON 格式
620
620
  `,r+=`- 如果不需要调用工具,直接给出最终答案即可
621
- `,r}function h_(t,e){if(!t||typeof t!="string")return null;const r=t.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),s=JSON.parse(n),o=s.name||s.action||s.tool,a=s.arguments||s.args||s.input||{};if(o&&e[o])return{toolName:o,arguments:a}}catch{}return null}const rI={openai:a_,deepseek:p_};class nI{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],this.useReActMode=!1,!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const n=e.providerType;let s;typeof n=="string"?s=rI[n]:s=n,this.llm=s({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=e.useReActMode??!1}async _createOneClient(e){try{let r;if("type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Qs(new URL(e.url)):"type"in e&&e.type==="extension"?r=new Mc(e.sessionId):r=e,e.useAISdkClient??!1){const s=await h$({transport:r});return s.__transport__=r,s}else{const s=new k0({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await s.connect(r),s.__transport__=r,s}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){try{const r=e.__transport__;if(r&&r instanceof ro||r&&r instanceof Xs||r&&r instanceof Mc)return;await r?.terminateSession?.(),await r?.close?.(),await e?.close?.()}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([n,s])=>{const o=await this._createOneClient(s);return{serverName:n,client:o}}));this.mcpClients={},r.forEach(({serverName:n,client:s})=>{this.mcpClients[n]=s})}async _getClientTools(e,r){if(!e)return null;try{return typeof e.tools=="function"?await e.tools():await f_(e)}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 e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([n,s])=>{const o=await this._getClientTools(s,n);return{serverName:n,tools:o}}));this.mcpTools={},r.forEach(({serverName:n,tools:s})=>{const o=s&&typeof s=="object"?s:{};this.mcpTools[n]=o})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}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(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){if(this.mcpServers[e])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=n;const s=await this._getClientTools(n,e);return this.mcpTools[e]=s&&typeof s=="object"?s:{},this.mcpServers[e]=r,this.onUpdatedTools?.(),n}async removeMcpServer(e){if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[e];delete this.mcpTools[e],n&&Object.keys(n).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),this.onUpdatedTools?.()}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((n,s)=>({...n,...s}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(e,r,n){const s=tI(e);return n?`${n}${s}`:`你是一个智能助手,可以通过调用工具来完成任务。
622
- ${s}`}async _executeReActToolCall(e,r,n){const s=n[e];if(!s)return{success:!1,error:`工具 ${e} 不存在`};try{const o=s,a=o.execute||o.call;return typeof a!="function"?{success:!1,error:`工具 ${e} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(o){return{success:!1,error:o?.message||String(o)||"工具执行失败"}}}async _chatReAct(e,{model:r,maxSteps:n=5,...s}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o=this._tempMergeTools(s.tools);if(Object.keys(o).length===0)return this._chat(e,{model:r,maxSteps:n,...s});let i=[];s.message&&!s.messages?i.push({role:"user",content:s.message}):s.messages?i=[...s.messages]:i=[...this.messages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(o,l,s.system)},p=i[0]?.role==="system"?i:[u,...i];return e===ju?this._chatReActStream(p,o,l,n,s):this._chatReActNonStream(p,o,l,n,s)}_messageHasImage(e){return e&&Array.isArray(e)?e.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(e){if(!e||!e.content)return null;if(!Array.isArray(e.content))return e;const r=e.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...e,content:r}}_buildMessagesForModel(e,r,n=3){const s=[];e&&s.push(e);let o=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(o<n)a.unshift(l),o++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return s.push(...a),s}async _chatReActNonStream(e,r,n,s,o){let a=[...e];const i=e[0]?.role==="system"?e[0]:null,l=i?e.slice(1):e;let c=0;const u=o.maxImages??3;for(;c<s;){c++;const h=this._buildMessagesForModel(i,l,u),{tools:d,...f}=o,m=(await nv({model:this.llm(n),messages:h,...f})).text,y={role:"assistant",content:m};l.push(y),a.push(y);const _=h_(m,r);if(!_)return this.messages=a,{text:m,response:{messages:a}};const g=await this._executeReActToolCall(_.toolName,_.arguments,r),S={role:"user",content:`<tool_response>
621
+ `,r}function h_(t,e){if(!t||typeof t!="string")return null;const r=t.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),s=JSON.parse(n),o=s.name||s.action||s.tool,a=s.arguments||s.args||s.input||{};if(o&&e[o])return{toolName:o,arguments:a}}catch{}return null}const rI={openai:a_,deepseek:p_};class nI{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],this.useReActMode=!1,!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const n=e.providerType;let s;typeof n=="string"?s=rI[n]:s=n,this.llm=s({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=e.useReActMode??!1}async _createOneClient(e){try{let r;if("type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Qs(new URL(e.url)):"type"in e&&e.type==="extension"?r=new T0(e.sessionId):r=e,e.useAISdkClient??!1){const s=await h$({transport:r});return s.__transport__=r,s}else{const s=new b0({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await s.connect(r),s.__transport__=r,s}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){try{const r=e.__transport__;if(r&&r instanceof ro||r&&r instanceof Xs)return;await r?.terminateSession?.(),await r?.close?.(),await e?.close?.()}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([n,s])=>{const o=await this._createOneClient(s);return{serverName:n,client:o}}));this.mcpClients={},r.forEach(({serverName:n,client:s})=>{this.mcpClients[n]=s})}async _getClientTools(e,r){if(!e)return null;try{return typeof e.tools=="function"?await e.tools():await f_(e)}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 e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([n,s])=>{const o=await this._getClientTools(s,n);return{serverName:n,tools:o}}));this.mcpTools={},r.forEach(({serverName:n,tools:s})=>{const o=s&&typeof s=="object"?s:{};this.mcpTools[n]=o})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}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(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){if(this.mcpServers[e])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=n;const s=await this._getClientTools(n,e);return this.mcpTools[e]=s&&typeof s=="object"?s:{},this.mcpServers[e]=r,this.onUpdatedTools?.(),n}async removeMcpServer(e){if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[e];delete this.mcpTools[e],n&&Object.keys(n).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),this.onUpdatedTools?.()}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((n,s)=>({...n,...s}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(n=>{delete r[n]}),r}_generateReActSystemPrompt(e,r,n){const s=tI(e);return n?`${n}${s}`:`你是一个智能助手,可以通过调用工具来完成任务。
622
+ ${s}`}async _executeReActToolCall(e,r,n){const s=n[e];if(!s)return{success:!1,error:`工具 ${e} 不存在`};try{const o=s,a=o.execute||o.call;return typeof a!="function"?{success:!1,error:`工具 ${e} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(o){return{success:!1,error:o?.message||String(o)||"工具执行失败"}}}async _chatReAct(e,{model:r,maxSteps:n=5,...s}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o=this._tempMergeTools(s.tools);if(Object.keys(o).length===0)return this._chat(e,{model:r,maxSteps:n,...s});let i=[];s.message&&!s.messages?i.push({role:"user",content:s.message}):s.messages?i=[...s.messages]:i=[...this.messages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(o,l,s.system)},p=i[0]?.role==="system"?i:[u,...i];return e===Lu?this._chatReActStream(p,o,l,n,s):this._chatReActNonStream(p,o,l,n,s)}_messageHasImage(e){return e&&Array.isArray(e)?e.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(e){if(!e||!e.content)return null;if(!Array.isArray(e.content))return e;const r=e.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...e,content:r}}_buildMessagesForModel(e,r,n=3){const s=[];e&&s.push(e);let o=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(o<n)a.unshift(l),o++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return s.push(...a),s}async _chatReActNonStream(e,r,n,s,o){let a=[...e];const i=e[0]?.role==="system"?e[0]:null,l=i?e.slice(1):e;let c=0;const u=o.maxImages??3;for(;c<s;){c++;const h=this._buildMessagesForModel(i,l,u),{tools:d,...f}=o,m=(await nv({model:this.llm(n),messages:h,...f})).text,y={role:"assistant",content:m};l.push(y),a.push(y);const _=h_(m,r);if(!_)return this.messages=a,{text:m,response:{messages:a}};const g=await this._executeReActToolCall(_.toolName,_.arguments,r),S={role:"user",content:`<tool_response>
623
623
  ${g.success?JSON.stringify(g.result):`工具执行失败 - ${g.error}`}
624
- </tool_response>`};l.push(S),a.push(S)}return this.messages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(e,r,n,s,o){const a=this,i=this.llm(n);let l,c;const u=new Promise((h,d)=>{l=h,c=d});return{fullStream:new ReadableStream({async start(h){let d=[...e];const f=e[0]?.role==="system"?e[0]:null,w=f?e.slice(1):[...e];let m=0,y="";const _=o.maxImages??3;try{for(;m<s;){m++;const g=a._buildMessagesForModel(f,w,_),{tools:b,...k}=o;delete k.system;const S=await ju({...k,model:i,messages:g});let T="";for await(const re of S.fullStream)re.type==="text-delta"?(T+=re.text||"",h.enqueue({type:"text-delta",text:re.text})):re.type==="text-start"?h.enqueue({type:"text-start"}):re.type==="text-end"||h.enqueue(re);y+=T;const x={role:"assistant",content:y};w.push(x),d.push(x);const I=h_(y,r);if(!I){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}if(I.toolName==="computer"&&I.arguments?.action==="terminate"){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}const A=`react-${Date.now()}`;h.enqueue({type:"tool-input-start",id:A,toolName:I.toolName});const P=JSON.stringify(I.arguments,null,2);h.enqueue({type:"tool-input-delta",id:A,delta:P});const D=await a._executeReActToolCall(I.toolName,I.arguments,r);let U,V=D.result;if(D.success&&D.result&&typeof D.result=="object"&&D.result.screenshot){U=D.result.screenshot;const{screenshot:re,..._e}=D.result;V=_e}let se="";D.success?V&&Array.isArray(V.content)&&V.content.length>0&&V.content[0].text?se=V.content[0].text:se=JSON.stringify(V):se=`工具执行失败 - ${D.error}`;let fe=`<tool_response>
624
+ </tool_response>`};l.push(S),a.push(S)}return this.messages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(e,r,n,s,o){const a=this,i=this.llm(n);let l,c;const u=new Promise((h,d)=>{l=h,c=d});return{fullStream:new ReadableStream({async start(h){let d=[...e];const f=e[0]?.role==="system"?e[0]:null,w=f?e.slice(1):[...e];let m=0,y="";const _=o.maxImages??3;try{for(;m<s;){m++;const g=a._buildMessagesForModel(f,w,_),{tools:b,...k}=o;delete k.system,delete k.onFinish;const S=await Lu({...k,model:i,messages:g});let T="";for await(const re of S.fullStream)re.type==="text-delta"?(T+=re.text||"",h.enqueue({type:"text-delta",text:re.text})):re.type==="text-start"?h.enqueue({type:"text-start"}):re.type==="text-end"||h.enqueue(re);y+=T;const x={role:"assistant",content:y};w.push(x),d.push(x);const I=h_(y,r);if(!I){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}if(I.toolName==="computer"&&I.arguments?.action==="terminate"){h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d});return}const A=`react-${Date.now()}`;h.enqueue({type:"tool-input-start",id:A,toolName:I.toolName});const P=JSON.stringify(I.arguments,null,2);h.enqueue({type:"tool-input-delta",id:A,delta:P});const D=await a._executeReActToolCall(I.toolName,I.arguments,r);let U,V=D.result;if(D.success&&D.result&&typeof D.result=="object"&&D.result.screenshot){U=D.result.screenshot;const{screenshot:re,..._e}=D.result;V=_e}let se="";D.success?V&&Array.isArray(V.content)&&V.content.length>0&&V.content[0].text?se=V.content[0].text:se=JSON.stringify(V):se=`工具执行失败 - ${D.error}`;let fe=`<tool_response>
625
625
  ${se}
626
626
  </tool_response>`;U&&(fe+=`
627
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),h.enqueue({type:"tool-result",toolCallId:A,result:fe});const de=U?{role:"user",content:[{type:"text",text:fe},{type:"image",image:U}]}:{role:"user",content:fe};w.push(de),d.push(de),y=""}h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d})}catch(g){h.error(g),c(g)}}}),response:u}}async _chat(e,{model:r,maxSteps:n=5,...s}){if(this.useReActMode)return this._chatReAct(e,{model:r,maxSteps:n,...s});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o={model:this.llm(r),stopWhen:Au(n),...s,tools:this._tempMergeTools(s.tools)};s.message&&!s.messages&&(this.messages.push({role:"user",content:s.message}),o.messages=[...this.messages]);const a=e(o);return a?.response?.then(i=>{this.messages.push(...i.messages)}),a}async chat(e){return this._chat(nv,e)}async chatStream(e){return this._chat(ju,e)}}Pe.AgentModelProvider=nI,Pe.Ajv=my,Pe.AuthClientProvider=I6,Pe.ContentScriptServerTransport=n5,Pe.ExtensionClientTransport=Mc,Pe.ExtensionPageServerTransport=r5,Pe.InMemoryTransport=ro,Pe.QrCode=om,Pe.ResourceTemplate=D6,Pe.UriTemplate=xr,Pe.WebMcpClient=k0,Pe.WebMcpServer=H6,Pe.completable=O6,Pe.createMessageChannelClientTransport=Q6,Pe.createMessageChannelPairTransport=J6,Pe.createMessageChannelServerTransport=B6,Pe.createRemoter=N5,Pe.createSSEClientTransport=K6,Pe.createStreamableHTTPClientTransport=Y6,Pe.getAISDKTools=f_,Pe.getDisplayName=V6,Pe.isMcpClient=t5,Pe.isMcpServer=W6,Pe.isMessageChannelClientTransport=e5,Pe.isMessageChannelServerTransport=G6,Pe.isSSEClientTransport=X6,Pe.isStreamableHTTPClientTransport=S0,Pe.z=_1,Object.defineProperty(Pe,Symbol.toStringTag,{value:"Module"})}));
627
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),h.enqueue({type:"tool-result",toolCallId:A,result:fe});const de=U?{role:"user",content:[{type:"text",text:fe},{type:"image",image:U}]}:{role:"user",content:fe};w.push(de),d.push(de),y=""}h.enqueue({type:"text-end"}),h.close(),a.messages=d,l({messages:d})}catch(g){h.error(g),c(g)}}}),response:u}}async _chat(e,{model:r,maxSteps:n=5,...s}){if(this.useReActMode)return this._chatReAct(e,{model:r,maxSteps:n,...s});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const o={model:this.llm(r),stopWhen:Ou(n),...s,tools:this._tempMergeTools(s.tools)};s.message&&!s.messages&&(this.messages.push({role:"user",content:s.message}),o.messages=[...this.messages]);const a=e(o);return a?.response?.then(i=>{this.messages.push(...i.messages)}),a}async chat(e){return this._chat(nv,e)}async chatStream(e){return this._chat(Lu,e)}}Pe.AgentModelProvider=nI,Pe.Ajv=my,Pe.AuthClientProvider=I6,Pe.ContentScriptServerTransport=n5,Pe.ExtensionClientTransport=T0,Pe.ExtensionPageServerTransport=r5,Pe.InMemoryTransport=ro,Pe.QrCode=om,Pe.ResourceTemplate=D6,Pe.UriTemplate=xr,Pe.WebMcpClient=b0,Pe.WebMcpServer=H6,Pe.completable=O6,Pe.createMessageChannelClientTransport=Q6,Pe.createMessageChannelPairTransport=J6,Pe.createMessageChannelServerTransport=B6,Pe.createRemoter=N5,Pe.createSSEClientTransport=K6,Pe.createStreamableHTTPClientTransport=Y6,Pe.getAISDKTools=f_,Pe.getDisplayName=V6,Pe.isMcpClient=t5,Pe.isMcpServer=W6,Pe.isMessageChannelClientTransport=e5,Pe.isMessageChannelServerTransport=G6,Pe.isSSEClientTransport=X6,Pe.isStreamableHTTPClientTransport=k0,Pe.z=_1,Object.defineProperty(Pe,Symbol.toStringTag,{value:"Module"})}));